code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* This is where the magic happens. The Game object is the heart of your game,
* providing quick access to common functions and handling the boot process.
*
* "Hell, there are no rules here - we're trying to accomplish something."
* Thomas A. Edison
*
* @class Phaser.Game
* @constructor
* @param {object} [gameConfig={}] - The game configuration object
*/
Phaser.Game = function (gameConfig) {
/**
* @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
* @readonly
*/
this.id = Phaser.GAMES.push(this) - 1;
/**
* @property {object} config - The Phaser.Game configuration object.
*/
this.config = null;
/**
* @property {object} physicsConfig - The Phaser.Physics.World configuration object.
*/
this.physicsConfig = null;
/**
* @property {string|HTMLElement} parent - The Games DOM parent.
* @default
*/
this.parent = '';
/**
* The current Game Width in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} width
* @readonly
* @default
*/
this.width = 800;
/**
* The current Game Height in pixels.
*
* _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
*
* @property {integer} height
* @readonly
* @default
*/
this.height = 600;
/**
* The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object.
*
* @property {integer} resolution
* @readonly
* @default
*/
this.resolution = 1;
/**
* @property {integer} _width - Private internal var.
* @private
*/
this._width = 800;
/**
* @property {integer} _height - Private internal var.
* @private
*/
this._height = 600;
/**
* @property {boolean} transparent - Use a transparent canvas background or not.
* @default
*/
this.transparent = false;
/**
* @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
* @default
*/
this.antialias = false;
/**
* @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
* @default
*/
this.preserveDrawingBuffer = false;
/**
* Clear the Canvas each frame before rendering the display list.
* You can set this to `false` to gain some performance if your game always contains a background that completely fills the display.
* @property {boolean} clearBeforeRender
* @default
*/
this.clearBeforeRender = true;
/**
* @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
* @protected
*/
this.renderer = null;
/**
* @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS.
* @readonly
*/
this.renderType = Phaser.AUTO;
/**
* @property {Phaser.StateManager} state - The StateManager.
*/
this.state = null;
/**
* @property {boolean} isBooted - Whether the game engine is booted, aka available.
* @readonly
*/
this.isBooted = false;
/**
* @property {boolean} isRunning - Is game running or paused?
* @readonly
*/
this.isRunning = false;
/**
* @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
* @protected
*/
this.raf = null;
/**
* @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
*/
this.add = null;
/**
* @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
*/
this.make = null;
/**
* @property {Phaser.Cache} cache - Reference to the assets cache.
*/
this.cache = null;
/**
* @property {Phaser.Input} input - Reference to the input manager
*/
this.input = null;
/**
* @property {Phaser.Loader} load - Reference to the assets loader.
*/
this.load = null;
/**
* @property {Phaser.Math} math - Reference to the math helper.
*/
this.math = null;
/**
* @property {Phaser.Net} net - Reference to the network class.
*/
this.net = null;
/**
* @property {Phaser.ScaleManager} scale - The game scale manager.
*/
this.scale = null;
/**
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
*/
this.sound = null;
/**
* @property {Phaser.Stage} stage - Reference to the stage.
*/
this.stage = null;
/**
* @property {Phaser.Time} time - Reference to the core game clock.
*/
this.time = null;
/**
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
*/
this.tweens = null;
/**
* @property {Phaser.World} world - Reference to the world.
*/
this.world = null;
/**
* @property {Phaser.Physics} physics - Reference to the physics manager.
*/
this.physics = null;
/**
* @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
*/
this.plugins = null;
/**
* @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
*/
this.rnd = null;
/**
* @property {Phaser.Device} device - Contains device information and capabilities.
*/
this.device = Phaser.Device;
/**
* @property {Phaser.Camera} camera - A handy reference to world.camera.
*/
this.camera = null;
/**
* @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
*/
this.canvas = null;
/**
* @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
*/
this.context = null;
/**
* @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
*/
this.debug = null;
/**
* @property {Phaser.Particles} particles - The Particle Manager.
*/
this.particles = null;
/**
* @property {Phaser.Create} create - The Asset Generator.
*/
this.create = null;
/**
* If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
* You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
* Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
* @property {boolean} lockRender
* @default
*/
this.lockRender = false;
/**
* @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
* @default
* @readonly
*/
this.stepping = false;
/**
* @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
* @default
* @readonly
*/
this.pendingStep = false;
/**
* @property {number} stepCount - When stepping is enabled this contains the current step cycle.
* @default
* @readonly
*/
this.stepCount = 0;
/**
* @property {Phaser.Signal} onPause - This event is fired when the game pauses.
*/
this.onPause = null;
/**
* @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
*/
this.onResume = null;
/**
* @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
*/
this.onBlur = null;
/**
* @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
*/
this.onFocus = null;
/**
* @property {boolean} _paused - Is game paused?
* @private
*/
this._paused = false;
/**
* @property {boolean} _codePaused - Was the game paused via code or a visibility change?
* @private
*/
this._codePaused = false;
/**
* The ID of the current/last logic update applied this render frame, starting from 0.
* The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
* @property {integer} currentUpdateID
* @protected
*/
this.currentUpdateID = 0;
/**
* Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed).
* @property {integer} updatesThisFrame
* @protected
*/
this.updatesThisFrame = 1;
/**
* @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
* @private
*/
this._deltaTime = 0;
/**
* @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
* @private
*/
this._lastCount = 0;
/**
* @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
* @private
*/
this._spiraling = 0;
/**
* @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
* @private
*/
this._kickstart = true;
/**
* If the game is struggling to maintain the desired FPS, this signal will be dispatched.
* The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
* @property {Phaser.Signal} fpsProblemNotifier
* @public
*/
this.fpsProblemNotifier = new Phaser.Signal();
/**
* @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly.
*/
this.forceSingleUpdate = true;
/**
* @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
* @private
*/
this._nextFpsNotification = 0;
// Parse the configuration object
if (typeof gameConfig !== 'object')
{
throw new Error('Missing game configuration object: ' + gameConfig);
}
this.parseConfig(gameConfig);
this.device.whenReady(this.boot, this);
return this;
};
Phaser.Game.prototype = {
/**
* Parses a Game configuration object.
*
* @method Phaser.Game#parseConfig
* @protected
*/
parseConfig: function (config) {
this.config = config;
if (config['enableDebug'] === undefined)
{
this.config.enableDebug = true;
}
if (config['width'])
{
this._width = config['width'];
}
if (config['height'])
{
this._height = config['height'];
}
if (config['renderer'])
{
this.renderType = config['renderer'];
}
if (config['parent'])
{
this.parent = config['parent'];
}
if (config['transparent'] !== undefined)
{
this.transparent = config['transparent'];
}
if (config['antialias'] !== undefined)
{
this.antialias = config['antialias'];
}
if (config['resolution'])
{
this.resolution = config['resolution'];
}
if (config['preserveDrawingBuffer'] !== undefined)
{
this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
}
if (config['clearBeforeRender'] !== undefined)
{
this.clearBeforeRender = config['clearBeforeRender'];
}
if (config['physicsConfig'])
{
this.physicsConfig = config['physicsConfig'];
}
var seed = [(Date.now() * Math.random()).toString()];
if (config['seed'])
{
seed = config['seed'];
}
this.rnd = new Phaser.RandomDataGenerator(seed);
var state = null;
if (config['state'])
{
state = config['state'];
}
this.state = new Phaser.StateManager(this, state);
},
/**
* Initialize engine sub modules and start the game.
*
* @method Phaser.Game#boot
* @protected
*/
boot: function () {
if (this.isBooted)
{
return;
}
this.onPause = new Phaser.Signal();
this.onResume = new Phaser.Signal();
this.onBlur = new Phaser.Signal();
this.onFocus = new Phaser.Signal();
this.isBooted = true;
PIXI.game = this;
this.math = Phaser.Math;
this.scale = new Phaser.ScaleManager(this, this._width, this._height);
this.stage = new Phaser.Stage(this);
this.setUpRenderer();
this.world = new Phaser.World(this);
this.add = new Phaser.GameObjectFactory(this);
this.make = new Phaser.GameObjectCreator(this);
this.cache = new Phaser.Cache(this);
this.load = new Phaser.Loader(this);
this.time = new Phaser.Time(this);
this.tweens = new Phaser.TweenManager(this);
this.input = new Phaser.Input(this);
this.sound = new Phaser.SoundManager(this);
this.physics = new Phaser.Physics(this, this.physicsConfig);
this.particles = new Phaser.Particles(this);
this.create = new Phaser.Create(this);
this.plugins = new Phaser.PluginManager(this);
this.net = new Phaser.Net(this);
this.time.boot();
this.stage.boot();
this.world.boot();
this.scale.boot();
this.input.boot();
this.sound.boot();
this.state.boot();
if (this.config['enableDebug'])
{
this.debug = new Phaser.Utils.Debug(this);
this.debug.boot();
}
else
{
this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} };
}
this.showDebugHeader();
this.isRunning = true;
if (this.config && this.config['forceSetTimeOut'])
{
this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
}
else
{
this.raf = new Phaser.RequestAnimationFrame(this, false);
}
this._kickstart = true;
if (window['focus'])
{
if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus))
{
window.focus();
}
}
this.raf.start();
},
/**
* Displays a Phaser version debug header in the console.
*
* @method Phaser.Game#showDebugHeader
* @protected
*/
showDebugHeader: function () {
if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner)
{
return;
}
var v = Phaser.VERSION;
var r = 'Canvas';
var a = 'HTML Audio';
var c = 1;
if (this.renderType === Phaser.WEBGL)
{
r = 'WebGL';
c++;
}
else if (this.renderType === Phaser.HEADLESS)
{
r = 'Headless';
}
if (this.device.webAudio)
{
a = 'WebAudio';
c++;
}
if (this.device.chrome)
{
var args = [
'%c %c %c Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
'background: #fb8cb3',
'background: #d44a52',
'color: #ffffff; background: #871905;',
'background: #d44a52',
'background: #fb8cb3',
'background: #ffffff'
];
for (var i = 0; i < 3; i++)
{
if (i < c)
{
args.push('color: #ff2424; background: #fff');
}
else
{
args.push('color: #959595; background: #fff');
}
}
console.log.apply(console, args);
}
else if (window['console'])
{
console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
}
},
/**
* Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
*
* @method Phaser.Game#setUpRenderer
* @protected
*/
setUpRenderer: function () {
if (this.config['canvas'])
{
this.canvas = this.config['canvas'];
}
else
{
this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true);
}
if (this.config['canvasStyle'])
{
this.canvas.style = this.config['canvasStyle'];
}
else
{
this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
}
if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL))
{
if (this.device.canvas)
{
// They requested Canvas and their browser supports it
this.renderType = Phaser.CANVAS;
this.renderer = new PIXI.CanvasRenderer(this);
this.context = this.renderer.context;
}
else
{
throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.');
}
}
else
{
// They requested WebGL and their browser supports it
this.renderType = Phaser.WEBGL;
this.renderer = new PIXI.WebGLRenderer(this);
this.context = null;
this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
}
if (this.device.cocoonJS)
{
this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false;
}
if (this.renderType !== Phaser.HEADLESS)
{
this.stage.smoothed = this.antialias;
Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
Phaser.Canvas.setTouchAction(this.canvas);
}
},
/**
* Handles WebGL context loss.
*
* @method Phaser.Game#contextLost
* @private
* @param {Event} event - The webglcontextlost event.
*/
contextLost: function (event) {
event.preventDefault();
this.renderer.contextLost = true;
},
/**
* Handles WebGL context restoration.
*
* @method Phaser.Game#contextRestored
* @private
*/
contextRestored: function () {
this.renderer.initContext();
this.cache.clearGLTextures();
this.renderer.contextLost = false;
},
/**
* The core game loop.
*
* @method Phaser.Game#update
* @protected
* @param {number} time - The current time as provided by RequestAnimationFrame.
*/
update: function (time) {
this.time.update(time);
if (this._kickstart)
{
this.updateLogic(this.time.desiredFpsMult);
// call the game render update exactly once every frame
this.updateRender(this.time.slowMotion * this.time.desiredFps);
this._kickstart = false;
return;
}
// if the logic time is spiraling upwards, skip a frame entirely
if (this._spiraling > 1 && !this.forceSingleUpdate)
{
// cause an event to warn the program that this CPU can't keep up with the current desiredFps rate
if (this.time.time > this._nextFpsNotification)
{
// only permit one fps notification per 10 seconds
this._nextFpsNotification = this.time.time + 10000;
// dispatch the notification signal
this.fpsProblemNotifier.dispatch();
}
// reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped
this._deltaTime = 0;
this._spiraling = 0;
// call the game render update exactly once every frame
this.updateRender(this.time.slowMotion * this.time.desiredFps);
}
else
{
// step size taking into account the slow motion speed
var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps;
// accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals
this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0);
// call the game update logic multiple times if necessary to "catch up" with dropped frames
// unless forceSingleUpdate is true
var count = 0;
this.updatesThisFrame = Math.floor(this._deltaTime / slowStep);
if (this.forceSingleUpdate)
{
this.updatesThisFrame = Math.min(1, this.updatesThisFrame);
}
while (this._deltaTime >= slowStep)
{
this._deltaTime -= slowStep;
this.currentUpdateID = count;
this.updateLogic(this.time.desiredFpsMult);
count++;
if (this.forceSingleUpdate && count === 1)
{
break;
}
else
{
this.time.refresh();
}
}
// detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly)
if (count > this._lastCount)
{
this._spiraling++;
}
else if (count < this._lastCount)
{
// looks like it caught up successfully, reset the spiral alert counter
this._spiraling = 0;
}
this._lastCount = count;
// call the game render update exactly once every frame unless we're playing catch-up from a spiral condition
this.updateRender(this._deltaTime / slowStep);
}
},
/**
* Updates all logic subsystems in Phaser. Called automatically by Game.update.
*
* @method Phaser.Game#updateLogic
* @protected
* @param {number} timeStep - The current timeStep value as determined by Game.update.
*/
updateLogic: function (timeStep) {
if (!this._paused && !this.pendingStep)
{
if (this.stepping)
{
this.pendingStep = true;
}
this.scale.preUpdate();
this.debug.preUpdate();
this.camera.preUpdate();
this.physics.preUpdate();
this.state.preUpdate(timeStep);
this.plugins.preUpdate(timeStep);
this.stage.preUpdate();
this.state.update();
this.stage.update();
this.tweens.update();
this.sound.update();
this.input.update();
this.physics.update();
this.particles.update();
this.plugins.update();
this.stage.postUpdate();
this.plugins.postUpdate();
}
else
{
// Scaling and device orientation changes are still reflected when paused.
this.scale.pauseUpdate();
this.state.pauseUpdate();
this.debug.preUpdate();
}
this.stage.updateTransform();
},
/**
* Runs the Render cycle.
* It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
* It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
* It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
* After this State.render is called. Any rendering that happens here will take place on-top of the display list.
* Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
* This method is called automatically by Game.update, you don't need to call it directly.
* Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
* Phaser will only render when this boolean is `false`.
*
* @method Phaser.Game#updateRender
* @protected
* @param {number} elapsedTime - The time elapsed since the last update.
*/
updateRender: function (elapsedTime) {
if (this.lockRender)
{
return;
}
this.state.preRender(elapsedTime);
if (this.renderType !== Phaser.HEADLESS)
{
this.renderer.render(this.stage);
this.plugins.render(elapsedTime);
this.state.render(elapsedTime);
}
this.plugins.postRender(elapsedTime);
},
/**
* Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
* Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
*
* @method Phaser.Game#enableStep
*/
enableStep: function () {
this.stepping = true;
this.pendingStep = false;
this.stepCount = 0;
},
/**
* Disables core game loop stepping.
*
* @method Phaser.Game#disableStep
*/
disableStep: function () {
this.stepping = false;
this.pendingStep = false;
},
/**
* When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
* This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
*
* @method Phaser.Game#step
*/
step: function () {
this.pendingStep = false;
this.stepCount++;
},
/**
* Nukes the entire game from orbit.
*
* Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins.
*
* Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM
* and resets the PIXI default renderer.
*
* @method Phaser.Game#destroy
*/
destroy: function () {
this.raf.stop();
this.state.destroy();
this.sound.destroy();
this.scale.destroy();
this.stage.destroy();
this.input.destroy();
this.physics.destroy();
this.plugins.destroy();
this.state = null;
this.sound = null;
this.scale = null;
this.stage = null;
this.input = null;
this.physics = null;
this.plugins = null;
this.cache = null;
this.load = null;
this.time = null;
this.world = null;
this.isBooted = false;
this.renderer.destroy(false);
Phaser.Canvas.removeFromDOM(this.canvas);
PIXI.defaultRenderer = null;
Phaser.GAMES[this.id] = null;
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gamePaused
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gamePaused: function (event) {
// If the game is already paused it was done via game code, so don't re-pause it
if (!this._paused)
{
this._paused = true;
this.time.gamePaused();
if (this.sound.muteOnPause)
{
this.sound.setMute();
}
this.onPause.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = true;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#gameResumed
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
gameResumed: function (event) {
// Game is paused, but wasn't paused via code, so resume it
if (this._paused && !this._codePaused)
{
this._paused = false;
this.time.gameResumed();
this.input.reset();
if (this.sound.muteOnPause)
{
this.sound.unsetMute();
}
this.onResume.dispatch(event);
// Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
if (this.device.cordova && this.device.iOS)
{
this.lockRender = false;
}
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusLoss
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusLoss: function (event) {
this.onBlur.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gamePaused(event);
}
},
/**
* Called by the Stage visibility handler.
*
* @method Phaser.Game#focusGain
* @param {object} event - The DOM event that caused the game to pause, if any.
* @protected
*/
focusGain: function (event) {
this.onFocus.dispatch(event);
if (!this.stage.disableVisibilityChange)
{
this.gameResumed(event);
}
}
};
Phaser.Game.prototype.constructor = Phaser.Game;
/**
* The paused state of the Game. A paused game doesn't update any of its subsystems.
* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
* @name Phaser.Game#paused
* @property {boolean} paused - Gets and sets the paused state of the Game.
*/
Object.defineProperty(Phaser.Game.prototype, "paused", {
get: function () {
return this._paused;
},
set: function (value) {
if (value === true)
{
if (this._paused === false)
{
this._paused = true;
this.sound.setMute();
this.time.gamePaused();
this.onPause.dispatch(this);
}
this._codePaused = true;
}
else
{
if (this._paused)
{
this._paused = false;
this.input.reset();
this.sound.unsetMute();
this.time.gameResumed();
this.onResume.dispatch(this);
}
this._codePaused = false;
}
}
});
/**
*
* "Deleted code is debugged code." - Jeff Sickel
*
* ヽ(〃^▽^〃)ノ
*
*/
| vpmedia/phaser2-lite | src/core/Game.js | JavaScript | mit | 31,942 |
module ActiveModelSerializers
module Adapter
class JsonApi
class Relationship
# {http://jsonapi.org/format/#document-resource-object-related-resource-links Document Resource Object Related Resource Links}
# {http://jsonapi.org/format/#document-links Document Links}
# {http://jsonapi.org/format/#document-resource-object-linkage Document Resource Relationship Linkage}
# {http://jsonapi.org/format/#document-meta Document Meta}
def initialize(parent_serializer, serializable_resource_options, association)
serializer = association.serializer
options = association.options
links = association.links
meta = association.meta
@object = parent_serializer.object
@scope = parent_serializer.scope
@association_options = options || {}
@serializable_resource_options = serializable_resource_options
@data = data_for(serializer)
@links = (links || {}).each_with_object({}) do |(key, value), hash|
result = Link.new(parent_serializer, value).as_json
hash[key] = result if result
end
@meta = meta.respond_to?(:call) ? parent_serializer.instance_eval(&meta) : meta
end
def as_json
hash = {}
hash[:data] = data if association_options[:include_data]
links = self.links
hash[:links] = links if links.any?
meta = self.meta
hash[:meta] = meta if meta
hash
end
protected
attr_reader :object, :scope, :data, :serializable_resource_options,
:association_options, :links, :meta
private
def data_for(serializer)
if serializer.respond_to?(:each)
serializer.map { |s| ResourceIdentifier.new(s, serializable_resource_options).as_json }
elsif association_options[:virtual_value]
association_options[:virtual_value]
elsif serializer && serializer.object
ResourceIdentifier.new(serializer, serializable_resource_options).as_json
end
end
end
end
end
end
| sixthedge/cellar | src/totem/api/vendor/active_model_serializers-0.10.2/lib/active_model_serializers/adapter/json_api/relationship.rb | Ruby | mit | 2,158 |
# -*- coding: utf-8 -*-
""" Request Management System - Controllers """
prefix = request.controller
resourcename = request.function
if prefix not in deployment_settings.modules:
session.error = T("Module disabled!")
redirect(URL(r=request, c="default", f="index"))
# Options Menu (available in all Functions' Views)
menu = [
[T("Home"), False, URL(r=request, f="index")],
[T("Requests"), False, URL(r=request, f="req"), [
[T("List"), False, URL(r=request, f="req")],
[T("Add"), False, URL(r=request, f="req", args="create")],
# @ToDo Search by priority, status, location
#[T("Search"), False, URL(r=request, f="req", args="search")],
]],
[T("All Requested Items"), False, URL(r=request, f="ritem")],
]
if session.rcvars:
if "hms_hospital" in session.rcvars:
hospital = db.hms_hospital
query = (hospital.id == session.rcvars["hms_hospital"])
selection = db(query).select(hospital.id, hospital.name, limitby=(0, 1)).first()
if selection:
menu_hospital = [
[selection.name, False, URL(r=request, c="hms", f="hospital", args=[selection.id])]
]
menu.extend(menu_hospital)
if "cr_shelter" in session.rcvars:
shelter = db.cr_shelter
query = (shelter.id == session.rcvars["cr_shelter"])
selection = db(query).select(shelter.id, shelter.name, limitby=(0, 1)).first()
if selection:
menu_shelter = [
[selection.name, False, URL(r=request, c="cr", f="shelter", args=[selection.id])]
]
menu.extend(menu_shelter)
response.menu_options = menu
def index():
""" Module's Home Page
Default to the rms_req list view.
"""
request.function = "req"
request.args = []
return req()
#module_name = deployment_settings.modules[prefix].name_nice
#response.title = module_name
#return dict(module_name=module_name, a=1)
def req():
""" RESTful CRUD controller """
resourcename = request.function # check again in case we're coming from index()
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
# Pre-processor
def prep(r):
response.s3.cancel = r.here()
if r.representation in shn_interactive_view_formats and r.method != "delete":
# Don't send the locations list to client (pulled by AJAX instead)
r.table.location_id.requires = IS_NULL_OR(IS_ONE_OF_EMPTY(db, "gis_location.id"))
#if r.method == "create" and not r.component:
# listadd arrives here as method=None
if not r.component:
table.datetime.default = request.utcnow
table.person_id.default = s3_logged_in_person()
# @ToDo Default the Organisation too
return True
response.s3.prep = prep
# Post-processor
def postp(r, output):
if r.representation in shn_interactive_view_formats:
#if r.method == "create" and not r.component:
# listadd arrives here as method=None
if r.method != "delete" and not r.component:
# Redirect to the Assessments tabs after creation
r.next = r.other(method="ritem", record_id=s3xrc.get_session(prefix, resourcename))
# Custom Action Buttons
if not r.component:
response.s3.actions = [
dict(label=str(T("Open")), _class="action-btn", url=str(URL(r=request, args=["[id]", "update"]))),
dict(label=str(T("Items")), _class="action-btn", url=str(URL(r=request, args=["[id]", "ritem"]))),
]
return output
response.s3.postp = postp
s3xrc.model.configure(table,
#listadd=False, #@todo: List add is causing errors with JS - FIX
editable=True)
return s3_rest_controller(prefix,
resourcename,
rheader=shn_rms_req_rheader)
def shn_rms_req_rheader(r):
""" Resource Header for Requests """
if r.representation == "html":
if r.name == "req":
req_record = r.record
if req_record:
_next = r.here()
_same = r.same()
try:
location = db(db.gis_location.id == req_record.location_id).select(limitby=(0, 1)).first()
location_represent = shn_gis_location_represent(location.id)
except:
location_represent = None
rheader_tabs = shn_rheader_tabs( r,
[(T("Edit Details"), None),
(T("Items"), "ritem"),
]
)
rheader = DIV( TABLE(
TR( TH( T("Message") + ": "),
TD(req_record.message, _colspan=3)
),
TR( TH( T("Time of Request") + ": "),
req_record.datetime,
TH( T( "Location") + ": "),
location_represent,
),
TR( TH( T("Priority") + ": "),
req_record.priority,
TH( T("Document") + ": "),
document_represent(req_record.document_id)
),
),
rheader_tabs
)
return rheader
return None
def ritem():
""" RESTful CRUD controller """
tablename = "%s_%s" % (prefix, resourcename)
table = db[tablename]
s3xrc.model.configure(table, insertable=False)
return s3_rest_controller(prefix, resourcename)
def store_for_req():
store_table = None
return dict(store_table = store_table)
| ptressel/sahana-eden-madpub | controllers/rms.py | Python | mit | 6,228 |
<?php
/**
* Project: Epsilon
* Date: 10/26/15
* Time: 5:30 PM
*
* @link https://github.com/falmar/Epsilon
* @author David Lavieri (falmar) <daviddlavier@gmail.com>
* @copyright 2015 David Lavieri
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*/
namespace Epsilon\Environment;
defined('EPSILON_EXEC') or die();
use Epsilon\Factory;
use Epsilon\Object\Object;
/**
* Class Cookie
*
* @package Epsilon\Environment
*/
class Cookie extends Object
{
private static $Instance;
private $Cookies;
private $newCookies;
public $Lifespan;
public $Path;
public $Domain;
/**
* Load the active cookies of the current session
*
* @param array $Options
*/
public function __construct($Options = [])
{
parent::__construct($Options);
if (!isset($this->Cookies)) {
$this->Cookies = &$_COOKIE;
}
$this->newCookies = [];
}
/**
* @return Cookie
*/
public static function getInstance()
{
if (!isset(self::$Instance)) {
self::$Instance = new Cookie();
}
return self::$Instance;
}
/**
* Set a cookie
*
* @param string $Key
* @param mixed $Value
* @param int|NULL $Lifespan seconds
*/
function set($Key, $Value, $Lifespan = null)
{
if ($Value === null) {
$Lifespan = time() - 1;
}
$this->newCookies[$Key] = [
'value' => base64_encode($Value),
'lifespan' => $Lifespan
];
$Lifespan = time() + ((is_int($Lifespan)) ? $Lifespan : $this->Lifespan);
if (!Factory::getApplication()->isCLI()) {
setcookie($Key, base64_encode($Value), $Lifespan, $this->Path, $this->Domain);
}
}
/**
* @param $Key
* @return null|string
*/
function get($Key)
{
if (isset($this->newCookies[$Key])) {
$value = $this->newCookies[$Key]['value'];
} elseif (isset($this->Cookies[$Key])) {
$value = $this->Cookies[$Key];
} else {
$value = null;
}
return ($value) ? base64_decode($value) : null;
}
}
| falmar/Epsilon | Libraries/Epsilon/Environment/Cookie.php | PHP | mit | 2,264 |
package org.jabref.gui.openoffice;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import org.jabref.Globals;
import org.jabref.gui.JabRefFrame;
import org.jabref.gui.keyboard.KeyBinding;
import org.jabref.logic.l10n.Localization;
import com.jgoodies.forms.builder.ButtonBarBuilder;
import com.jgoodies.forms.builder.FormBuilder;
import com.jgoodies.forms.layout.FormLayout;
/**
* Dialog for adding citation with page number info.
*/
class AdvancedCiteDialog {
private static boolean defaultInPar = true;
private boolean okPressed;
private final JDialog diag;
private final JTextField pageInfo = new JTextField(15);
public AdvancedCiteDialog(JabRefFrame parent) {
diag = new JDialog((JFrame) null, Localization.lang("Cite special"), true);
ButtonGroup bg = new ButtonGroup();
JRadioButton inPar = new JRadioButton(Localization.lang("Cite selected entries between parenthesis"));
JRadioButton inText = new JRadioButton(Localization.lang("Cite selected entries with in-text citation"));
bg.add(inPar);
bg.add(inText);
if (defaultInPar) {
inPar.setSelected(true);
} else {
inText.setSelected(true);
}
inPar.addChangeListener(changeEvent -> defaultInPar = inPar.isSelected());
FormBuilder builder = FormBuilder.create()
.layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref, 4dlu, pref"));
builder.add(inPar).xyw(1, 1, 3);
builder.add(inText).xyw(1, 3, 3);
builder.add(Localization.lang("Extra information (e.g. page number)") + ":").xy(1, 5);
builder.add(pageInfo).xy(3, 5);
builder.padding("10dlu, 10dlu, 10dlu, 10dlu");
diag.getContentPane().add(builder.getPanel(), BorderLayout.CENTER);
ButtonBarBuilder bb = new ButtonBarBuilder();
bb.addGlue();
JButton ok = new JButton(Localization.lang("OK"));
JButton cancel = new JButton(Localization.lang("Cancel"));
bb.addButton(ok);
bb.addButton(cancel);
bb.addGlue();
bb.padding("5dlu, 5dlu, 5dlu, 5dlu");
diag.getContentPane().add(bb.getPanel(), BorderLayout.SOUTH);
diag.pack();
ActionListener okAction = actionEvent -> {
okPressed = true;
diag.dispose();
};
ok.addActionListener(okAction);
pageInfo.addActionListener(okAction);
inPar.addActionListener(okAction);
inText.addActionListener(okAction);
Action cancelAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
okPressed = false;
diag.dispose();
}
};
cancel.addActionListener(cancelAction);
builder.getPanel().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE), "close");
builder.getPanel().getActionMap().put("close", cancelAction);
}
public void showDialog() {
diag.setLocationRelativeTo(diag.getParent());
diag.setVisible(true);
}
public boolean canceled() {
return !okPressed;
}
public String getPageInfo() {
return pageInfo.getText().trim();
}
public boolean isInParenthesisCite() {
return defaultInPar;
}
}
| tobiasdiez/jabref | src/main/java/org/jabref/gui/openoffice/AdvancedCiteDialog.java | Java | mit | 3,726 |
//
// GuidExtensions.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace CSF
{
/// <summary>
/// Extension methods for the <c>System.Guid</c> type.
/// </summary>
public static class GuidExtensions
{
#region constants
private const int GUID_BYTE_COUNT = 16;
private static readonly int[] REORDERING_MAP = new[] { 3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15 };
#endregion
#region extension methods
/// <summary>
/// Returns a byte array representing the given <c>System.Guid</c> in an RFC-4122 compliant format.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A byte array representation of the GUID, in RFC-4122 compliant form.
/// </returns>
/// <param name='guid'>
/// The GUID for which to get the byte array.
/// </param>
public static byte[] ToRFC4122ByteArray(this Guid guid)
{
return BitConverter.IsLittleEndian? ReorderBytes(guid.ToByteArray()) : guid.ToByteArray();
}
/// <summary>
/// Returns a <c>System.Guid</c>, created from the given RFC-4122 compliant byte array.
/// </summary>
/// <remarks>
/// <para>
/// The rationale for this method (and the reason for requiring it) is because Microsoft internally represent the
/// GUID structure in a manner which does not comply with RFC-4122's definition of a UUID. The first three blocks
/// of data (out of 4 total) are stored using the machine's native endianness. The RFC defines that these three
/// blocks should be represented in big-endian format. This does not cause a problem when getting a
/// string-representation of the GUID, since the framework automatically converts to big-endian format before
/// formatting as a string. When getting a byte array equivalent of the GUID though, it can cause issues if the
/// recipient of that byte array expects a standards-compliant UUID.
/// </para>
/// <para>
/// This method checks the architecture of the current machine. If it is little-endian then - before returning a
/// value - the byte-order of the first three blocks of data are reversed. If the machine is big-endian then the
/// bytes are left untouched (since they are already correct).
/// </para>
/// <para>
/// For more information, see https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding
/// </para>
/// </remarks>
/// <returns>
/// A GUID, created from the given byte array.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID, in RFC-4122 compliant form.
/// </param>
public static Guid FromRFC4122ByteArray(this byte[] guidBytes)
{
return new Guid(BitConverter.IsLittleEndian? ReorderBytes(guidBytes) : guidBytes);
}
#endregion
#region static methods
/// <summary>
/// Copies a byte array that represents a GUID, reversing the order of the bytes in data-blocks one to three.
/// </summary>
/// <returns>
/// A copy of the original byte array, with the modifications.
/// </returns>
/// <param name='guidBytes'>
/// A byte array representing a GUID.
/// </param>
public static byte[] ReorderBytes(byte[] guidBytes)
{
if(guidBytes == null)
{
throw new ArgumentNullException(nameof(guidBytes));
}
else if(guidBytes.Length != GUID_BYTE_COUNT)
{
throw new ArgumentException(Resources.ExceptionMessages.MustBeSixteenBytesInAGuid, nameof(guidBytes));
}
byte[] output = new byte[GUID_BYTE_COUNT];
for(int i = 0; i < GUID_BYTE_COUNT; i++)
{
output[i] = guidBytes[REORDERING_MAP[i]];
}
return output;
}
#endregion
}
}
| csf-dev/CSF.Core | CSF/GuidExtensions.cs | C# | mit | 6,175 |
<?php
/**
* Content wrappers
*
* This template can be overridden by copying it to yourtheme/woocommerce/global/wrapper-start.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
$template = get_option( 'template' );
switch ( $template ) {
case 'twentyeleven' :
echo '<div id="primary"><div id="content" role="main" class="twentyeleven">';
break;
case 'twentytwelve' :
echo '<div id="primary" class="site-content"><div id="content" role="main" class="twentytwelve">';
break;
case 'twentythirteen' :
echo '<div id="primary" class="site-content"><div id="content" role="main" class="entry-content twentythirteen">';
break;
case 'twentyfourteen' :
echo '<div id="primary" class="content-area"><div id="content" role="main" class="site-content twentyfourteen"><div class="tfwc">';
break;
case 'twentyfifteen' :
echo '<div id="primary" role="main" class="content-area twentyfifteen"><div id="main" class="site-main t15wc">';
break;
case 'twentysixteen' :
echo '<div id="primary" class="content-area twentysixteen"><main id="main" class="site-main" role="main">';
break;
default :
echo '<div id="container"><div id="content" role="main">';
break;
}
| srjwebster/doubletrouble | woocommerce/global/wrapper-start.php | PHP | mit | 1,773 |
//******************************************************************************************************
// App.xaml.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 09/28/2009 - Mehulbhai P Thakkar
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Text;
using System.Windows;
using Microsoft.Maps.MapControl;
using openPDCManager.ModalDialogs;
using openPDCManager.Utilities;
namespace openPDCManager
{
public partial class App : Application
{
#region [ Properties ]
public string NodeValue { get; set; }
public string NodeName { get; set; }
public string TimeSeriesDataServiceUrl { get; set; }
public string RemoteStatusServiceUrl { get; set; }
public string RealTimeStatisticServiceUrl { get; set; }
public ApplicationIdCredentialsProvider Credentials { get; set; }
#endregion
#region [ Constructor ]
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
#endregion
#region [ Application Event Handlers ]
private void Application_Startup(object sender, StartupEventArgs e)
{
if ((e.InitParams != null) && (e.InitParams.ContainsKey("BaseServiceUrl")))
Resources.Add("BaseServiceUrl", e.InitParams["BaseServiceUrl"]);
ApplicationIdCredentialsProvider credentialsProvider = new ApplicationIdCredentialsProvider();
if ((e.InitParams != null) && (e.InitParams.ContainsKey("BingMapsKey")))
credentialsProvider.ApplicationId = e.InitParams["BingMapsKey"];
this.Credentials = credentialsProvider;
this.RootVisual = new MasterLayoutControl();
//Set default system settings if no settings exist.
ProxyClient.SetDefaultSystemSettings(false);
}
private void Application_Exit(object sender, EventArgs e)
{
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
//// If the app is running outside of the debugger then report the exception using
//// the browser's exception mechanism. On IE this will display it a yellow alert
//// icon in the status bar and Firefox will display a script error.
//if (!System.Diagnostics.Debugger.IsAttached)
//{
// // NOTE: This will allow the application to continue running after an exception has been thrown
// // but not handled.
// // For production applications this error handling should be replaced with something that will
// // report the error to the website and stop the application.
// e.Handled = true;
// Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
//}
StringBuilder sb = new StringBuilder();
sb.AppendLine("Exception Type: " + e.GetType().ToString());
sb.AppendLine("Error Message: " + e.ExceptionObject.Message);
sb.AppendLine("Stack Trace: " + e.ExceptionObject.StackTrace);
SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Application Error Occured", SystemMessage = sb.ToString(), UserMessageType = MessageType.Error },
ButtonType.OkOnly);
sm.ShowPopup();
}
#endregion
#region [ Methods ]
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}
#endregion
}
} | GridProtectionAlliance/openPDC | Source/Applications/openPDCManager/Silverlight/App.xaml.cs | C# | mit | 4,907 |
package com.ricex.aft.android.request;
import org.springframework.http.HttpStatus;
public class AFTResponse<T> {
/** The successful response from the server */
private final T response;
/** The error response from the server */
private final String error;
/** The HttpStatus code of the response */
private final HttpStatus statusCode;
/** Whether or not this response is valid */
private final boolean valid;
/** Creates a new instance of AFTResponse, representing a successful response
*
* @param response The parsed response received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, HttpStatus statusCode) {
this.response = response;
this.statusCode = statusCode;
this.error = null;
valid = true;
}
/** Creates a new instance of AFTResponse, representing an invalid (error) response
*
* @param response The response (if any) received from the server
* @param error The error message received from the server
* @param statusCode The status code of the response
*/
public AFTResponse(T response, String error, HttpStatus statusCode) {
this.response = response;
this.error = error;
this.statusCode = statusCode;
valid = false;
}
/** Whether or not this response is valid
*
* @return True if the server returned Http OK (200), otherwise false
*/
public boolean isValid() {
return valid;
}
/** The response from the server if valid
*
* @return The response from the server
*/
public T getResponse() {
return response;
}
/** Returns the error received by the server, if invalid response
*
* @return The error the server returned
*/
public String getError() {
return error;
}
/** Return the status code received from the server
*
* @return the status code received from the server
*/
public HttpStatus getStatusCode() {
return statusCode;
}
}
| mwcaisse/AndroidFT | aft-android/src/main/java/com/ricex/aft/android/request/AFTResponse.java | Java | mit | 1,925 |
<?php
/**
* Routes configuration
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different URLs to chosen controllers and their actions (functions).
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Core\Plugin;
use Cake\Routing\Router;
Router::scope('/', function ($routes) {
/**
* Here, we are connecting '/' (base path) to a controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, src/Template/Pages/home.ctp)...
*/
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
/**
* ...and connect the rest of 'Pages' controller's URLs.
*/
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
Router::scope(
'/bookmarks',
['controller' => 'Bookmarks'],
function ($routes) {
$routes->connect('/tagged/*', ['action' => 'tags']);
}
);
/**
* Connect a route for the index action of any controller.
* And a more general catch all route for any action.
*
* The `fallbacks` method is a shortcut for
* `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);`
* `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);`
*
* You can remove these routes once you've connected the
* routes you want in your application.
*/
$routes->fallbacks();
});
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
| simkimsia/500-webapps | bookmarker/cake3_bookmarker/config/routes.php | PHP | mit | 2,129 |
/* app/ui/map/svg */
define(
[
'jquery',
'raphael',
'app/ui/map/data',
'app/ui/map/util',
'util/detector',
'pubsub'
],
function ($, Raphael, MapData, MapUtil, Detector) {
'use strict';
var SVG;
return {
nzte: {},
markers: [],
exports: {},
countryText: {},
sets: {},
continentSets: {},
text: {},
raphael: null,
_$container: null,
_isExportsMap: false,
init: function () {
SVG = this;
this._$container = $('.js-map-container');
this._isExportsMap = $('#js-map-nzte').length ? false : true;
//If already setup just show the map again
if (this._$container.is('.is-loaded')) {
this._$container.show();
return;
}
if (this._isExportsMap) {
this._initInteractiveMap();
return;
}
this._initRegularMap();
},
_initInteractiveMap: function () {
this._setUpMap();
this._drawMap();
this._createContinentSets();
this._initInteractiveMapEvents();
this._setLoaded();
this._hideLoader();
},
_initRegularMap: function () {
this._setUpMap();
this._drawMap();
this._createSets();
this._initRegularMapEvents();
this._setLoaded();
this._hideLoader();
},
_setLoaded: function () {
this._$container.addClass('is-loaded');
},
_hideLoader: function () {
$.publish('/loader/hide');
},
_setUpMap: function () {
var id = this._isExportsMap ? 'js-map-exports' : 'js-map-nzte';
this._$container.show();
this.raphael = Raphael(id, '100%', '100%');
this.raphael.setViewBox(0, 0, 841, 407, true);
this.raphael.canvas.setAttribute('preserveAspectRatio', 'xMinYMin meet');
},
_drawMap: function () {
this._addMainMap();
this._addContinentMarkers();
this._addContinentMarkerText();
if (this._isExportsMap) {
this._addCountryMarkers();
}
},
_addMainMap: function () {
var mainAttr = {
stroke: 'none',
fill: '#dededd',
'fill-rule': 'evenodd',
'stroke-linejoin': 'round'
};
this.nzte.main = this.raphael.path(MapData.main).attr(mainAttr);
},
_addContinentMarkers: function () {
var markerAttr = {
stroke: 'none',
fill: '#f79432',
'stroke-linejoin': 'round',
cursor: 'pointer'
};
var markerPaths = MapData.markers[0];
for (var continent in markerPaths) {
if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') {
this.markers[continent] = this.raphael.path(markerPaths[continent]).attr(markerAttr);
}
}
},
_addContinentMarkerText: function () {
var textAttr = {
stroke: 'none',
fill: '#ffffff',
'fill-rule': 'evenodd',
'stroke-linejoin': 'round',
cursor: 'pointer'
};
var textPaths = MapData.text[0];
for (var continent in textPaths) {
if (!this._isExportsMap || this._isExportsMap && continent !== 'new-zealand') {
this.text[continent] = this.raphael.path(textPaths[continent]).attr(textAttr);
}
}
},
_addCountryMarkers: function () {
var marker;
for (var region in this.markers) {
marker = this.markers[region];
this._createHoverBox(region, marker);
}
},
_createHoverBox: function (region, marker) {
var set;
var markerAttr = {
stroke: 'none',
fill: '#116697',
opacity: 0,
'stroke-linejoin': 'round'
};
var markerPaths = MapData.exportsText[0];
var country = markerPaths[region];
if (!country) {
return;
}
var countryText = markerPaths[region][0];
var numberOfCountries = Object.keys(countryText).length;
var markerBox = marker.getBBox();
var topX = markerBox.x;
var bottomY = markerBox.y2;
var width = region !== 'india-middle-east-and-africa' ? 150 : 200;
//Add the rectangle
this.exports[region] = this.raphael.rect(topX + 28, bottomY - 1, width, (21 * numberOfCountries) + 5).toBack().attr(markerAttr);
//Create a set to combine countries, hover box and region icon/text
set = this.raphael.set();
set.push(
this.exports[region]
);
//Add the country Text
this._addCountryText(markerBox, countryText, topX + 28, bottomY - 1, 21, region, set);
},
_addCountryText: function (markerBox, countryText, x, y, height, region, set) {
var updatedX = x + 10;
var updatedY = y + 10;
var textAttr = {
font: '13px Arial',
textAlign: 'left',
fill: "#ffffff",
cursor: 'pointer',
'text-decoration': 'underline',
'text-anchor': 'start',
opacity: 0
};
for (var country in countryText) {
var text = countryText[country].toUpperCase();
this.countryText[country] = this.raphael.text(updatedX, updatedY, text).toBack().attr(textAttr);
updatedY += height;
set.push(
this.countryText[country]
);
}
this.continentSets[region] = set.hide();
},
_createSets: function () {
for (var region in this.markers) {
var set = this.raphael.set();
set.push(
this.markers[region],
this.text[region]
);
this.sets[region] = set;
}
},
_createContinentSets: function () {
for (var region in this.markers) {
var set = this.raphael.set();
set.push(
this.markers[region],
this.text[region],
this.continentSets[region]
);
this.sets[region] = set;
}
},
_initInteractiveMapEvents: function () {
this._initCountryTextEvents();
this._initCountryHoverEvents();
},
_initRegularMapEvents: function () {
var bounceEasing = 'cubic-bezier(0.680, -0.550, 0.265, 1.550)';
var mouseOverMarkerBounce = {
transform: 's1.1'
};
var mouseOverMarkerBounceWithTranslate = {
transform: 's1.1t5,0'
};
var mouseOutMarkerBounce = {
transform: 's1'
};
var mouseOverMarker = {
fill: '#116697'
};
var mouseOutMarker = {
fill: '#f79432'
};
for (var region in this.sets) {
var set = this.sets[region];
var marker = this.markers[region];
var text = this.text[region];
(function (savedSet, savedRegion, savedMarker, savedText) {
savedSet.attr({
cursor: 'pointer'
});
savedSet.hover(function () {
//A slight translation is needed for 'india-middle-east-and-africa' so when hovered it isn't clipped by container
var transformAttr = savedRegion !== 'india-middle-east-and-africa' ? mouseOverMarkerBounce : mouseOverMarkerBounceWithTranslate;
savedMarker.animate(transformAttr, 250, bounceEasing);
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedText.animate(transformAttr, 250, bounceEasing);
}, function () {
savedMarker.animate(mouseOutMarkerBounce, 250, bounceEasing);
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedText.animate(mouseOutMarkerBounce, 250, bounceEasing);
});
savedSet.click(function () {
MapUtil.goToUrl(savedRegion, false);
});
})(set, region, marker, text);
}
},
_initCountryHoverEvents: function () {
var noHover = Detector.noSvgHover();
var mouseOverMarker = {
fill: '#116697'
};
var mouseOutMarker = {
fill: '#f79432'
};
for (var region in this.sets) {
var set = this.sets[region];
var continentSet = this.continentSets[region];
var marker = this.markers[region];
var text = this.text[region];
var hoverBox = this.exports[region];
(function (savedSet, savedContinentSet, savedRegion, savedMarker, savedText, savedBox) {
savedSet.attr({
cursor: 'pointer'
});
if (noHover) {
savedMarker.data('open', false);
savedSet.click(function () {
if (savedMarker.data('open') === false) {
SVG._closeAllContinents();
savedMarker.data('open', true);
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo');
} else {
savedMarker.data('open', false);
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
}
});
savedSet.hover(function () {
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
}, function () {
savedMarker.data('open') === false && savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
});
} else {
savedSet.hover(function () {
savedMarker.animate(mouseOverMarker, 250, 'easeInOutExpo');
savedContinentSet.show().toFront().animate({ opacity: 1 }, 250, 'easeInOutExpo');
}, function () {
savedMarker.animate(mouseOutMarker, 250, 'easeInOutSine');
savedContinentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
});
}
})(set, continentSet, region, marker, text, hoverBox);
}
},
_closeAllContinents: function () {
for (var region in this.sets) {
var continentSet = this.continentSets[region];
var marker = this.markers[region];
var mouseOutMarker = {
fill: '#f79432'
};
marker.data('open', false);
marker.animate(mouseOutMarker, 250, 'easeInOutSine');
continentSet.animate({ opacity: 0 }, 250, 'easeInOutSine').hide().toBack();
}
},
_initCountryTextEvents: function () {
for (var country in this.countryText) {
var text = this.countryText[country];
(function (savedText, savedCountry) {
savedText.click(function () {
MapUtil.goToUrl(savedCountry, true);
});
savedText.hover(function () {
savedText.animate({ 'fill-opacity': 0.6 }, 250, 'easeInOutSine');
}, function () {
savedText.animate({ 'fill-opacity': 1 }, 250, 'easeInOutSine');
});
})(text, country);
}
}
};
}
); | patocallaghan/questionnaire-js | original/assets/scripts/src/app/ui/map/svg.js | JavaScript | mit | 9,939 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only)
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost:8889',
'username' => 'root',
'password' => 'root',
'database' => 'belttest',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
| khandroj/lampbelttest | application/config/database.php | PHP | mit | 4,535 |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
meta: {
version: '2.0.0',
banner: '/*! Ebla - v<%= meta.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> ' +
'Monospaced */'
},
concat: {
dist: {
src: ['<banner:meta.banner>',
'javascripts/libs/jquery.cookie.js',
'javascripts/ebla/ebla.js',
'javascripts/ebla/debug.js',
'javascripts/ebla/flash-message.js',
'javascripts/ebla/compatibility.js',
'javascripts/ebla/elements.js',
'javascripts/ebla/controls.js',
'javascripts/ebla/data.js',
'javascripts/ebla/images.js',
'javascripts/ebla/layout.js',
'javascripts/ebla/loader.js',
'javascripts/ebla/navigation.js',
'javascripts/ebla/navigation.event.js',
'javascripts/ebla/navigation.keyboard.js',
'javascripts/ebla/placesaver.js',
'javascripts/ebla/progress.js',
'javascripts/ebla/resize.js',
'javascripts/ebla/toc.js',
'javascripts/ebla/init.js',
'javascripts/ebla/book.js'],
dest: 'javascripts/ebla.js'
}
},
uglify: {
dist: {
src: ['<banner:meta.banner>', 'javascripts/ebla.js'],
dest: 'javascripts/ebla.min.js'
}
},
sass: {
dist: {
options: {
style: 'compressed'
},
files: {
'stylesheets/ebla.css': 'stylesheets/ebla.scss',
'stylesheets/book.css': 'stylesheets/book.scss'
}
}
},
watch: {
files: ['javascripts/ebla/*.js', 'stylesheets/*.scss'],
tasks: ['sass', 'concat', 'uglify']
},
jshint: {
files: ['Gruntfile.js', 'javascripts/ebla.js'],
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
jquery: true,
devel: true,
globals: {
Modernizr: true,
debug: true,
bookData: true,
bookJson: true
}
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
// Default task.
grunt.registerTask('default', ['sass', 'concat', 'jshint', 'uglify']);
};
| monospaced/paperback | ebla/Gruntfile.js | JavaScript | mit | 2,746 |
<?php
// src/AppBundle/Entity/Blog.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="blog")
*/
class Blog
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=100)
*/
protected $title;
/**
* @ORM\Column(type="decimal", scale=2)
*/
protected $body;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
* @return Blog
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set body
*
* @param string $body
* @return Blog
*/
public function setBody($body)
{
$this->body = $body;
return $this;
}
/**
* Get body
*
* @return string
*/
public function getBody()
{
return $this->body;
}
}
| codeglider/SymfonyShoeStoreDemo | src/AppBundle/Entity/Blog.php | PHP | mit | 1,238 |
import {Chart} from 'react-google-charts';
import React, {Component, PropTypes} from 'react';
import DataFormatter from '../../utils/DataFormatter';
class EnvyBarChart extends Component {
constructor(props) {
super(props);
this.state={
options:{
hAxis: {title: 'Event Type'},
vAxis: {title: 'Envy Events'},
legend: 'none',
},
};
}
generateGraph(events) {
var formatter = new DataFormatter();
var result = formatter.generateEnvyGraph(events);
return result;
}
render() {
var data = this.generateGraph(this.props.events);
return (
<Chart
chartType="ColumnChart"
data={data}
options={this.state.options}
graph_id="EnvyBarChart"
width='40vw'
height='50vh'
/>
);
}
};
EnvyBarChart.propTypes = {
events: PropTypes.array.isRequired
}
export default EnvyBarChart; | papernotes/actemotion | src/components/charts/EnvyBarChart.js | JavaScript | mit | 828 |
using ApiAiSDK.Model;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UPT.BOT.Aplicacion.DTOs.BOT;
using UPT.BOT.Distribucion.Bot.Acceso.Documento;
namespace UPT.BOT.Distribucion.Bot.BotService.Dialogos.Documento
{
[Serializable]
public class BoletinDialog : BaseDialog, IDialog<object>
{
private AIResponse response;
public BoletinDialog(AIResponse response)
{
this.response = response;
}
public async Task StartAsync(IDialogContext context)
{
IMessageActivity actividaMensaje = context.MakeMessage();
actividaMensaje.Text = response.Result.Fulfillment.Speech ?? string.Empty;
actividaMensaje.Recipient = actividaMensaje.From;
actividaMensaje.Type = ActivityTypes.Message;
await context.PostAsync(actividaMensaje);
List<BoletinDto> entidades = new BoletinProxy(ruta).Obtener();
List<Attachment> listaAdjuntos = new List<Attachment>();
HeroCard tarjetaFormato = new HeroCard("Boletines");
tarjetaFormato.Subtitle = "Puedes descargar boletines que te serán de gran ayuda!";
tarjetaFormato.Buttons = entidades.Select(p => new CardAction
{
Title = p.DescripcionTitulo,
Value = p.DescripcionUrl,
Type = ActionTypes.DownloadFile
}).ToList();
listaAdjuntos.Add(tarjetaFormato.ToAttachment());
IMessageActivity actividadTarjeta = context.MakeMessage();
actividadTarjeta.Recipient = actividadTarjeta.From;
actividadTarjeta.Attachments = listaAdjuntos;
actividadTarjeta.AttachmentLayout = AttachmentLayoutTypes.List;
actividadTarjeta.Type = ActivityTypes.Message;
await context.PostAsync(actividadTarjeta);
context.Done(this);
}
}
}
| williamccondori/UPT.BOT | UPT.BOT.Distribucion.Bot.BotService/Dialogos/Documento/BoletinDialog.cs | C# | mit | 2,032 |
"use strict";
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
EmailValidator = require('./emailValidator');
class User {
constructor(explicitConnection) {
this.explicitConnection = explicitConnection;
this.schema = new Schema({
email: {
type: 'string',
trim: true,
required: true
},
organization: {
type: 'string',
trim: true,
required: true
},
password: {type: 'string', required: true},
isVisibleAccount: {type: 'boolean'},
userApiKey: {type: 'string'},
userApiSecret: {type: 'string'},
linkedApps: {},
avatarProto: {type: 'string'},
gmailAccount: {type: 'string'},
facebookAccount: {type: 'string'},
twitterAccount: {type: 'string'},
fullname: {type: 'string'},
loginHistories: [],
changeProfileHistories: [],
changeAuthorizationHistories: [],
sparqlQuestions: [],
blockingHistories: [],
authorizations: {},
tripleUsage: {type: 'number', default: 0},
tripleUsageHistory: [],
isBlocked: {
type: 'boolean',
required: true
},
blockedCause: {
type: 'string',
}
}).index({ email: 1, organization: 1 }, { unique: true });
}
getModel() {
if (this.explicitConnection === undefined) {
return mongoose.model('User', this.schema);
} else {
return this.explicitConnection.model('User', this.schema);
}
}
}
module.exports = User; | koneksys/KLD | api/model/user.js | JavaScript | mit | 1,603 |
package cn.edu.ustc.appseed.clubseed.activity;
/*
* Show the detail content of the event which you select.
* Why to use a custom toolbar instead of the default toolbar in ActionBarActivity?
* Because the custom toolbar is very convenient to edit it and good to unify the GUI.
*/
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import cn.edu.ustc.appseed.clubseed.R;
import cn.edu.ustc.appseed.clubseed.data.Event;
import cn.edu.ustc.appseed.clubseed.data.ViewActivityPhp;
import cn.edu.ustc.appseed.clubseed.fragment.NoticeFragment;
import cn.edu.ustc.appseed.clubseed.fragment.StarFragment;
import cn.edu.ustc.appseed.clubseed.utils.AppUtils;
public class StarContentActivity extends ActionBarActivity {
private Toolbar toolbar;
private TextView mTextView;
private ImageView mImageView;
private TextView nullTextView;
private Event mEvent;
int ID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_content);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mTextView = (TextView) findViewById(R.id.textViewEventContent);
mImageView = (ImageView) findViewById(R.id.imgContent);
if (toolbar != null) {
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
ID = getIntent().getIntExtra(StarFragment.EXTRA_ID, 0);
mEvent = AppUtils.savedEvents.get(ID);
setTitle(mEvent.getTitle());
mTextView.setText(mEvent.getContent());
mImageView.setImageBitmap(mEvent.getBitmap());
}
}
| leerduo/ClubSeed | app/src/main/java/cn/edu/ustc/appseed/clubseed/activity/StarContentActivity.java | Java | mit | 2,293 |
package com.smbc.droid;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.android.volley.toolbox.NetworkImageView;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ComicPagerAdapter adapter = new ComicPagerAdapter( getSupportFragmentManager());
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
// findViewById(R.id.btn_next).setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// viewPager.setCurrentItem(viewPager.getCurrentItem()+1, true);
// }
// });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| nindalf/smbc-droid | app/src/main/java/com/smbc/droid/MainActivity.java | Java | mit | 1,709 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace image_viewer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ImageForm());
}
}
}
| rjclaasen/image-viewer | Program.cs | C# | mit | 517 |
using System;
using OKHOSTING.UI.Controls;
using OKHOSTING.UI.Controls.Layouts;
using OKHOSTING.UI.Xamarin.Mac.Controls;
using OKHOSTING.UI.Xamarin.Mac.Controls.Layout;
namespace OKHOSTING.UI.Xamarin.Mac
{
public class Platform
{
public override T Create<T>()
{
T control = null;
if (typeof(T) == typeof(IAutocomplete))
{
control = new Autocomplete() as T;
}
else if (typeof(T) == typeof(IButton))
{
control = new Button() as T;
}
else if (typeof(T) == typeof(ICalendar))
{
control = new Calendar() as T;
}
else if (typeof(T) == typeof(ICheckBox))
{
control = new CheckBox() as T;
}
else if (typeof(T) == typeof(IHyperLink))
{
control = new HyperLink() as T;
}
else if (typeof(T) == typeof(IImage))
{
control = new Image() as T;
}
else if (typeof(T) == typeof(ILabel))
{
control = new Label() as T;
}
else if (typeof(T) == typeof(ILabelButton))
{
control = new LabelButton() as T;
}
else if (typeof(T) == typeof(IListPicker))
{
control = new ListPicker() as T;
}
else if (typeof(T) == typeof(IPasswordTextBox))
{
control = new PasswordTextBox() as T;
}
else if (typeof(T) == typeof(ITextArea))
{
control = new TextArea() as T;
}
else if (typeof(T) == typeof(ITextBox))
{
control = new TextBox() as T;
}
else if (typeof(T) == typeof(IGrid))
{
control = new Grid() as T;
}
else if (typeof(T) == typeof(IStack))
{
control = new Stack() as T;
}
return control;
}
public override void Finish()
{
base.Finish();
}
//virtual
public virtual Color Parse(global::Xamarin.Mac.Color color)
{
return new Color((int) color.A, (int) color.R, (int) color.G, (int) color.B);
}
public virtual global::Xamarin.Mac.Color Parse(Color color)
{
return global::Xamarin.Mac.Color.FromRgba(color.Alpha, color.Red, color.Green, color.Blue);
}
public virtual HorizontalAlignment Parse(global::Xamarin.Mac.LayoutAlignment horizontalAlignment)
{
switch (horizontalAlignment)
{
case global::Xamarin.Mac.LayoutAlignment.Start:
return HorizontalAlignment.Left;
case global::Xamarin.Mac.LayoutAlignment.Center:
return HorizontalAlignment.Center;
case global::Xamarin.Mac.LayoutAlignment.End:
return HorizontalAlignment.Right;
case global::Xamarin.Mac.LayoutAlignment.Fill:
return HorizontalAlignment.Fill;
}
return HorizontalAlignment.Left;
}
public virtual global::Xamarin.Mac.LayoutAlignment Parse(HorizontalAlignment horizontalAlignment)
{
switch (horizontalAlignment)
{
case HorizontalAlignment.Left:
return global::Xamarin.Mac.LayoutAlignment.Start;
case HorizontalAlignment.Center:
return global::Xamarin.Mac.LayoutAlignment.Center;
case HorizontalAlignment.Right:
return global::Xamarin.Mac.LayoutAlignment.End;
case HorizontalAlignment.Fill:
return global::Xamarin.Mac.LayoutAlignment.Fill;
}
throw new ArgumentOutOfRangeException("horizontalAlignment");
}
public virtual VerticalAlignment ParseVerticalAlignment(global::Xamarin.Mac.LayoutAlignment verticalAlignment)
{
switch (verticalAlignment)
{
case global::Xamarin.Mac.LayoutAlignment.Start:
return VerticalAlignment.Top;
case global::Xamarin.Mac.LayoutAlignment.Center:
return VerticalAlignment.Center;
case global::Xamarin.Mac.LayoutAlignment.End:
return VerticalAlignment.Bottom;
case global::Xamarin.Mac.LayoutAlignment.Fill:
return VerticalAlignment.Fill;
}
return VerticalAlignment.Top;
}
public virtual global::Xamarin.Mac.LayoutAlignment Parse(VerticalAlignment verticalAlignment)
{
switch (verticalAlignment)
{
case VerticalAlignment.Top:
return global::Xamarin.Mac.LayoutAlignment.Start;
case VerticalAlignment.Center:
return global::Xamarin.Mac.LayoutAlignment.Center;
case VerticalAlignment.Bottom:
return global::Xamarin.Mac.LayoutAlignment.End;
case VerticalAlignment.Fill:
return global::Xamarin.Mac.LayoutAlignment.Fill;
}
return global::Xamarin.Mac.LayoutAlignment.Start;
}
public HorizontalAlignment Parse(global::Xamarin.Mac.TextAlignment textAlignment)
{
switch (textAlignment)
{
case global::Xamarin.Mac.TextAlignment.Start:
return HorizontalAlignment.Left;
case global::Xamarin.Mac.TextAlignment.Center:
return HorizontalAlignment.Center;
case global::Xamarin.Mac.TextAlignment.End:
return HorizontalAlignment.Right;
}
return HorizontalAlignment.Left;
}
public global::Xamarin.Mac.TextAlignment ParseTextAlignment(HorizontalAlignment alignment)
{
switch (alignment)
{
case HorizontalAlignment.Left:
return global::Xamarin.Mac.TextAlignment.Start;
case HorizontalAlignment.Center:
return global::Xamarin.Mac.TextAlignment.Center;
case HorizontalAlignment.Right:
return global::Xamarin.Mac.TextAlignment.End;
case HorizontalAlignment.Fill:
return global::Xamarin.Mac.TextAlignment.Start;
}
return global::Xamarin.Mac.TextAlignment.Start;
}
//static
public static new Platform Current
{
get
{
var platform = (Platform)UI.Platform.Current;
if (platform == null)
{
platform = new Platform();
UI.Platform.Current = platform;
}
return platform;
}
}
}
} | okhosting/OKHOSTING.UI | src/Xamarin/OKHOSTING.UI.Xamarin.Mac/Platform.cs | C# | mit | 5,381 |
module.export = {
}; | Force-Wj/chat-demo | src/base/util.js | JavaScript | mit | 22 |
(function (ns) {
// dependencies
var assert = require('assert');
var esgraph = require('esgraph');
var worklist = require('analyses');
var common = require("../../base/common.js");
var Context = require("../../base/context.js");
var Base = require("../../base/index.js");
var codegen = require('escodegen');
var annotateRight = require("./infer_expression.js");
var InferenceScope = require("./registry/").InferenceScope;
var System = require("./registry/system.js");
var Annotations = require("./../../type-system/annotation.js");
var walk = require('estraverse');
var Tools = require("../settools.js");
var Shade = require("../../interfaces.js");
var walkes = require('walkes');
var validator = require('../validator');
var TypeInfo = require("../../type-system/typeinfo.js").TypeInfo;
// shortcuts
var Syntax = common.Syntax;
var Set = worklist.Set;
var FunctionAnnotation = Annotations.FunctionAnnotation;
var ANNO = Annotations.ANNO;
function findConstantsFor(ast, names, constantVariables) {
var result = new Set(), annotation, name, formerValue;
constantVariables = constantVariables ? constantVariables.values() : [];
walkes(ast, {
AssignmentExpression: function(recurse) {
if (this.left.type != Syntax.Identifier) {
Shade.throwError(ast, "Can't find constant for computed left expression");
}
name = this.left.name;
if(names.has(name)) {
annotation = ANNO(this.right);
if(annotation.hasConstantValue()) {
switch(this.operator) {
case "=":
result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)});
break;
case "-=":
case "+=":
case "*=":
case "/=":
formerValue = constantVariables.filter(function(v){ return v.name == name; });
if(formerValue.length) {
var c = formerValue[0].constant, v;
switch(this.operator) {
case "+=":
v = c + TypeInfo.copyStaticValue(annotation);
break;
case "-=":
v = c - TypeInfo.copyStaticValue(annotation);
break;
case "*=":
v = c * TypeInfo.copyStaticValue(annotation);
break;
case "/=":
v = c / TypeInfo.copyStaticValue(annotation);
break;
}
result.add({ name: name, constant: v});
}
break;
default:
assert(!this.operator);
}
}
}
recurse(this.right);
},
VariableDeclarator: function(recurse) {
name = this.id.name;
if (this.init && names.has(name)) {
annotation = ANNO(this.init);
if(annotation.hasConstantValue()) {
result.add({ name: name, constant: TypeInfo.copyStaticValue(annotation)});
}
}
recurse(this.init);
},
UpdateExpression: function(recurse) {
if(this.argument.type == Syntax.Identifier) {
name = this.argument.name;
annotation = ANNO(this);
if(annotation.hasConstantValue()) {
var value = TypeInfo.copyStaticValue(annotation);
if (!this.prefix) {
value = this.operator == "--" ? --value : ++value;
}
result.add({ name: name, constant: value});
}
}
}
});
return result;
}
/**
*
* @param ast
* @param {AnalysisContext} context
* @param {*} opt
* @constructor
*/
var TypeInference = function (ast, context, opt) {
opt = opt || {};
this.context = context;
this.propagateConstants = opt.propagateConstants || false;
};
Base.extend(TypeInference.prototype, {
/**
* @param {*} ast
* @param {*} opt
* @returns {*}
*/
inferBody: function (ast, opt) {
var cfg = esgraph(ast, { omitExceptions: true }),
context = this.context,
propagateConstants = this.propagateConstants;
//console.log("infer body", cfg)
var result = worklist(cfg,
/**
* @param {Set} input
* @this {FlowNode}
* @returns {*}
*/
function (input) {
if (!this.astNode || this.type) // Start and end node do not influence the result
return input;
//console.log("Analyze", codegen.generate(this.astNode), this.astNode.type);
// Local
if(propagateConstants) {
this.kill = this.kill || Tools.findVariableAssignments(this.astNode, true);
}
annotateRight(context, this.astNode, propagateConstants ? input : null );
this.decl = this.decl || context.declare(this.astNode);
//context.computeConstants(this.astNode, input);
if(!propagateConstants) {
return input;
}
var filteredInput = null, generate = null;
if (this.kill.size) {
// Only if there's an assignment, we need to generate
generate = findConstantsFor(this.astNode, this.kill, propagateConstants ? input : null);
var that = this;
filteredInput = new Set(input.filter(function (elem) {
return !that.kill.some(function(tokill) { return elem.name == tokill });
}));
}
var result = Set.union(filteredInput || input, generate);
// console.log("input:", input);
// console.log("kill:", this.kill);
// console.log("generate:", generate);
// console.log("filteredInput:", filteredInput);
// console.log("result:", result);
return result;
}
, {
direction: 'forward',
merge: worklist.merge(function(a,b) {
if (!a && !b)
return null;
//console.log("Merge", a && a.values(), b && b.values())
var result = Set.intersect(a, b);
//console.log("Result", result && result.values())
return result;
})
});
//Tools.printMap(result, cfg);
return ast;
}
});
/**
*
* @param ast
* @param {AnalysisContext} context
* @param opt
* @returns {*}
*/
var inferProgram = function (ast, context, opt) {
opt = opt || {};
//var globalScope = createGlobalScope(ast);
//registerSystemInformation(globalScope, opt);
var typeInference = new TypeInference(ast, context, opt);
var result = typeInference.inferBody(ast, opt);
return result;
};
ns.infer = inferProgram;
}(exports));
| xml3d/shade.js | src/analyze/typeinference/typeinference.js | JavaScript | mit | 8,226 |
package lab;
public class IntArrayWorker
{
/** two dimensional matrix */
private int[][] matrix = null;
/** set the matrix to the passed one
* @param theMatrix the one to use
*/
public void setMatrix(int[][] theMatrix)
{
matrix = theMatrix;
}
/**
* Method to return the total
* @return the total of the values in the array
*/
public int getTotal()
{
int total = 0;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
total = total + matrix[row][col];
}
}
return total;
}
/**
* Method to return the total using a nested for-each loop
* @return the total of the values in the array
*/
public int getTotalNested()
{
int total = 0;
for (int[] rowArray : matrix)
{
for (int item : rowArray)
{
total = total + item;
}
}
return total;
}
/**
* Method to fill with an increasing count
*/
public void fillCount()
{
int numCols = matrix[0].length;
int count = 1;
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < numCols; col++)
{
matrix[row][col] = count;
count++;
}
}
}
/**
* print the values in the array in rows and columns
*/
public void print()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length; col++)
{
System.out.print( matrix[row][col] + " " );
}
System.out.println();
}
System.out.println();
}
public int getCount(int num){
int count = 0;
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] == num)
count++;
return count;
}
public int getColTotal(int col){
int total = 0;
for(int row = 0; row < matrix.length; row++)
total += matrix[row][col];
return total;
}
public int getLargest(){
int largest = matrix[0][0];
for(int row = 0; row < matrix.length; row++)
for(int col = 0; col < matrix[0].length; col++)
if(matrix[row][col] > largest)
largest = matrix[row][col];
return largest;
}
/**
* fill the array with a pattern
*/
public void fillPattern1()
{
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[0].length;
col++)
{
if (row < col)
matrix[row][col] = 1;
else if (row == col)
matrix[row][col] = 2;
else
matrix[row][col] = 3;
}
}
}
} | Zedai/APCOMSCI | ApComSci/pictures_lab/lab/IntArrayWorker.java | Java | mit | 2,755 |
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[143];
int n; bool seen[143];
int dfs(int u) {
seen[u] = true;
int result = 0;
for (int v: adj[u])
if (!seen[v])
result += dfs(v) + 1;
return result;
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
while (cin >> n && n) {
for (int i=0, sz; i<n; ++i) {
cin >> sz;
adj[i].resize(sz);
for (int j=0; j<sz; ++j) {
cin >> adj[i][j];
--adj[i][j];
}
}
int mx=-1, mxi;
for (int i=0; i<n; ++i) {
memset(seen, 0, n);
int c = dfs(i);
if (mx < c) {
mx = c;
mxi = i;
}
}
cout << mxi+1 << "\n";
}
}
| arash16/prays | UVA/vol-109/10926.cpp | C++ | mit | 815 |
<?php
namespace SergeiK\izVladimiraBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class CarAdmin extends Admin
{
/**
* @param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('title', null, array(
'label' => 'Название'
))
->add('publish', null, array(
'label' => 'Опубликованно'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
;
}
/**
* @param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('publish', null, array(
'label' => 'Опубликованно'
))
->add('_action', 'actions', array(
'actions' => array(
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* @param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('adds', 'textarea', array(
'label' => 'Дополнительная информация',
'attr' => array(
'class' => 'ckeditor'
)
))
->add('images', 'sonata_type_collection', array(
'required' => false,
'by_reference' => false,
'label' => 'Фото'
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position'
)
)
->add('publish', null, array(
'label' => 'Опубликовать'
))
;
}
/**
* @param ShowMapper $showMapper
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('title', null, array(
'label' => 'Название'
))
->add('seats', null, array(
'label' => 'Колличество посадочных мест'
))
->add('adds', null, array(
'label' => 'Дополнительная информация'
))
;
}
public function prePersist($car){
foreach($car->getImages() as $image){
$image->setCar($car);
}
}
public function preUpdate($car){
foreach($car->getImages() as $image){
$image->setCar($car);
}
}
}
| SergeiKutanov/izvladimira | src/SergeiK/izVladimiraBundle/Admin/CarAdmin.php | PHP | mit | 3,503 |
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
namespace NAudio.Lame
{
/// <summary>
/// Decoder for ID3v2 tags
/// </summary>
public static class ID3Decoder
{
/// <summary>
/// Read an ID3v2 Tag from the current position in a stream.
/// </summary>
/// <param name="stream"><see cref="Stream"/> positioned at start of ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(Stream stream)
{
byte[] header = new byte[10];
int rc = stream.Read(header, 0, 10);
if (rc != 10 || !ValidateTagHeader(header))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(header, 6);
if (size < 10 || size >= (1 << 28))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Load entire tag into buffer and parse
var buffer = new byte[10 + size];
#pragma warning disable IDE0059 // Unnecessary assignment of a value
rc = stream.Read(buffer, 0, buffer.Length);
#pragma warning restore IDE0059 // Unnecessary assignment of a value
return InternalDecode(buffer, 0, size, header[5]);
}
/// <summary>
/// Read an ID3v2 Tag from the supplied array.
/// </summary>
/// <param name="buffer">Array containing complete ID3v2 Tag.</param>
/// <returns><see cref="ID3TagData"/> with tag content.</returns>
public static ID3TagData Decode(byte[] buffer)
{
// Check header
if (!ValidateTagHeader(buffer))
throw new InvalidDataException("Bad ID3 Tag Header");
// decode size field and confirm range
int size = DecodeHeaderSize(buffer, 6);
if (size < 10 || size > (buffer.Length - 10))
throw new InvalidDataException($"ID3 header size '{size:#,0}' out of range.");
// Decode tag content
return InternalDecode(buffer, 10, size, buffer[5]);
}
/// <summary>
/// Decode frames from ID3 tag
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="flags"></param>
/// <returns></returns>
private static ID3TagData InternalDecode(byte[] buffer, int offset, int size, byte flags)
{
// copy tag body data into array and remove unsynchronization padding if present
byte[] bytes = new byte[size];
Array.Copy(buffer, offset, bytes, 0, size);
if ((flags & 0x80) != 0)
bytes = UnsyncBytes(bytes);
var res = new ID3TagData();
int pos = 0;
// skip extended header if present
if ((flags & 0x40) != 0)
{
var ehSize = DecodeBEInt32(bytes, pos);
pos += ehSize + 4;
}
// load all frames from the tag buffer
for (var frame = ID3FrameData.ReadFrame(bytes, pos, out int frameSize); frameSize > 0 && frame != null; frame = ID3FrameData.ReadFrame(bytes, pos, out frameSize))
{
switch (frame.FrameID)
{
case "TIT2":
res.Title = frame.ParseString();
break;
case "TPE1":
res.Artist = frame.ParseString();
break;
case "TALB":
res.Album = frame.ParseString();
break;
case "TYER":
res.Year = frame.ParseString();
break;
case "COMM":
res.Comment = frame.ParseCommentText();
break;
case "TCON":
res.Genre = frame.ParseString();
break;
case "TRCK":
res.Track = frame.ParseString();
break;
case "TIT3":
res.Subtitle = frame.ParseString();
break;
case "TPE2":
res.AlbumArtist = frame.ParseString();
break;
case "TXXX":
{
var udt = frame.ParseUserDefinedText();
res.UserDefinedText[udt.Key] = udt.Value;
break;
}
case "APIC":
{
var pic = frame.ParseAPIC();
res.AlbumArt = pic?.ImageBytes;
break;
}
default:
break;
}
pos += frameSize;
}
return res;
}
/// <summary>
/// Check ID3v2 tag header is correctly formed
/// </summary>
/// <param name="buffer">Array containing ID3v2 header</param>
/// <returns>True if checks pass, else false</returns>
private static bool ValidateTagHeader(byte[] buffer)
=> buffer?.Length >= 4 && buffer[0] == 'I' && buffer[1] == 'D' && buffer[2] == '3' && buffer[3] == 3 && buffer[4] == 0;
/// <summary>
/// Decode a 28-bit integer stored in the low 7 bits of 4 bytes at the offset, most-significant bits first (big-endian).
/// </summary>
/// <param name="buffer">Array containing value to decode.</param>
/// <param name="offset">Offset in array of the 4 bytes containing the value.</param>
/// <returns>Decoded value.</returns>
private static int DecodeHeaderSize(byte[] buffer, int offset)
=> (int)(
((uint)buffer[offset] << 21) |
((uint)buffer[offset + 1] << 14) |
((uint)buffer[offset + 2] << 7) |
buffer[offset + 3]
);
/// <summary>
/// Read 16-bit integer from <paramref name="buffer"/> as 2 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>16-bit integer value.</returns>
private static short DecodeBEInt16(byte[] buffer, int offset)
=> (short)((buffer[offset] << 8) | buffer[offset + 1]);
/// <summary>
/// Read 32-bit integer from <paramref name="buffer"/> as 4 big-endian bytes at <paramref name="offset"/>.
/// </summary>
/// <param name="buffer">Byte array containing value.</param>
/// <param name="offset">Offset in byte array to start of value.</param>
/// <returns>32-bit integer value.</returns>
private static int DecodeBEInt32(byte[] buffer, int offset)
=> ((buffer[offset] << 24) | (buffer[offset + 1] << 16) | (buffer[offset + 2] << 8) | (buffer[offset + 3]));
/// <summary>
/// Remove NUL bytes inserted by 'unsynchronisation' of data buffer.
/// </summary>
/// <param name="buffer">Buffer with 'unsynchronized' data.</param>
/// <returns>New array with insertions removed.</returns>
private static byte[] UnsyncBytes(IEnumerable<byte> buffer)
{
IEnumerable<byte> ProcessBuffer()
{
byte prev = 0;
foreach (var b in buffer)
{
if (b != 0 || prev != 0xFF)
yield return b;
prev = b;
}
}
return ProcessBuffer().ToArray();
}
/// <summary>
/// Represents an ID3 frame read from the tag.
/// </summary>
private class ID3FrameData
{
/// <summary>
/// Four-character Frame ID.
/// </summary>
public readonly string FrameID;
/// <summary>
/// Size of the frame in bytes, not including the header. Should equal the size of the Data buffer.
/// </summary>
public readonly int Size;
/// <summary>
/// Frame header flags.
/// </summary>
public readonly short Flags;
/// <summary>
/// Frame content as bytes.
/// </summary>
public readonly byte[] Data;
// private constructor
private ID3FrameData(string frameID, int size, short flags, byte[] data)
{
FrameID = frameID;
Size = size;
Flags = flags;
Data = data;
}
/// <summary>
/// Read an ID3v2 content frame from the supplied buffer.
/// </summary>
/// <param name="buffer">Array containing content frame data.</param>
/// <param name="offset">Offset of start of content frame data.</param>
/// <param name="size">Output: total bytes consumed by frame, including header, or -1 if no frame available.</param>
/// <returns><see cref="ID3FrameData"/> with frame, or null if no frame available.</returns>
public static ID3FrameData ReadFrame(byte[] buffer, int offset, out int size)
{
size = -1;
if ((buffer.Length - offset) <= 10)
return null;
// Extract header data
string frameID = Encoding.ASCII.GetString(buffer, offset, 4);
int frameLength = DecodeBEInt32(buffer, offset + 4);
short frameFlags = DecodeBEInt16(buffer, offset + 8);
// copy frame content to byte array
byte[] content = new byte[frameLength];
Array.Copy(buffer, offset + 10, content, 0, frameLength);
// Decompress if necessary
if ((frameFlags & 0x80) != 0)
{
using (var ms = new MemoryStream())
using (var dec = new DeflateStream(new MemoryStream(content), CompressionMode.Decompress))
{
dec.CopyTo(ms);
content = ms.ToArray();
}
}
// return frame
size = 10 + frameLength;
return new ID3FrameData(frameID, frameLength, frameFlags, content);
}
/// <summary>
/// Read an ASCII string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetASCIIString(byte[] buffer, ref int offset, bool requireTerminator)
{
int start = offset;
int position = offset;
for (; position < buffer.Length && buffer[position] != 0; position++) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 1;
return length < 1 ? string.Empty : Encoding.ASCII.GetString(buffer, start, length);
}
/// <summary>
/// Read a Unicode string from an array, NUL-terminated or optionally end of buffer.
/// </summary>
/// <param name="buffer">Array containing ASCII string.</param>
/// <param name="offset">Start of string in array.</param>
/// <param name="requireTerminator">If true then fail if no terminator found.</param>
/// <returns>String from buffer, string.Empty if 0-length, null on failure.</returns>
private static string GetUnicodeString(byte[] buffer, ref int offset, bool requireTerminator = true)
{
int start = offset;
int position = offset;
for (; position < buffer.Length - 1 && (buffer[position] != 0 || buffer[position + 1] != 0); position += 2) ;
if (requireTerminator && position >= buffer.Length)
return null;
int length = position - start;
offset = position + 2;
string res = LameDLLWrap.UCS2.GetString(buffer, start, length);
return res;
}
delegate string delGetString(byte[] buffer, ref int offset, bool requireTeminator);
private delGetString GetGetString()
{
byte encoding = Data[0];
if (encoding == 0)
return GetASCIIString;
if (encoding == 1)
return GetUnicodeString;
throw new InvalidDataException($"Invalid string encoding: {encoding}");
}
/// <summary>
/// Parse the frame content as a string.
/// </summary>
/// <returns>String content, string.Empty if 0-length.</returns>
/// <exception cref="InvalidDataException">Invalid string encoding.</exception>
public string ParseString()
{
int position = 1;
return GetGetString()(Data, ref position, false);
}
/// <summary>
/// Parse the frame content as a Comment (COMM) frame, return comment text only.
/// </summary>
/// <returns>Comment text only. Language and short description omitted.</returns>
public string ParseCommentText()
{
var getstr = GetGetString();
int position = 1;
string language = Encoding.ASCII.GetString(Data, position, 3);
position += 3;
string shortdesc = getstr(Data, ref position, true);
string comment = getstr(Data, ref position, false);
return comment;
}
/// <summary>
/// Parse the frame content as a User-Defined Text Information (TXXX) frame.
/// </summary>
/// <returns><see cref="KeyValuePair{TKey, TValue}"/> with content, or exception on error.</returns>
public KeyValuePair<string, string> ParseUserDefinedText()
{
byte encoding = Data[0];
delGetString getstring;
if (encoding == 0)
getstring = GetASCIIString;
else if (encoding == 1)
getstring = GetUnicodeString;
else
throw new InvalidDataException($"Unknown string encoding: {encoding}");
int position = 1;
string description = getstring(Data, ref position, true);
string value = getstring(Data, ref position, false);
return new KeyValuePair<string, string>(description, value);
}
/// <summary>
/// Parse the frame content as an attached picture (APIC) frame.
/// </summary>
/// <returns><see cref="APICData"/> object </returns>
public APICData ParseAPIC()
{
if (FrameID != "APIC")
return null;
var getstr = GetGetString();
// get attributes
int position = 1;
string mime = getstr(Data, ref position, true);
byte type = Data[position++];
string description = getstr(Data, ref position, true);
// get image content
int datalength = Data.Length - position;
byte[] imgdata = new byte[datalength];
Array.Copy(Data, position, imgdata, 0, datalength);
return new APICData
{
MIMEType = mime,
ImageType = type,
Description = description,
ImageBytes = imgdata,
};
}
/// <summary>
/// Data for an Attached Picture (APIC) frame.
/// </summary>
public class APICData
{
/// <summary>
/// MIME type of contained image
/// </summary>
public string MIMEType;
/// <summary>
/// Type of image. Refer to http://id3.org/id3v2.3.0#Attached_picture for list of values.
/// </summary>
public byte ImageType;
/// <summary>
/// Picture description.
/// </summary>
public string Description;
/// <summary>
/// Picture file content.
/// </summary>
public byte[] ImageBytes;
}
}
}
}
| Corey-M/NAudio.Lame | NAudio.Lame/ID3Decoder.cs | C# | mit | 17,597 |
module Daemontools
VERSION = "0.1.3"
end
| vladimirich/daemontools | lib/daemontools/version.rb | Ruby | mit | 43 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ListRange} from '@angular/cdk/collections';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Inject,
Input,
NgZone,
OnDestroy,
OnInit,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {DomSanitizer, SafeStyle} from '@angular/platform-browser';
import {animationFrameScheduler, fromEvent, Observable, Subject} from 'rxjs';
import {sampleTime, take, takeUntil} from 'rxjs/operators';
import {CdkVirtualForOf} from './virtual-for-of';
import {VIRTUAL_SCROLL_STRATEGY, VirtualScrollStrategy} from './virtual-scroll-strategy';
/** Checks if the given ranges are equal. */
function rangesEqual(r1: ListRange, r2: ListRange): boolean {
return r1.start == r2.start && r1.end == r2.end;
}
/** A viewport that virtualizes it's scrolling with the help of `CdkVirtualForOf`. */
@Component({
moduleId: module.id,
selector: 'cdk-virtual-scroll-viewport',
templateUrl: 'virtual-scroll-viewport.html',
styleUrls: ['virtual-scroll-viewport.css'],
host: {
'class': 'cdk-virtual-scroll-viewport',
'[class.cdk-virtual-scroll-orientation-horizontal]': 'orientation === "horizontal"',
'[class.cdk-virtual-scroll-orientation-vertical]': 'orientation === "vertical"',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkVirtualScrollViewport implements OnInit, OnDestroy {
/** Emits when the viewport is detached from a CdkVirtualForOf. */
private _detachedSubject = new Subject<void>();
/** Emits when the rendered range changes. */
private _renderedRangeSubject = new Subject<ListRange>();
/** The direction the viewport scrolls. */
@Input() orientation: 'horizontal' | 'vertical' = 'vertical';
/** The element that wraps the rendered content. */
@ViewChild('contentWrapper') _contentWrapper: ElementRef;
/** A stream that emits whenever the rendered range changes. */
renderedRangeStream: Observable<ListRange> = this._renderedRangeSubject.asObservable();
/**
* The total size of all content (in pixels), including content that is not currently rendered.
*/
_totalContentSize = 0;
/** The transform used to offset the rendered content wrapper element. */
_renderedContentTransform: SafeStyle;
/** The raw string version of the rendered content transform. */
private _rawRenderedContentTransform: string;
/** The currently rendered range of indices. */
private _renderedRange: ListRange = {start: 0, end: 0};
/** The length of the data bound to this viewport (in number of items). */
private _dataLength = 0;
/** The size of the viewport (in pixels). */
private _viewportSize = 0;
/** The pending scroll offset to be applied during the next change detection cycle. */
private _pendingScrollOffset: number | null;
/** the currently attached CdkVirtualForOf. */
private _forOf: CdkVirtualForOf<any> | null;
/** The last rendered content offset that was set. */
private _renderedContentOffset = 0;
/**
* Whether the last rendered content offset was to the end of the content (and therefore needs to
* be rewritten as an offset to the start of the content).
*/
private _renderedContentOffsetNeedsRewrite = false;
/** Observable that emits when the viewport is destroyed. */
private _destroyed = new Subject<void>();
/** Whether there is a pending change detection cycle. */
private _isChangeDetectionPending = false;
/** A list of functions to run after the next change detection cycle. */
private _runAfterChangeDetection: Function[] = [];
constructor(public elementRef: ElementRef, private _changeDetectorRef: ChangeDetectorRef,
private _ngZone: NgZone, private _sanitizer: DomSanitizer,
@Inject(VIRTUAL_SCROLL_STRATEGY) private _scrollStrategy: VirtualScrollStrategy) {}
ngOnInit() {
// It's still too early to measure the viewport at this point. Deferring with a promise allows
// the Viewport to be rendered with the correct size before we measure. We run this outside the
// zone to avoid causing more change detection cycles. We handle the change detection loop
// ourselves instead.
this._ngZone.runOutsideAngular(() => Promise.resolve().then(() => {
this._measureViewportSize();
this._scrollStrategy.attach(this);
fromEvent(this.elementRef.nativeElement, 'scroll')
// Sample the scroll stream at every animation frame. This way if there are multiple
// scroll events in the same frame we only need to recheck our layout once.
.pipe(sampleTime(0, animationFrameScheduler), takeUntil(this._destroyed))
.subscribe(() => this._scrollStrategy.onContentScrolled());
this._markChangeDetectionNeeded();
}));
}
ngOnDestroy() {
this.detach();
this._scrollStrategy.detach();
this._destroyed.next();
// Complete all subjects
this._renderedRangeSubject.complete();
this._detachedSubject.complete();
this._destroyed.complete();
}
/** Attaches a `CdkVirtualForOf` to this viewport. */
attach(forOf: CdkVirtualForOf<any>) {
if (this._forOf) {
throw Error('CdkVirtualScrollViewport is already attached.');
}
// Subscribe to the data stream of the CdkVirtualForOf to keep track of when the data length
// changes. Run outside the zone to avoid triggering change detection, since we're managing the
// change detection loop ourselves.
this._ngZone.runOutsideAngular(() => {
this._forOf = forOf;
this._forOf.dataStream.pipe(takeUntil(this._detachedSubject)).subscribe(data => {
const newLength = data.length;
if (newLength !== this._dataLength) {
this._dataLength = newLength;
this._scrollStrategy.onDataLengthChanged();
}
});
});
}
/** Detaches the current `CdkVirtualForOf`. */
detach() {
this._forOf = null;
this._detachedSubject.next();
}
/** Gets the length of the data bound to this viewport (in number of items). */
getDataLength(): number {
return this._dataLength;
}
/** Gets the size of the viewport (in pixels). */
getViewportSize(): number {
return this._viewportSize;
}
// TODO(mmalerba): This is technically out of sync with what's really rendered until a render
// cycle happens. I'm being careful to only call it after the render cycle is complete and before
// setting it to something else, but its error prone and should probably be split into
// `pendingRange` and `renderedRange`, the latter reflecting whats actually in the DOM.
/** Get the current rendered range of items. */
getRenderedRange(): ListRange {
return this._renderedRange;
}
/**
* Sets the total size of all content (in pixels), including content that is not currently
* rendered.
*/
setTotalContentSize(size: number) {
if (this._totalContentSize !== size) {
this._totalContentSize = size;
this._markChangeDetectionNeeded();
}
}
/** Sets the currently rendered range of indices. */
setRenderedRange(range: ListRange) {
if (!rangesEqual(this._renderedRange, range)) {
this._renderedRangeSubject.next(this._renderedRange = range);
this._markChangeDetectionNeeded(() => this._scrollStrategy.onContentRendered());
}
}
/**
* Gets the offset from the start of the viewport to the start of the rendered data (in pixels).
*/
getOffsetToRenderedContentStart(): number | null {
return this._renderedContentOffsetNeedsRewrite ? null : this._renderedContentOffset;
}
/**
* Sets the offset from the start of the viewport to either the start or end of the rendered data
* (in pixels).
*/
setRenderedContentOffset(offset: number, to: 'to-start' | 'to-end' = 'to-start') {
const axis = this.orientation === 'horizontal' ? 'X' : 'Y';
let transform = `translate${axis}(${Number(offset)}px)`;
this._renderedContentOffset = offset;
if (to === 'to-end') {
// TODO(mmalerba): The viewport should rewrite this as a `to-start` offset on the next render
// cycle. Otherwise elements will appear to expand in the wrong direction (e.g.
// `mat-expansion-panel` would expand upward).
transform += ` translate${axis}(-100%)`;
this._renderedContentOffsetNeedsRewrite = true;
}
if (this._rawRenderedContentTransform != transform) {
// We know this value is safe because we parse `offset` with `Number()` before passing it
// into the string.
this._rawRenderedContentTransform = transform;
this._renderedContentTransform = this._sanitizer.bypassSecurityTrustStyle(transform);
this._markChangeDetectionNeeded(() => {
if (this._renderedContentOffsetNeedsRewrite) {
this._renderedContentOffset -= this.measureRenderedContentSize();
this._renderedContentOffsetNeedsRewrite = false;
this.setRenderedContentOffset(this._renderedContentOffset);
} else {
this._scrollStrategy.onRenderedOffsetChanged();
}
});
}
}
/** Sets the scroll offset on the viewport. */
setScrollOffset(offset: number) {
// Rather than setting the offset immediately, we batch it up to be applied along with other DOM
// writes during the next change detection cycle.
this._pendingScrollOffset = offset;
this._markChangeDetectionNeeded();
}
/** Gets the current scroll offset of the viewport (in pixels). */
measureScrollOffset(): number {
return this.orientation === 'horizontal' ?
this.elementRef.nativeElement.scrollLeft : this.elementRef.nativeElement.scrollTop;
}
/** Measure the combined size of all of the rendered items. */
measureRenderedContentSize(): number {
const contentEl = this._contentWrapper.nativeElement;
return this.orientation === 'horizontal' ? contentEl.offsetWidth : contentEl.offsetHeight;
}
/**
* Measure the total combined size of the given range. Throws if the range includes items that are
* not rendered.
*/
measureRangeSize(range: ListRange): number {
if (!this._forOf) {
return 0;
}
return this._forOf.measureRangeSize(range, this.orientation);
}
/** Update the viewport dimensions and re-render. */
checkViewportSize() {
// TODO: Cleanup later when add logic for handling content resize
this._measureViewportSize();
this._scrollStrategy.onDataLengthChanged();
}
/** Measure the viewport size. */
private _measureViewportSize() {
const viewportEl = this.elementRef.nativeElement;
this._viewportSize = this.orientation === 'horizontal' ?
viewportEl.clientWidth : viewportEl.clientHeight;
}
/** Queue up change detection to run. */
private _markChangeDetectionNeeded(runAfter?: Function) {
if (runAfter) {
this._runAfterChangeDetection.push(runAfter);
}
// Use a Promise to batch together calls to `_doChangeDetection`. This way if we set a bunch of
// properties sequentially we only have to run `_doChangeDetection` once at the end.
if (!this._isChangeDetectionPending) {
this._isChangeDetectionPending = true;
this._ngZone.runOutsideAngular(() => Promise.resolve().then(() => {
if (this._ngZone.isStable) {
this._doChangeDetection();
} else {
this._ngZone.onStable.pipe(take(1)).subscribe(() => this._doChangeDetection());
}
}));
}
}
/** Run change detection. */
private _doChangeDetection() {
this._isChangeDetectionPending = false;
// Apply changes to Angular bindings.
this._ngZone.run(() => this._changeDetectorRef.detectChanges());
// Apply the pending scroll offset separately, since it can't be set up as an Angular binding.
if (this._pendingScrollOffset != null) {
if (this.orientation === 'horizontal') {
this.elementRef.nativeElement.scrollLeft = this._pendingScrollOffset;
} else {
this.elementRef.nativeElement.scrollTop = this._pendingScrollOffset;
}
}
for (let fn of this._runAfterChangeDetection) {
fn();
}
this._runAfterChangeDetection = [];
}
}
| amcdnl/material2 | src/cdk-experimental/scrolling/virtual-scroll-viewport.ts | TypeScript | mit | 12,339 |
module Devise
module Hooks
# A small warden proxy so we can remember, forget and
# sign out users from hooks.
class Proxy #:nodoc:
include Devise::Controllers::Rememberable
include Devise::Controllers::SignInOut
attr_reader :warden
delegate :cookies, :env, :to => :warden
def initialize(warden)
@warden = warden
end
def session
warden.request.session
end
end
end
end
| QARIO/dochive | vendor/bundle/gems/devise-3.2.3/lib/devise/hooks/proxy.rb | Ruby | mit | 454 |
import array
import numbers
real_types = [numbers.Real]
int_types = [numbers.Integral]
iterable_types = [set, list, tuple, array.array]
try:
import numpy
except ImportError:
pass
else:
real_types.extend([numpy.float32, numpy.float64])
int_types.extend([numpy.int32, numpy.int64])
iterable_types.append(numpy.ndarray)
# use these with isinstance to test for various types that include builtins
# and numpy types (if numpy is available)
real_types = tuple(real_types)
int_types = tuple(int_types)
iterable_types = tuple(iterable_types)
| DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/typegroups.py | Python | mit | 558 |
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { toggleSelect } from '../actions/users';
import { createLink } from '../../utils';
class User extends Component {
render() {
const profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'bigger') : '';
const small_profile_image_url_https = this.props.user.profile_image_url_https ? this.props.user.profile_image_url_https.replace('normal', 'mini') : '';
var description = this.props.user.description;
if(description) {
description = description.replace(/@[A-Za-z_0-9]+/g, id => createLink(`https://twitter.com/${id.substring(1)}`, id));
this.props.user.entities.description.urls.forEach(url => description = description.replace(new RegExp(url.url, 'g'), createLink(url.expanded_url, url.expanded_url)));
}
return this.props.settings.showMode === 'card' ? (
<li className={'responsive-card ' + (this.props.user.select ? 'responsive-card--selected' : '')}>
<input type="checkbox" checked={this.props.user.select} className="user__select" onChange={this.props.toggleSelect} />
<div alt="" className="card-img-top" style={{
backgroundImage: this.props.user.profile_banner_url ? `url(${this.props.user.profile_banner_url + '/600x200'})` : 'none',
backgroundColor: !this.props.user.profile_banner_url ? `#${this.props.user.profile_link_color}` : 'transparent'
}} onClick={this.props.toggleSelect}></div>
<div className="card-block">
<div className="media">
<div className="media-left">
<img src={profile_image_url_https} width="73" height="73" className="media-left__icon" />
</div>
<div className="media-body">
<div className="card-title">
<div className="card-title__name">
{this.props.user.name}
</div>
<div className="card-title__screen-name">
<small>
<a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new" title={this.props.user.id_str}>@{this.props.user.screen_name}</a>
{this.props.user.protected ? (
<span>
<i className="fa fa-lock"></i>
</span>
) : null}
</small>
</div>
</div>
</div>
</div>
</div>
<ul className="list-group list-group-flush">
{
this.props.user.entities && this.props.user.entities.url ? (
<li className="list-group-item">
<a href={this.props.user.entities.url.urls[0].url} target="_new">
<i className="fa fa-link fa-fw"></i> {this.props.user.entities.url.urls[0].expanded_url ? this.props.user.entities.url.urls[0].expanded_url : this.props.user.entities.url.urls[0].url}</a>
</li>
) : null
}
{
this.props.user.location ? (
<li className="list-group-item">
<i className="fa fa-map-marker fa-fw"></i>
{this.props.user.location}
</li>
) : null
}
</ul>
{this.props.user.entities && !this.props.user.entities.url && !this.props.user.location ? <hr /> : null}
<div className="card-block">
<p className="card-text" dangerouslySetInnerHTML={{__html: description}}>
</p>
</div>
</li>
) : (
<tr onClick={e => {
if(['A', 'INPUT'].includes(e.target.tagName)) {
e.stopPropagation();
} else {
this.props.toggleSelect();
}
}}>
<td className="user-list-table__checkbox user-list-table__checkbox--row">
<input type="checkbox" checked={this.props.user.select} onChange={this.props.toggleSelect} />
</td>
<td className="user-list-table__name user-list-table__name--row"><img src={small_profile_image_url_https} width="24" height="24" /> {this.props.user.name}</td>
<td>
<a href={`https://twitter.com/${this.props.user.screen_name}`} target="_new">{this.props.user.screen_name}</a>
{this.props.user.protected ? (
<span>
<i className="fa fa-lock"></i>
</span>
) : null}
</td>
<td>{this.props.user.friends_count}</td>
<td>{this.props.user.followers_count}</td>
<td>{this.props.user.status ? moment(new Date(this.props.user.status.created_at)).format('YYYY/MM/DD HH:mm:ss') : null}</td>
</tr>
);
}
}
User.propTypes = {
userId: PropTypes.string.isRequired,
user: PropTypes.object.isRequired,
settings: PropTypes.object.isRequired
};
User.defaultProps = {
userId: '0',
user: {},
settings: {}
};
function mapStateToProps(state, ownProps) {
return {
user: state.users.users.allUserInfo[ownProps.userId],
settings: state.settings
};
}
function mapDispatchToProps(dispatch, ownProps) {
return {
toggleSelect() {
dispatch(toggleSelect(ownProps.userId));
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(User);
| sunya9/follow-manager | src/containers/User.js | JavaScript | mit | 5,320 |
<?php
/**
* This file is part of the PPI Framework.
*
* @copyright Copyright (c) 2011-2013 Paul Dragoonis <paul@ppi.io>
* @license http://opensource.org/licenses/mit-license.php MIT
* @link http://www.ppi.io
*/
namespace PPICacheModule\Cache\Driver;
use PPICacheModule\Cache\CacheInterface;
/**
* Memory cache driver.
*
* @author Vítor Brandão <vitor@ppi.io>
* @package PPI
* @subpackage Cache
*/
class MemoryCache implements CacheInterface
{
/**
* @var array $data
*/
protected $data = array();
/**
* {@inheritdoc}
*/
public function get($key)
{
return isset($this->data[$key]) ? new CacheItem($key, $this->data[$key]) : false;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->data[$key] = $value;
return true;
}
/**
* {@inheritdoc}
*/
public function remove($key)
{
unset($this->data[$key]);
return true;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys)
{
$items = array();
foreach ($keys as $key) {
$items[$key] = $this->get($key);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function setMultiple($items, $ttl = null)
{
$results = array();
foreach ($items as $key => $item) {
$this->data[$key] = $item;
$results[$key] = true;
}
return $results;
}
/**
* {@inheritdoc}
*/
public function removeMultiple($keys)
{
$results = array();
foreach ($keys as $key) {
unset($this->data[$key]);
$results[$key] = true;
}
return $results;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->data = array();
return true;
}
}
| ppi/cache | Cache/Driver/MemoryCache.php | PHP | mit | 1,925 |
/***
* Textile parser for JavaScript
*
* Copyright (c) 2012 Borgar Þorsteinsson (MIT License).
*
*/
/*jshint
laxcomma:true
laxbreak:true
eqnull:true
loopfunc:true
sub:true
*/
;(function(){
"use strict";
/***
* Regular Expression helper methods
*
* This provides the `re` object, which contains several helper
* methods for working with big regular expressions (soup).
*
*/
var re = {
_cache: {}
, pattern: {
'punct': "[!-/:-@\\[\\\\\\]-`{-~]"
, 'space': '\\s'
}
, escape: function ( src ) {
return src.replace( /[\-\[\]\{\}\(\)\*\+\?\.\,\\\^\$\|\#\s]/g, "\\$&" );
}
, collapse: function ( src ) {
return src.replace( /(?:#.*?(?:\n|$))/g, '' )
.replace( /\s+/g, '' )
;
}
, expand_patterns: function ( src ) {
// TODO: provide escape for patterns: \[:pattern:] ?
return src.replace( /\[\:\s*(\w+)\s*\:\]/g, function ( m, k ) {
return ( k in re.pattern )
? re.expand_patterns( re.pattern[ k ] )
: k
;
})
;
}
, isRegExp: function ( r ) {
return Object.prototype.toString.call( r ) === "[object RegExp]";
}
, compile: function ( src, flags ) {
if ( re.isRegExp( src ) ) {
if ( arguments.length === 1 ) { // no flags arg provided, use the RegExp one
flags = ( src.global ? 'g' : '' ) +
( src.ignoreCase ? 'i' : '' ) +
( src.multiline ? 'm' : '' );
}
src = src.source;
}
// don't do the same thing twice
var ckey = src + ( flags || '' );
if ( ckey in re._cache ) { return re._cache[ ckey ]; }
// allow classes
var rx = re.expand_patterns( src );
// allow verbose expressions
if ( flags && /x/.test( flags ) ) {
rx = re.collapse( rx );
}
// allow dotall expressions
if ( flags && /s/.test( flags ) ) {
rx = rx.replace( /([^\\])\./g, '$1[^\\0]' );
}
// TODO: test if MSIE and add replace \s with [\s\u00a0] if it is?
// clean flags and output new regexp
flags = ( flags || '' ).replace( /[^gim]/g, '' );
return ( re._cache[ ckey ] = new RegExp( rx, flags ) );
}
};
/***
* JSONML helper methods - http://www.jsonml.org/
*
* This provides the `JSONML` object, which contains helper
* methods for rendering JSONML to HTML.
*
* Note that the tag ! is taken to mean comment, this is however
* not specified in the JSONML spec.
*
*/
var JSONML = {
escape: function ( text, esc_quotes ) {
return text.replace( /&(?!(#\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});)/g, "&" )
.replace( /</g, "<" )
.replace( />/g, ">" )
.replace( /"/g, esc_quotes ? """ : '"' )
.replace( /'/g, esc_quotes ? "'" : "'" )
;
}
, toHTML: function ( jsonml ) {
jsonml = jsonml.concat();
// basic case
if ( typeof jsonml === "string" ) {
return JSONML.escape( jsonml );
}
var tag = jsonml.shift()
, attributes = {}
, content = []
, tag_attrs = ""
, a
;
if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !_isArray( jsonml[ 0 ] ) ) {
attributes = jsonml.shift();
}
while ( jsonml.length ) {
content.push( JSONML.toHTML( jsonml.shift() ) );
}
for ( a in attributes ) {
tag_attrs += ( attributes[ a ] == null )
? " " + a
: " " + a + '="' + JSONML.escape( String( attributes[ a ] ), true ) + '"'
;
}
// be careful about adding whitespace here for inline elements
if ( tag == "!" ) {
return "<!--" + content.join( "" ) + "-->";
}
else if ( tag === "img" || tag === "br" || tag === "hr" || tag === "input" ) {
return "<" + tag + tag_attrs + " />";
}
else {
return "<" + tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">";
}
}
};
// merge object b properties into obect a
function merge ( a, b ) {
for ( var k in b ) {
a[ k ] = b[ k ];
}
return a;
}
var _isArray = Array.isArray || function ( a ) { return Object.prototype.toString.call(a) === '[object Array]'; };
/* expressions */
re.pattern[ 'blocks' ] = '(?:b[qc]|div|notextile|pre|h[1-6]|fn\\d+|p|###)';
re.pattern[ 'pba_class' ] = '\\([^\\)]+\\)';
re.pattern[ 'pba_style' ] = '\\{[^\\}]+\\}';
re.pattern[ 'pba_lang' ] = '\\[[^\\[\\]]+\\]';
re.pattern[ 'pba_align' ] = '(?:<>|<|>|=)';
re.pattern[ 'pba_pad' ] = '[\\(\\)]+';
re.pattern[ 'pba_attr' ] = '(?:[:pba_class:]|[:pba_style:]|[:pba_lang:]|[:pba_align:]|[:pba_pad:])*';
re.pattern[ 'url_punct' ] = '[.,«»″‹›!?]';
re.pattern[ 'html_id' ] = '[a-zA-Z][a-zA-Z\\d:]*';
re.pattern[ 'html_attr' ] = '(?:"[^"]+"|\'[^\']+\'|[^>\\s]+)';
re.pattern[ 'tx_urlch' ] = '[\\w"$\\-_.+!*\'(),";\\/?:@=&%#{}|\\\\^~\\[\\]`]';
re.pattern[ 'tx_cite' ] = ':((?:[^\\s()]|\\([^\\s()]+\\)|[()])+?)(?=[!-\\.:-@\\[\\\\\\]-`{-~]+(?:$|\\s)|$|\\s)';
re.pattern[ 'listhd' ] = '[\\t ]*[\\#\\*]*(\\*|\\#(?:_|\\d+)?)[:pba_attr:](?: \\S|\\.\\s*(?=\\S|\\n))';
re.pattern[ 'ucaps' ] = "A-Z"+
// Latin extended À-Þ
"\u00c0-\u00d6\u00d8-\u00de"+
// Latin caps with embelishments and ligatures...
"\u0100\u0102\u0104\u0106\u0108\u010a\u010c\u010e\u0110\u0112\u0114\u0116\u0118\u011a\u011c\u011e\u0120\u0122\u0124\u0126\u0128\u012a\u012c\u012e\u0130\u0132\u0134\u0136\u0139\u013b\u013d\u013f"+
"\u0141\u0143\u0145\u0147\u014a\u014c\u014e\u0150\u0152\u0154\u0156\u0158\u015a\u015c\u015e\u0160\u0162\u0164\u0166\u0168\u016a\u016c\u016e\u0170\u0172\u0174\u0176\u0178\u0179\u017b\u017d"+
"\u0181\u0182\u0184\u0186\u0187\u0189-\u018b\u018e-\u0191\u0193\u0194\u0196-\u0198\u019c\u019d\u019f\u01a0\u01a2\u01a4\u01a6\u01a7\u01a9\u01ac\u01ae\u01af\u01b1-\u01b3\u01b5\u01b7\u01b8\u01bc"+
"\u01c4\u01c7\u01ca\u01cd\u01cf\u01d1\u01d3\u01d5\u01d7\u01d9\u01db\u01de\u01e0\u01e2\u01e4\u01e6\u01e8\u01ea\u01ec\u01ee\u01f1\u01f4\u01f6-\u01f8\u01fa\u01fc\u01fe"+
"\u0200\u0202\u0204\u0206\u0208\u020a\u020c\u020e\u0210\u0212\u0214\u0216\u0218\u021a\u021c\u021e\u0220\u0222\u0224\u0226\u0228\u022a\u022c\u022e\u0230\u0232\u023a\u023b\u023d\u023e"+
"\u0241\u0243-\u0246\u0248\u024a\u024c\u024e"+
"\u1e00\u1e02\u1e04\u1e06\u1e08\u1e0a\u1e0c\u1e0e\u1e10\u1e12\u1e14\u1e16\u1e18\u1e1a\u1e1c\u1e1e\u1e20\u1e22\u1e24\u1e26\u1e28\u1e2a\u1e2c\u1e2e\u1e30\u1e32\u1e34\u1e36\u1e38\u1e3a\u1e3c\u1e3e\u1e40"+
"\u1e42\u1e44\u1e46\u1e48\u1e4a\u1e4c\u1e4e\u1e50\u1e52\u1e54\u1e56\u1e58\u1e5a\u1e5c\u1e5e\u1e60\u1e62\u1e64\u1e66\u1e68\u1e6a\u1e6c\u1e6e\u1e70\u1e72\u1e74\u1e76\u1e78\u1e7a\u1e7c\u1e7e"+
"\u1e80\u1e82\u1e84\u1e86\u1e88\u1e8a\u1e8c\u1e8e\u1e90\u1e92\u1e94\u1e9e\u1ea0\u1ea2\u1ea4\u1ea6\u1ea8\u1eaa\u1eac\u1eae\u1eb0\u1eb2\u1eb4\u1eb6\u1eb8\u1eba\u1ebc\u1ebe"+
"\u1ec0\u1ec2\u1ec4\u1ec6\u1ec8\u1eca\u1ecc\u1ece\u1ed0\u1ed2\u1ed4\u1ed6\u1ed8\u1eda\u1edc\u1ede\u1ee0\u1ee2\u1ee4\u1ee6\u1ee8\u1eea\u1eec\u1eee\u1ef0\u1ef2\u1ef4\u1ef6\u1ef8\u1efa\u1efc\u1efe"+
"\u2c60\u2c62-\u2c64\u2c67\u2c69\u2c6b\u2c6d-\u2c70\u2c72\u2c75\u2c7e\u2c7f"+
"\ua722\ua724\ua726\ua728\ua72a\ua72c\ua72e\ua732\ua734\ua736\ua738\ua73a\ua73c\ua73e"+
"\ua740\ua742\ua744\ua746\ua748\ua74a\ua74c\ua74e\ua750\ua752\ua754\ua756\ua758\ua75a\ua75c\ua75e\ua760\ua762\ua764\ua766\ua768\ua76a\ua76c\ua76e\ua779\ua77b\ua77d\ua77e"+
"\ua780\ua782\ua784\ua786\ua78b\ua78d\ua790\ua792\ua7a0\ua7a2\ua7a4\ua7a6\ua7a8\ua7aa";
var re_block = re.compile( /^([:blocks:])/ )
, re_block_se = re.compile( /^[:blocks:]$/ )
, re_block_normal = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n(?:\s*\n|$)+)/, 's' )
, re_block_extended = re.compile( /^(.*?)($|\r?\n(?=[:listhd:])|\r?\n+(?=[:blocks:][:pba_attr:]\.))/, 's' )
, re_ruler = /^(\-\-\-+|\*\*\*+|___+)(\r?\n\s+|$)/
, re_list = re.compile( /^((?:[:listhd:][^\0]*?(?:\r?\n|$))+)(\s*\n|$)/,'s' )
, re_list_item = re.compile( /^([\#\*]+)([^\0]+?)(\n(?=[:listhd:])|$)/, 's' )
, re_deflist = /^((?:- (?:[^\n]\n?)+?)+:=(?: *\n[^\0]+?=:(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- )))))+/
, re_deflist_item = /^((?:- (?:[^\n]\n?)+?)+):=( *\n[^\0]+?=:\s*(?:\n|$)|(?:[^\0]+?(?:$|\n(?=\n|- ))))/
, re_table = re.compile( /^((?:table[:pba_attr:]\.\n)?(?:(?:[:pba_attr:]\.[^\n\S]*)?\|.*?\|[^\n\S]*(?:\n|$))+)([^\n\S]*\n)?/, 's' )
, re_table_head = /^table(_?)([^\n]+)\.\s?\n/
, re_table_row = re.compile( /^([:pba_attr:]\.[^\n\S]*)?\|(.*?)\|[^\n\S]*(\n|$)/, 's' )
, re_fenced_phrase = /^\[(__?|\*\*?|\?\?|[\-\+\^~@%])([^\n]+)\1\]/
, re_phrase = /^([\[\{]?)(__?|\*\*?|\?\?|[\-\+\^~@%])/
, re_text = re.compile( /^.+?(?=[\\<!\[_\*`]|\n|$)/, 's' )
, re_image = re.compile( /^!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?/ )
, re_image_fenced = re.compile( /^\[!(?!\s)([:pba_attr:](?:\.[^\n\S]|\.(?:[^\.\/]))?)([^!\s]+?) ?(?:\(((?:[^\(\)]+|\([^\(\)]+\))+)\))?!(?::([^\s]+?(?=[!-\.:-@\[\\\]-`{-~](?:$|\s)|\s|$)))?\]/ )
// NB: there is an exception in here to prevent matching "TM)"
, re_caps = re.compile( /^((?!TM\)|tm\))[[:ucaps:]](?:[[:ucaps:]\d]{1,}(?=\()|[[:ucaps:]\d]{2,}))(?:\((.*?)\))?(?=\W|$)/ )
, re_link = re.compile( /^"(?!\s)((?:[^\n"]|"(?![\s:])[^\n"]+"(?!:))+)"[:tx_cite:]/ )
, re_link_fenced = /^\["([^\n]+?)":((?:\[[a-z0-9]*\]|[^\]])+)\]/
, re_link_ref = re.compile( /^\[([^\]]+)\]((?:https?:\/\/|\/)\S+)(?:\s*\n|$)/ )
, re_link_title = /\s*\(((?:\([^\(\)]*\)|[^\(\)])+)\)$/
, re_footnote_def = /^fn\d+$/
, re_footnote = /^\[(\d+)(\!?)\]/
// HTML
, re_html_tag_block = re.compile( /^\s*<([:html_id:](?::[a-zA-Z\d]+)*)((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ )
, re_html_tag = re.compile( /^<([:html_id:])((?:\s[^=\s\/]+(?:\s*=\s*[:html_attr:])?)+)?\s*(\/?)>(\n*)/ )
, re_html_comment = re.compile( /^<!--(.+?)-->/, 's' )
, re_html_end_tag = re.compile( /^<\/([:html_id:])([^>]*)>/ )
, re_html_attr = re.compile( /^\s*([^=\s]+)(?:\s*=\s*("[^"]+"|'[^']+'|[^>\s]+))?/ )
, re_entity = /&(#\d\d{2,}|#x[\da-fA-F]{2,}|[a-zA-Z][a-zA-Z1-4]{1,6});/
// glyphs
, re_dimsign = /([\d\.,]+['"]? ?)x( ?)(?=[\d\.,]['"]?)/g
, re_emdash = /(^|[\s\w])--([\s\w]|$)/g
, re_trademark = /(\b ?|\s|^)(?:\((?:TM|tm)\)|\[(?:TM|tm)\])/g
, re_registered = /(\b ?|\s|^)(?:\(R\)|\[R\])/gi
, re_copyright = /(\b ?|\s|^)(?:\(C\)|\[C\])/gi
, re_apostrophe = /(\w)\'(\w)/g
, re_double_prime = re.compile( /(\d*[\.,]?\d+)"(?=\s|$|[:punct:])/g )
, re_single_prime = re.compile( /(\d*[\.,]?\d+)'(?=\s|$|[:punct:])/g )
, re_closing_dquote = re.compile( /([^\s\[\(])"(?=$|\s|[:punct:])/g )
, re_closing_squote = re.compile( /([^\s\[\(])'(?=$|\s|[:punct:])/g )
// pba
, re_pba_classid = /^\(([^\(\)\n]+)\)/
, re_pba_padding_l = /^(\(+)/
, re_pba_padding_r = /^(\)+)/
, re_pba_align_blk = /^(<>|<|>|=)/
, re_pba_align_img = /^(<|>|=)/
, re_pba_valign = /^(~|\^|\-)/
, re_pba_colspan = /^\\(\d+)/
, re_pba_rowspan = /^\/(\d+)/
, re_pba_styles = /^\{([^\}]*)\}/
, re_pba_css = /^\s*([^:\s]+)\s*:\s*(.+)\s*$/
, re_pba_lang = /^\[([^\[\]\n]+)\]/
;
var phrase_convert = {
'*': 'strong'
, '**': 'b'
, '??': 'cite'
, '_': 'em'
, '__': 'i'
, '-': 'del'
, '%': 'span'
, '+': 'ins'
, '~': 'sub'
, '^': 'sup'
, '@': 'code'
};
// area, base, basefont, bgsound, br, col, command, embed, frame, hr,
// img, input, keygen, link, meta, param, source, track or wbr
var html_singletons = {
'br': 1
, 'hr': 1
, 'img': 1
, 'link': 1
, 'meta': 1
, 'wbr': 1
, 'area': 1
, 'param': 1
, 'input': 1
, 'option': 1
, 'base': 1
};
var pba_align_lookup = {
'<': 'left'
, '=': 'center'
, '>': 'right'
, '<>': 'justify'
};
var pba_valign_lookup = {
'~':'bottom'
, '^':'top'
, '-':'middle'
};
// HTML tags allowed in the document (root) level that trigger HTML parsing
var allowed_blocktags = {
'p': 0
, 'hr': 0
, 'ul': 1
, 'ol': 0
, 'li': 0
, 'div': 1
, 'pre': 0
, 'object': 1
, 'script': 0
, 'noscript': 0
, 'blockquote': 1
, 'notextile': 1
};
function ribbon ( feed ) {
var _slot = null
, org = feed + ''
, pos = 0
;
return {
save: function () {
_slot = pos;
}
, load: function () {
pos = _slot;
feed = org.slice( pos );
}
, advance: function ( n ) {
pos += ( typeof n === 'string' ) ? n.length : n;
return ( feed = org.slice( pos ) );
}
, lookbehind: function ( nchars ) {
nchars = nchars == null ? 1 : nchars;
return org.slice( pos - nchars, pos );
}
, startsWith: function ( s ) {
return feed.substring(0, s.length) === s;
}
, valueOf: function(){
return feed;
}
, toString: function(){
return feed;
}
};
}
function builder ( arr ) {
var _arr = _isArray( arr ) ? arr : [];
return {
add: function ( node ) {
if ( typeof node === 'string' &&
typeof _arr[_arr.length - 1 ] === 'string' ) {
// join if possible
_arr[ _arr.length - 1 ] += node;
}
else if ( _isArray( node ) ) {
var f = node.filter(function(s){ return s !== undefined; });
_arr.push( f );
}
else if ( node ) {
_arr.push( node );
}
return this;
}
, merge: function ( s ) {
for (var i=0,l=s.length; i<l; i++) {
this.add( s[i] );
}
return this;
}
, linebreak: function () {
if ( _arr.length ) {
this.add( '\n' );
}
}
, get: function () {
return _arr;
}
};
}
function copy_pba ( s, blacklist ) {
if ( !s ) { return undefined; }
var k, d = {};
for ( k in s ) {
if ( k in s && ( !blacklist || !(k in blacklist) ) ) {
d[ k ] = s[ k ];
}
}
return d;
}
function parse_html_attr ( attr ) {
// parse ATTR and add to element
var _attr = {}
, m
, val
;
while ( (m = re_html_attr.exec( attr )) ) {
_attr[ m[1] ] = ( typeof m[2] === 'string' )
? m[2].replace( /^(["'])(.*)\1$/, '$2' )
: null
;
attr = attr.slice( m[0].length );
}
return _attr;
}
// This "indesciminately" parses HTML text into a list of JSON-ML element
// No steps are taken however to prevent things like <table><p><td> - user can still create nonsensical but "well-formed" markup
function parse_html ( src, whitelist_tags ) {
var org = src + ''
, list = []
, root = list
, _stack = []
, m
, oktag = whitelist_tags ? function ( tag ) { return tag in whitelist_tags; } : function () { return true; }
, tag
;
src = (typeof src === 'string') ? ribbon( src ) : src;
// loop
do {
if ( (m = re_html_comment.exec( src )) && oktag('!') ) {
src.advance( m[0] );
list.push( [ '!', m[1] ] );
}
// end tag
else if ( (m = re_html_end_tag.exec( src )) && oktag(m[1]) ) {
tag = m[1];
var junk = m[2];
if ( _stack.length ) {
for (var i=_stack.length-1; i>=0; i--) {
var head = _stack[i];
if ( head[0] === tag ) {
_stack.splice( i );
list = _stack[ _stack.length - 1 ] || root;
break;
}
}
}
src.advance( m[0] );
}
// open/void tag
else if ( (m = re_html_tag.exec( src )) && oktag(m[1]) ) {
src.advance( m[0] );
tag = m[1];
var single = m[3] || m[1] in html_singletons
, tail = m[4]
, element = [ tag ]
;
// attributes
if ( m[2] ) { element.push( parse_html_attr( m[2] ) ); }
// tag
if ( single ) { // single tag
// let us add the element and continue our quest...
list.push( element );
if ( tail ) { list.push( tail ); }
}
else { // open tag
if ( tail ) { element.push( tail ); }
// TODO: some things auto close other things: <td>, <li>, <p>, <table>
// if ( tag === 'p' && _stack.length ) {
// var seek = /^(p)$/;
// for (var i=_stack.length-1; i>=0; i--) {
// var head = _stack[i];
// if ( seek.test( head[0] ) /* === tag */ ) {
// //src.advance( m[0] );
// _stack.splice( i );
// list = _stack[i] || root;
// }
// }
// }
// TODO: some elements can move parser into "text" mode
// style, xmp, iframe, noembed, noframe, textarea, title, script, noscript, plaintext
//if ( /^(script)$/.test( tag ) ) { }
_stack.push( element );
list.push( element );
list = element;
}
}
else {
// no match, move by all "uninteresting" chars
m = /([^<]+|[^\0])/.exec( src );
if ( m ) {
list.push( m[0] );
}
src.advance( m ? m[0].length || 1 : 1 );
}
}
while ( src.valueOf() );
return root;
}
/* attribute parser */
function parse_attr ( input, element, end_token ) {
/*
The attr bit causes massive problems for span elements when parentheses are used.
Parentheses are a total mess and, unsurprisingly, cause trip-ups:
RC: `_{display:block}(span) span (span)_` -> `<em style="display:block;" class="span">(span) span (span)</em>`
PHP: `_{display:block}(span) span (span)_` -> `<em style="display:block;">(span) span (span)</em>`
PHP and RC seem to mostly solve this by not parsing a final attr parens on spans if the
following character is a non-space. I've duplicated that: Class/ID is not matched on spans
if it is followed by `end_token` or <space>.
Lang is not matched here if it is followed by the end token. Theoretically I could limit the lang
attribute to /^\[[a-z]{2+}(\-[a-zA-Z0-9]+)*\]/ because Textile is layered on top of HTML which
only accepts valid BCP 47 language tags, but who knows what atrocities are being preformed
out there in the real world. So this attempts to emulate the other libraries.
*/
input += '';
if ( !input || element === 'notextile' ) { return undefined; }
var m
, st = {}
, o = { 'style': st }
, remaining = input
, is_block = element === 'table' || element === 'td' || re_block_se.test( element ) // "in" test would be better but what about fn#.?
, is_img = element === 'img'
, is_list = element === 'li'
, is_phrase = !is_block && !is_img && element !== 'a'
, re_pba_align = ( is_img ) ? re_pba_align_img : re_pba_align_blk
;
do {
if ( (m = re_pba_styles.exec( remaining )) ) {
m[1].split(';').forEach(function(p){
var d = p.match( re_pba_css );
if ( d ) { st[ d[1] ] = d[2]; }
});
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_lang.exec( remaining )) ) {
var rm = remaining.slice( m[0].length );
if (
( !rm && is_phrase ) ||
( end_token && end_token === rm.slice(0,end_token.length) )
) {
m = null;
}
else {
o['lang'] = m[1];
remaining = remaining.slice( m[0].length );
}
continue;
}
if ( (m = re_pba_classid.exec( remaining )) ) {
var rm = remaining.slice( m[0].length );
if (
( !rm && is_phrase ) ||
( end_token && (rm[0] === ' ' || end_token === rm.slice(0,end_token.length)) )
) {
m = null;
}
else {
var bits = m[1].split( '#' );
if ( bits[0] ) { o['class'] = bits[0]; }
if ( bits[1] ) { o['id'] = bits[1]; }
remaining = rm;
}
continue;
}
if ( is_block || is_list ) {
if ( (m = re_pba_padding_l.exec( remaining )) ) {
st[ "padding-left" ] = ( m[1].length ) + "em";
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_padding_r.exec( remaining )) ) {
st[ "padding-right" ] = ( m[1].length ) + "em";
remaining = remaining.slice( m[0].length );
continue;
}
}
// only for blocks:
if ( is_img || is_block || is_list ) {
if ( (m = re_pba_align.exec( remaining )) ) {
var align = pba_align_lookup[ m[1] ];
if ( is_img ) {
o[ 'align' ] = align;
}
else {
st[ 'text-align' ] = align;
}
remaining = remaining.slice( m[0].length );
continue;
}
}
// only for table cells
if ( element === 'td' || element === 'tr' ) {
if ( (m = re_pba_valign.exec( remaining )) ) {
st[ "vertical-align" ] = pba_valign_lookup[ m[1] ];
remaining = remaining.slice( m[0].length );
continue;
}
}
if ( element === 'td' ) {
if ( (m = re_pba_colspan.exec( remaining )) ) {
o[ "colspan" ] = m[1];
remaining = remaining.slice( m[0].length );
continue;
}
if ( (m = re_pba_rowspan.exec( remaining )) ) {
o[ "rowspan" ] = m[1];
remaining = remaining.slice( m[0].length );
continue;
}
}
}
while ( m );
// collapse styles
var s = [];
for ( var v in st ) { s.push( v + ':' + st[v] ); }
if ( s.length ) { o.style = s.join(';'); } else { delete o.style; }
return remaining == input
? undefined
: [ input.length - remaining.length, o ]
;
}
/* glyph parser */
function parse_glyphs ( src ) {
if ( typeof src !== 'string' ) { return src; }
// NB: order is important here ...
return src
// arrow
.replace( /([^\-]|^)->/, '$1→' ) // arrow
// dimensions
.replace( re_dimsign, '$1×$2' ) // dimension sign
// ellipsis
.replace( /([^.]?)\.{3}/g, '$1…' ) // ellipsis
// dashes
.replace( re_emdash, '$1—$2' ) // em dash
.replace( / - /g, ' – ' ) // en dash
// legal marks
.replace( re_trademark, '$1™' ) // trademark
.replace( re_registered, '$1®' ) // registered
.replace( re_copyright, '$1©' ) // copyright
// double quotes
.replace( re_double_prime, '$1″' ) // double prime
.replace( re_closing_dquote, '$1”' ) // double closing quote
.replace( /"/g, '“' ) // double opening quote
// single quotes
.replace( re_single_prime, '$1′' ) // single prime
.replace( re_apostrophe, '$1’$2' ) // I'm an apostrophe
.replace( re_closing_squote, '$1’' ) // single closing quote
.replace( /'/g, '‘' )
// fractions and degrees
.replace( /[\(\[]1\/4[\]\)]/, '¼' )
.replace( /[\(\[]1\/2[\]\)]/, '½' )
.replace( /[\(\[]3\/4[\]\)]/, '¾' )
.replace( /[\(\[]o[\]\)]/, '°' )
.replace( /[\(\[]\+\/\-[\]\)]/, '±' )
;
}
/* list parser */
function list_pad ( n ) {
var s = '\n';
while ( n-- ) { s += '\t'; }
return s;
}
function parse_list ( src, options ) {
src = ribbon( src.replace( /(^|\r?\n)[\t ]+/, '$1' ) );
var stack = []
, curr_idx = {}
, last_idx = options._lst || {}
, list_pba
, item_index = 0
, m
, n
, s
;
while ( (m = re_list_item.exec( src )) ) {
var item = [ 'li' ]
, start_index = 0
, dest_level = m[1].length
, type = m[1].substr(-1) === '#' ? 'ol' : 'ul'
, new_li = null
, lst
, par
, pba
, r
;
// list starts and continuations
if ( n = /^(_|\d+)/.exec( m[2] ) ) {
item_index = isFinite( n[1] )
? parseInt( n[1], 10 )
: last_idx[ dest_level ] || curr_idx[ dest_level ] || 1;
m[2] = m[2].slice( n[1].length );
}
if ( pba = parse_attr( m[2], 'li' ) ) {
m[2] = m[2].slice( pba[0] );
pba = pba[1];
}
// list control
if ( /^\.\s*$/.test( m[2] ) ) {
list_pba = pba || {};
src.advance( m[0] );
continue;
}
// create nesting until we have correct level
while ( stack.length < dest_level ) {
// list always has an attribute object, this simplifies first-pba resolution
lst = [ type, {}, list_pad( stack.length + 1 ), (new_li = [ 'li' ]) ];
par = stack[ stack.length - 1 ];
if ( par ) {
par.li.push( list_pad( stack.length ) );
par.li.push( lst );
}
stack.push({
ul: lst
, li: new_li
, att: 0 // count pba's found per list
});
curr_idx[ stack.length ] = 1;
}
// remove nesting until we have correct level
while ( stack.length > dest_level ) {
r = stack.pop();
r.ul.push( list_pad( stack.length ) );
// lists have a predictable structure - move pba from listitem to list
if ( r.att === 1 && !r.ul[3][1].substr ) {
merge( r.ul[1], r.ul[3].splice( 1, 1 )[ 0 ] );
}
}
// parent list
par = stack[ stack.length - 1 ];
// have list_pba or start_index?
if ( item_index ) {
par.ul[1].start = curr_idx[ dest_level ] = item_index;
item_index = 0; // falsy prevents this from fireing until it is set again
}
if ( list_pba ) {
par.att = 9; // "more than 1" prevent pba transfers on list close
merge( par.ul[1], list_pba );
list_pba = null;
}
if ( !new_li ) {
par.ul.push( list_pad( stack.length ), item );
par.li = item;
}
if ( pba ) {
par.li.push( pba );
par.att++;
}
Array.prototype.push.apply( par.li, parse_inline( m[2].trim(), options ) );
src.advance( m[0] );
curr_idx[ dest_level ] = (curr_idx[ dest_level ] || 0) + 1;
}
// remember indexes for continuations next time
options._lst = curr_idx;
while ( stack.length ) {
s = stack.pop();
s.ul.push( list_pad( stack.length ) );
// lists have a predictable structure - move pba from listitem to list
if ( s.att === 1 && !s.ul[3][1].substr ) {
merge( s.ul[1], s.ul[3].splice( 1, 1 )[ 0 ] );
}
}
return s.ul;
}
/* definitions list parser */
function parse_deflist ( src, options ) {
src = ribbon( src.trim() );
var deflist = [ 'dl', '\n' ]
, terms
, def
, m
;
while ( (m = re_deflist_item.exec( src )) ) {
// add terms
terms = m[1].split( /(?:^|\n)\- / ).slice(1);
while ( terms.length ) {
deflist.push( '\t'
, [ 'dt' ].concat( parse_inline( terms.shift().trim(), options ) )
, '\n'
);
}
// add definitions
def = m[2].trim();
deflist.push( '\t'
, [ 'dd' ].concat(
/=:$/.test( def )
? parse_blocks( def.slice(0,-2).trim(), options )
: parse_inline( def, options )
)
, '\n'
);
src.advance( m[0] );
}
return deflist;
}
/* table parser */
function parse_table ( src, options ) {
src = ribbon( src.trim() );
var table = [ 'table' ]
, row
, inner
, pba
, more
, m
;
if ( (m = re_table_head.exec( src )) ) {
// parse and apply table attr
src.advance( m[0] );
pba = parse_attr( m[2], 'table' );
if ( pba ) {
table.push( pba[1] );
}
}
while ( (m = re_table_row.exec( src )) ) {
row = [ 'tr' ];
if ( m[1] && (pba = parse_attr( m[1], 'tr' )) ) {
// FIXME: requires "\.\s?" -- else what ?
row.push( pba[1] );
}
table.push( '\n\t', row );
inner = ribbon( m[2] );
do {
inner.save();
// cell loop
var th = inner.startsWith( '_' )
, cell = [ th ? 'th' : 'td' ]
;
if ( th ) {
inner.advance( 1 );
}
pba = parse_attr( inner, 'td' );
if ( pba ) {
inner.advance( pba[0] );
cell.push( pba[1] ); // FIXME: don't do this if next text fails
}
if ( pba || th ) {
var d = /^\.\s*/.exec( inner );
if ( d ) {
inner.advance( d[0] );
}
else {
cell = [ 'td' ];
inner.load();
}
}
var mx = /^(==.*?==|[^\|])*/.exec( inner );
cell = cell.concat( parse_inline( mx[0], options ) );
row.push( '\n\t\t', cell );
more = inner.valueOf().charAt( mx[0].length ) === '|';
inner.advance( mx[0].length + 1 );
}
while ( more );
row.push( '\n\t' );
src.advance( m[0] );
}
table.push( '\n' );
return table;
}
/* inline parser */
function parse_inline ( src, options ) {
src = ribbon( src );
var list = builder()
, m
, pba
;
// loop
do {
src.save();
// linebreak -- having this first keeps it from messing to much with other phrases
if ( src.startsWith( '\r\n' ) ) {
src.advance( 1 ); // skip cartridge returns
}
if ( src.startsWith( '\n' ) ) {
src.advance( 1 );
if ( options.breaks ) {
list.add( [ 'br' ] );
}
list.add( '\n' );
continue;
}
// inline notextile
if ( (m = /^==(.*?)==/.exec( src )) ) {
src.advance( m[0] );
list.add( m[1] );
continue;
}
// lookbehind => /([\s>.,"'?!;:])$/
var behind = src.lookbehind( 1 );
var boundary = !behind || /^[\s>.,"'?!;:()]$/.test( behind );
// FIXME: need to test right boundary for phrases as well
if ( (m = re_phrase.exec( src )) && ( boundary || m[1] ) ) {
src.advance( m[0] );
var tok = m[2]
, fence = m[1]
, phrase_type = phrase_convert[ tok ]
, code = phrase_type === 'code'
;
if ( (pba = !code && parse_attr( src, phrase_type, tok )) ) {
src.advance( pba[0] );
pba = pba[1];
}
// FIXME: if we can't match the fence on the end, we should output fence-prefix as normal text
// seek end
var m_mid;
var m_end;
if ( fence === '[' ) {
m_mid = '^(.*?)';
m_end = '(?:])';
}
else if ( fence === '{' ) {
m_mid = '^(.*?)';
m_end = '(?:})';
}
else {
var t1 = re.escape( tok.charAt(0) );
m_mid = ( code )
? '^(\\S+|\\S+.*?\\S)'
: '^([^\\s' + t1 + ']+|[^\\s' + t1 + '].*?\\S('+t1+'*))'
;
m_end = '(?=$|[\\s.,"\'!?;:()«»„“”‚‘’])';
}
var rx = re.compile( m_mid + '(' + re.escape( tok ) + ')' + m_end );
if ( (m = rx.exec( src )) && m[1] ) {
src.advance( m[0] );
if ( code ) {
list.add( [ phrase_type, m[1] ] );
}
else {
list.add( [ phrase_type, pba ].concat( parse_inline( m[1], options ) ) );
}
continue;
}
// else
src.load();
}
// image
if ( (m = re_image.exec( src )) || (m = re_image_fenced.exec( src )) ) {
src.advance( m[0] );
pba = m[1] && parse_attr( m[1], 'img' );
var attr = pba ? pba[1] : { 'src':'' }
, img = [ 'img', attr ]
;
attr.src = m[2];
attr.alt = m[3] ? ( attr.title = m[3] ) : '';
if ( m[4] ) { // +cite causes image to be wraped with a link (or link_ref)?
// TODO: support link_ref for image cite
img = [ 'a', { 'href': m[4] }, img ];
}
list.add( img );
continue;
}
// html comment
if ( (m = re_html_comment.exec( src )) ) {
src.advance( m[0] );
list.add( [ '!', m[1] ] );
continue;
}
// html tag
// TODO: this seems to have a lot of overlap with block tags... DRY?
if ( (m = re_html_tag.exec( src )) ) {
src.advance( m[0] );
var tag = m[1]
, single = m[3] || m[1] in html_singletons
, element = [ tag ]
, tail = m[4]
;
if ( m[2] ) {
element.push( parse_html_attr( m[2] ) );
}
if ( single ) { // single tag
list.add( element ).add( tail );
continue;
}
else { // need terminator
// gulp up the rest of this block...
var re_end_tag = re.compile( "^(.*?)(</" + tag + "\\s*>)", 's' );
if ( (m = re_end_tag.exec( src )) ) {
src.advance( m[0] );
if ( tag === 'code' ) {
element.push( tail, m[1] );
}
else if ( tag === 'notextile' ) {
list.merge( parse_inline( m[1], options ) );
continue;
}
else {
element = element.concat( parse_inline( m[1], options ) );
}
list.add( element );
continue;
}
// end tag is missing, treat tag as normal text...
}
src.load();
}
// footnote
if ( (m = re_footnote.exec( src )) && /\S/.test( behind ) ) {
src.advance( m[0] );
list.add( [ 'sup', { 'class': 'footnote', 'id': 'fnr' + m[1] },
( m[2] === '!' ? m[1] // "!" suppresses the link
: [ 'a', { href: '#fn' + m[1] }, m[1] ] )
] );
continue;
}
// caps / abbr
if ( (m = re_caps.exec( src )) ) {
src.advance( m[0] );
var caps = [ 'span', { 'class': 'caps' }, m[1] ];
if ( m[2] ) {
caps = [ 'acronym', { 'title': m[2] }, caps ]; // FIXME: use <abbr>, not acronym!
}
list.add( caps );
continue;
}
// links
if ( (boundary && (m = re_link.exec( src ))) || (m = re_link_fenced.exec( src )) ) {
src.advance( m[0].length );
var title = m[1].match( re_link_title )
, inner = ( title ) ? m[1].slice( 0, m[1].length - title[0].length ) : m[1]
;
if ( (pba = parse_attr( inner, 'a' )) ) {
inner = inner.slice( pba[0] );
pba = pba[1];
}
else {
pba = {};
}
if ( title && !inner ) { inner = title[0]; title = ""; }
pba.href = m[2];
if ( title ) { pba.title = title[1]; }
list.add( [ 'a', pba ].concat( parse_inline( inner.replace( /^(\.?\s*)/, '' ), options ) ) );
continue;
}
// no match, move by all "uninteresting" chars
m = /([a-zA-Z0-9,.':]+|[ \f\r\t\v\xA0\u2028\u2029]+|[^\0])/.exec( src );
if ( m ) {
list.add( m[0] );
}
src.advance( m ? m[0].length || 1 : 1 );
}
while ( src.valueOf() );
return list.get().map( parse_glyphs );
}
/* block parser */
function parse_blocks ( src, options ) {
var list = builder()
, paragraph = function ( s, tag, pba, linebreak ) {
tag = tag || 'p';
var out = [];
s.split( /(?:\r?\n){2,}/ ).forEach(function( bit, i ) {
if ( tag === 'p' && /^\s/.test( bit ) ) {
// no-paragraphs
// WTF?: Why does Textile not allow linebreaks in spaced lines
bit = bit.replace( /\r?\n[\t ]/g, ' ' ).trim();
out = out.concat( parse_inline( bit, options ) );
}
else {
if ( linebreak && i ) { out.push( linebreak ); }
out.push( pba ? [ tag, pba ].concat( parse_inline( bit, options ) )
: [ tag ].concat( parse_inline( bit, options ) ) );
}
});
return out;
}
, link_refs = {}
, m
;
src = ribbon( src.replace( /^( *\r?\n)+/, '' ) );
// loop
while ( src.valueOf() ) {
src.save();
// link_ref -- this goes first because it shouldn't trigger a linebreak
if ( (m = re_link_ref.exec( src )) ) {
src.advance( m[0] );
link_refs[ m[1] ] = m[2];
continue;
}
// add linebreak
list.linebreak();
// named block
if ( (m = re_block.exec( src )) ) {
src.advance( m[0] );
var block_type = m[0]
, pba = parse_attr( src, block_type )
;
if ( pba ) {
src.advance( pba[0] );
pba = pba[1];
}
if ( (m = /^\.(\.?)(?:\s|(?=:))/.exec( src )) ) {
// FIXME: this whole copy_pba seems rather strange?
// slurp rest of block
var extended = !!m[1];
m = ( extended ? re_block_extended : re_block_normal ).exec( src.advance( m[0] ) );
src.advance( m[0] );
// bq | bc | notextile | pre | h# | fn# | p | ###
if ( block_type === 'bq' ) {
var cite, inner = m[1];
if ( (m = /^:(\S+)\s+/.exec( inner )) ) {
if ( !pba ) { pba = {}; }
pba.cite = m[1];
inner = inner.slice( m[0].length );
}
// RedCloth adds all attr to both: this is bad because it produces duplicate IDs
list.add( [ 'blockquote', pba, '\n' ].concat(
paragraph( inner, 'p', copy_pba(pba, { 'cite':1, 'id':1 }), '\n' )
).concat(['\n']) );
}
else if ( block_type === 'bc' ) {
var sub_pba = ( pba ) ? copy_pba(pba, { 'id':1 }) : null;
list.add( [ 'pre', pba, ( sub_pba ? [ 'code', sub_pba, m[1] ] : [ 'code', m[1] ] ) ] );
}
else if ( block_type === 'notextile' ) {
list.merge( parse_html( m[1] ) );
}
else if ( block_type === '###' ) {
// ignore the insides
}
else if ( block_type === 'pre' ) {
// I disagree with RedCloth, but agree with PHP here:
// "pre(foo#bar).. line1\n\nline2" prevents multiline preformat blocks
// ...which seems like the whole point of having an extended pre block?
list.add( [ 'pre', pba, m[1] ] );
}
else if ( re_footnote_def.test( block_type ) ) { // footnote
// Need to be careful: RedCloth fails "fn1(foo#m). footnote" -- it confuses the ID
var fnid = block_type.replace( /\D+/g, '' );
if ( !pba ) { pba = {}; }
pba['class'] = ( pba['class'] ? pba['class'] + ' ' : '' ) + 'footnote';
pba['id'] = 'fn' + fnid;
list.add( [ "p", pba, [ 'a', { 'href': '#fnr' + fnid }, [ 'sup', fnid ] ], ' ' ].concat( parse_inline( m[1], options ) ) );
}
else { // heading | paragraph
list.merge( paragraph( m[1], block_type, pba, '\n' ) );
}
continue;
}
else {
src.load();
}
}
// HTML comment
if ( (m = re_html_comment.exec( src )) ) {
src.advance( m[0] + (/(?:\s*\n+)+/.exec( src ) || [])[0] );
list.add( [ '!', m[1] ] );
continue;
}
// block HTML
if ( (m = re_html_tag_block.exec( src )) ) {
var tag = m[1]
, single = m[3] || tag in html_singletons
, tail = m[4]
;
// Unsurprisingly, all Textile implementations I have tested have trouble parsing simple HTML:
//
// "<div>a\n<div>b\n</div>c\n</div>d"
//
// I simply match them here as there is no way anyone is using nested HTML today, or if they
// are, then this will at least output less broken HTML as redundant tags will get quoted.
// Is block tag? ...
if ( tag in allowed_blocktags ) {
src.advance( m[0] );
var element = [ tag ];
if ( m[2] ) {
element.push( parse_html_attr( m[2] ) );
}
if ( single ) { // single tag
// let us add the element and continue our quest...
list.add( element );
continue;
}
else { // block
// gulp up the rest of this block...
var re_end_tag = re.compile( "^(.*?)(\\s*)(</" + tag + "\\s*>)(\\s*)", 's' );
if ( (m = re_end_tag.exec( src )) ) {
src.advance( m[0] );
if ( tag === 'pre' ) {
element.push( tail );
element = element.concat( parse_html( m[1].replace( /(\r?\n)+$/, '' ), { 'code': 1 } ) );
if ( m[2] ) { element.push( m[2] ); }
list.add( element );
}
else if ( tag === 'notextile' ) {
element = parse_html( m[1].trim() );
list.merge( element );
}
else if ( tag === 'script' || tag === 'noscript' ) {
//element = parse_html( m[1].trim() );
element.push( tail + m[1] );
list.add( element );
}
else {
// These strange (and unnecessary) linebreak tests are here to get the
// tests working perfectly. In reality, this doesn't matter one bit.
if ( /\n/.test( tail ) ) { element.push( '\n' ); }
if ( /\n/.test( m[1] ) ) {
element = element.concat( parse_blocks( m[1], options ) );
}
else {
element = element.concat( parse_inline( m[1].replace( /^ +/, '' ), options ) );
}
if ( /\n/.test( m[2] ) ) { element.push( '\n' ); }
list.add( element );
}
continue;
}
/*else {
// end tag is missing, treat tag as normal text...
}*/
}
}
src.load();
}
// ruler
if ( (m = re_ruler.exec( src )) ) {
src.advance( m[0] );
list.add( [ 'hr' ] );
continue;
}
// list
if ( (m = re_list.exec( src )) ) {
src.advance( m[0] );
list.add( parse_list( m[0], options ) );
continue;
}
// definition list
if ( (m = re_deflist.exec( src )) ) {
src.advance( m[0] );
list.add( parse_deflist( m[0], options ) );
continue;
}
// table
if ( (m = re_table.exec( src )) ) {
src.advance( m[0] );
list.add( parse_table( m[1], options ) );
continue;
}
// paragraph
m = re_block_normal.exec( src );
list.merge( paragraph( m[1], 'p', undefined, "\n" ) );
src.advance( m[0] );
}
return list.get().map( fix_links, link_refs );
}
// recurse the tree and swap out any "href" attributes
function fix_links ( jsonml ) {
if ( _isArray( jsonml ) ) {
if ( jsonml[0] === 'a' ) { // found a link
var attr = jsonml[1];
if ( typeof attr === "object" && 'href' in attr && attr.href in this ) {
attr.href = this[ attr.href ];
}
}
for (var i=1,l=jsonml.length; i<l; i++) {
if ( _isArray( jsonml[i] ) ) {
fix_links.call( this, jsonml[i] );
}
}
}
return jsonml;
}
/* exposed */
function textile ( txt, opt ) {
// get a throw-away copy of options
opt = merge( merge( {}, textile.defaults ), opt || {} );
// run the converter
return parse_blocks( txt, opt ).map( JSONML.toHTML ).join( '' );
}
// options
textile.defaults = {
'breaks': true // single-line linebreaks are converted to <br> by default
};
textile.setOptions = textile.setoptions = function ( opt ) {
merge( textile.defaults, opt );
return this;
};
textile.parse = textile.convert = textile;
textile.html_parser = parse_html;
textile.jsonml = function ( txt, opt ) {
// get a throw-away copy of options
opt = merge( merge( {}, textile.defaults ), opt || {} );
// parse and return tree
return [ 'html' ].concat( parse_blocks( txt, opt ) );
};
textile.serialize = JSONML.toHTML;
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = textile;
}
else {
this.textile = textile;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
| muffinmad/atom-textile-preview | lib/textile.js | JavaScript | mit | 45,902 |
package com.smartbit8.laravelstorm.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.ide.browsers.*;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter;
import com.intellij.util.xmlb.XmlSerializer;
import com.jetbrains.php.config.interpreters.PhpInterpreter;
import com.jetbrains.php.config.interpreters.PhpInterpretersManagerImpl;
import com.smartbit8.laravelstorm.ui.LaravelRunConfSettingsEditor;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class LaravelRunConf extends RunConfigurationBase {
private Project project;
private String host = "localhost";
private int port = 8000;
private String route = "/";
private WebBrowser browser;
private PhpInterpreter interpreter;
LaravelRunConf(@NotNull Project project, @NotNull ConfigurationFactory factory, String name) {
super(project, factory, name);
this.project = project;
}
@Override
public void createAdditionalTabComponents(AdditionalTabComponentManager manager, ProcessHandler startedProcess) {
LogTab logTab = new LogTab(getProject());
manager.addAdditionalTabComponent(logTab, "Laravel.log");
startedProcess.addProcessListener(new ProcessAdapter() {
@Override
public void startNotified(ProcessEvent event) {
logTab.start();
}
@Override
public void processTerminated(ProcessEvent event) {
startedProcess.removeProcessListener(this);
}
});
}
@Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
Settings settings = XmlSerializer.deserialize(element, Settings.class);
this.host = settings.host;
this.port = settings.port;
this.route = settings.route;
this.browser = WebBrowserManager.getInstance().findBrowserById(settings.browser);
this.interpreter = PhpInterpretersManagerImpl.getInstance(getProject()).findInterpreter(settings.interpreterName);
}
@Override
public void writeExternal(Element element) throws WriteExternalException {
Settings settings = new Settings();
settings.host = this.host;
settings.port = this.port;
settings.route = this.route;
if (this.browser != null)
settings.browser = this.browser.getId().toString();
else
settings.browser = "";
if (this.interpreter != null)
settings.interpreterName = this.interpreter.getName();
else
settings.interpreterName = "";
XmlSerializer.serializeInto(settings, element, new SkipDefaultsSerializationFilter());
super.writeExternal(element);
}
@NotNull
@Override
public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() {
return new LaravelRunConfSettingsEditor(getProject());
}
@Override
public void checkConfiguration() throws RuntimeConfigurationException {}
@Nullable
@Override
public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment executionEnvironment) throws ExecutionException {
return new CommandLineState(executionEnvironment) {
@NotNull
@Override
protected ProcessHandler startProcess() throws ExecutionException {
String phpExec = (interpreter != null? interpreter.getPathToPhpExecutable():"php");
GeneralCommandLine cmd = new GeneralCommandLine(phpExec, "artisan", "serve", "--host=" + host, "--port="+ port);
cmd.setWorkDirectory(project.getBasePath());
OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void onTextAvailable(ProcessEvent event, Key outputType) {
String text = event.getText();
if (text != null){
if (text.startsWith("Laravel development server started:")){
BrowserLauncher.getInstance().browse("http://" + host + ":" + port +
(route.startsWith("/") ? route : "/" + route), browser);
handler.removeProcessListener(this);
}
}
}
});
// new LaravelRunMgr(handler, new File(getProject().getBasePath()+("/storage/logs/laravel.log")));
return handler;
}
};
}
public int getPort() {
return port;
}
public String getHost() {
return host;
}
public void setPort(int port) {
this.port = port;
}
public void setHost(String host) {
this.host = host;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public WebBrowser getBrowser() {
return browser;
}
public void setBrowser(WebBrowser browser) {
this.browser = browser;
}
public PhpInterpreter getInterpreter() {
return interpreter;
}
public void setInterpreter(PhpInterpreter interpreter) {
this.interpreter = interpreter;
}
public static class Settings {
public String host;
public int port;
public String route;
public String browser;
public String interpreterName;
}
}
| 3mmarg97/LaravelStorm | src/com/smartbit8/laravelstorm/run/LaravelRunConf.java | Java | mit | 6,140 |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :question do
sq_no '2'
query 'What is Ruby?'
question_type "Hard"
association :level
association :content
after(:build) do |question|
FactoryGirl.create(:correct, :question => question)
2.times {|i| FactoryGirl.create(:incorrect, :question => question)}
end
end
end
| techvision/brails | spec/factories/questions.rb | Ruby | mit | 411 |
/*! Copyright 2011, Ben Lin (http://dreamerslab.com/)
* Licensed under the MIT License (LICENSE.txt).
*
* Version: 1.0.0
*
* Requires: jQuery 1.2.3+
*/
$.preload = function(){
var tmp = [], i = arguments.length;
// reverse loop run faster
for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ] ));
}; | dreamerslab/ci.view | example_site/assets/js/lib/jquery.preload.js | JavaScript | mit | 320 |
/*jshint indent: 4, browser:true*/
/*global L*/
/*
* L.TimeDimension.Player
*/
//'use strict';
L.TimeDimension.Player = (L.Layer || L.Class).extend({
includes: (L.Evented || L.Mixin.Events),
initialize: function(options, timeDimension) {
L.setOptions(this, options);
this._timeDimension = timeDimension;
this._paused = false;
this._buffer = this.options.buffer || 5;
this._minBufferReady = this.options.minBufferReady || 1;
this._waitingForBuffer = false;
this._loop = this.options.loop || false;
this._steps = 1;
this._timeDimension.on('timeload', (function(data) {
this.release(); // free clock
this._waitingForBuffer = false; // reset buffer
}).bind(this));
this.setTransitionTime(this.options.transitionTime || 1000);
this._timeDimension.on('limitschanged availabletimeschanged timeload', (function(data) {
this._timeDimension.prepareNextTimes(this._steps, this._minBufferReady, this._loop);
}).bind(this));
},
_tick: function() {
var maxIndex = this._getMaxIndex();
var maxForward = (this._timeDimension.getCurrentTimeIndex() >= maxIndex) && (this._steps > 0);
var maxBackward = (this._timeDimension.getCurrentTimeIndex() == 0) && (this._steps < 0);
if (maxForward || maxBackward) {
// we reached the last step
if (!this._loop) {
this.pause();
this.stop();
this.fire('animationfinished');
return;
}
}
if (this._paused) {
return;
}
var numberNextTimesReady = 0,
buffer = this._bufferSize;
if (this._minBufferReady > 0) {
numberNextTimesReady = this._timeDimension.getNumberNextTimesReady(this._steps, buffer, this._loop);
// If the player was waiting, check if all times are loaded
if (this._waitingForBuffer) {
if (numberNextTimesReady < buffer) {
console.log('Waiting until buffer is loaded. ' + numberNextTimesReady + ' of ' + buffer + ' loaded');
this.fire('waiting', {
buffer: buffer,
available: numberNextTimesReady
});
return;
} else {
// all times loaded
console.log('Buffer is fully loaded!');
this.fire('running');
this._waitingForBuffer = false;
}
} else {
// check if player has to stop to wait and force to full all the buffer
if (numberNextTimesReady < this._minBufferReady) {
console.log('Force wait for load buffer. ' + numberNextTimesReady + ' of ' + buffer + ' loaded');
this._waitingForBuffer = true;
this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop);
this.fire('waiting', {
buffer: buffer,
available: numberNextTimesReady
});
return;
}
}
}
this.pause();
this._timeDimension.nextTime(this._steps, this._loop);
if (buffer > 0) {
this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop);
}
},
_getMaxIndex: function(){
return Math.min(this._timeDimension.getAvailableTimes().length - 1,
this._timeDimension.getUpperLimitIndex() || Infinity);
},
start: function(numSteps) {
if (this._intervalID) return;
this._steps = numSteps || 1;
this._waitingForBuffer = false;
var startedOver = false;
if (this.options.startOver){
if (this._timeDimension.getCurrentTimeIndex() === this._getMaxIndex()){
this._timeDimension.setCurrentTimeIndex(this._timeDimension.getLowerLimitIndex() || 0);
startedOver = true;
}
}
this.release();
this._intervalID = window.setInterval(
L.bind(this._tick, this),
this._transitionTime);
if (!startedOver)
this._tick();
this.fire('play');
this.fire('running');
},
stop: function() {
if (!this._intervalID) return;
clearInterval(this._intervalID);
this._intervalID = null;
this._waitingForBuffer = false;
this.fire('stop');
},
pause: function() {
this._paused = true;
},
release: function () {
this._paused = false;
},
getTransitionTime: function() {
return this._transitionTime;
},
isPlaying: function() {
return this._intervalID ? true : false;
},
isWaiting: function() {
return this._waitingForBuffer;
},
isLooped: function() {
return this._loop;
},
setLooped: function(looped) {
this._loop = looped;
this.fire('loopchange', {
loop: looped
});
},
setTransitionTime: function(transitionTime) {
this._transitionTime = transitionTime;
if (typeof this._buffer === 'function') {
this._bufferSize = this._buffer.call(this, this._transitionTime, this._minBufferReady, this._loop);
console.log('Buffer size changed to ' + this._bufferSize);
} else {
this._bufferSize = this._buffer;
}
if (this._intervalID) {
this.stop();
this.start(this._steps);
}
this.fire('speedchange', {
transitionTime: transitionTime,
buffer: this._bufferSize
});
},
getSteps: function() {
return this._steps;
}
}); | geofbaum/geofbaum.github.io | src/leaflet.timedimension.player.js | JavaScript | mit | 5,914 |
<?php
namespace pagosBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\DBAL\DriverManager;
class pagoRepository extends EntityRepository
{
public function facturar($lineas,$entidad,$cuenta) {
$datos=array('serie'=>'',
'folio'=>'',
'empresa_id'=>'',
'observaciones'=>'',
'fecha'=>'',
'cliente_id'=>$entidad->getClienteId(),
'receptor_nombre'=>$entidad->getRazonSocial(),
'receptor_rfc'=>$entidad->getRfc(),
'calle'=>$entidad->getCalle(),
'no_exterior'=>$entidad->getNoExterior(),
'no_interior'=>$entidad->getNoInterior(),
'referencia'=>$entidad->getReferencia(),
'colonia'=>$entidad->getColonia(),
'municipio'=>$entidad->getMunicipio(),
'codigo_postal'=>$entidad->getCodigoPostal(),
'localidad'=>$entidad->getLocalidad(),
'estado'=>$entidad->getEstado(),
'pais'=>$entidad->getPais(),
'forma_de_pago'=>'Pago en una sola exhibición',
'condiciones_de_pago'=>'',
'moneda_id'=>'MXN',
'tipo_cambio'=>'1',
'metodo_de_pago'=>'targeta',
'num_cuenta_pago'=>$cuenta,
'fecha_vencimiento'=>date('d/m/Y'),
'vendedor_id'=>'',
'vendedor_nombre'=>'',
'opReq1'=>'ventas:facturas_venta:facturas_venta:Add','operaciones'=>'2');
$x=0;
foreach ($lineas as $linea ) {
$masDatos[]=array(
'conceptos['.$x.'][sku]'=>'SERVICIO',
'conceptos['.$x.'][cantidad]'=>$linea->getCantidad(),
'conceptos['.$x.'][no_identificacion]'=>'',
'conceptos['.$x.'][cuenta_predial_numero]'=>'',
'conceptos['.$x.'][precio_unitario]'=>$linea->getTotal(),
'conceptos['.$x.'][precio_lista]'=>$linea->getTotal(),
'conceptos['.$x.'][descuento]'=>'0',
'conceptos['.$x.'][tipo_descuento]'=>'F',
'conceptos['.$x.'][factor_descuento]'=>'0',
'conceptos['.$x.'][importe_precio_lista]'=>$linea->getTotal(),
'conceptos['.$x.'][importe]'=>$linea->getTotal(),
'conceptos['.$x.'][importe_ieps]'=>'0',
'conceptos['.$x.'][observaciones]'=>'',
'conceptos['.$x.'][unidad_id]'=>'PZ',
'conceptos['.$x.'][usa_lotes]'=>'N',
'conceptos['.$x.'][usa_series]'=>'N',
'conceptos['.$x.'][es_paquete]'=>'N',
'conceptos['.$x.'][almacenable]'=>'N',
'conceptos['.$x.'][costo]'=>'0',
'conceptos['.$x.'][impuestos_traslados][0][esquema_impuestos_id]'=>'IVA_GENERAL',
'conceptos['.$x.'][impuestos_traslados][0][impuesto]'=>'IVA',
'conceptos['.$x.'][impuestos_traslados][0][aplicacion]'=>'T',
'conceptos['.$x.'][impuestos_traslados][0][tasa]'=>'16.0000',
'conceptos['.$x.'][impuestos_traslados][0][num_impuesto]'=>'1',
'conceptos['.$x.'][impuestos_traslados][0][importe]'=>'0.16',
'conceptos['.$x.'][pedido_serie]'=>'',
'conceptos['.$x.'][pedido_folio]'=>'',
'conceptos['.$x.'][pedido_item]'=>'',
'conceptos['.$x.'][impuestos_retenciones]'=>'',
'conceptos['.$x.'][lista_precios_id]'=>'',
'conceptos['.$x.'][descripcion]'=>'SERVICIO'
);
$x++;
}
$req='';
$req1='';
foreach ($datos as $key => $value)
{
$fullipnA[$key] = $value;
$encodedvalue = urlencode(stripslashes($value));
$req .= "&$key=$encodedvalue";
}
for($i=0;$i<count($masDatos); $i++){
foreach ($masDatos[$i] as $key => $value)
{
$fullipnA[$key] = $value;
$encodedvalue = urlencode(stripslashes($value));
$req1 .= "&$key=$encodedvalue";
}
}
// echo $req;
$url='https://e.sisnet.mx:7443/SisnetV3/php/responseweb.php';
$curl_result=$curl_err='';
$varPost="&workspace=default&usuario=demo&contrasena=demo&sucursal=aps_01|MATRIZ|43&resultType=xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_CERTINFO,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$varPost.$req.$req1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$datos= curl_exec ($ch);
curl_close ($ch);
//echo $datos;
$resultado=explode('||', $datos);
$max_int_length = strlen((string) PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $resultado[1]);
// echo $json_without_bigints;
$elarrid = json_decode($json_without_bigints,true, 512);
return $elarrid['record'];
}
public function sellar($datos,$usuario){
$valores=array('opReq1'=>'ventas:facturas_venta:facturas_venta:OpenCFD',
'empresa_id'=>$datos['empresa_id'],
'serie'=>$datos['serie'],
'folio'=>$datos['folio'],
'preview'=>'true',
'opReq2'=>'ventas:facturas_venta:facturas_venta:SendMail',
'nombre'=>$usuario->getNombre(),
'correo'=>$usuario->getEmail(),'operaciones'=>'3');
$req='';
foreach ($valores as $key => $value)
{
$fullipnA[$key] = $value;
$encodedvalue = urlencode(stripslashes($value));
$req .= "&$key=$encodedvalue";
}
$url='https://e.sisnet.mx:7443/SisnetV3/php/responseweb.php';
$curl_result=$curl_err='';
$varPost="&workspace=default&usuario=demo&contrasena=demo&sucursal=aps_01|MATRIZ|43&resultType=xml";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_CERTINFO,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$varPost.$req);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//$datos= curl_exec ($ch);
curl_close ($ch);
echo $datos;
$resultado=explode('||', $datos);
/*$max_int_length = strlen((string) PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $resultado[1]);
// echo $json_without_bigints;
$elarrid = json_decode($json_without_bigints,true, 512);*/
}
public function addMonth($dates,$num = 1,$format='d/m/Y')
{
$date = $dates->format('Y-n-j');
list($y, $m, $d) = explode('-', $date);
$m += $num;
while ($m > 12)
{
$m -= 12;
$y++;
}
$last_day = date('t', strtotime("$y-$m-1"));
if ($d > $last_day)
{
$d = $last_day;
}
$dates->setDate($y, $m, $d);
return $dates->format($format);
}
}
| elmaspicudo/algo | src/pagosBundle/Entity/pagoRepository.php | PHP | mit | 8,184 |
package com.bitdubai.fermat_bnk_api.layer.bnk_wallet.bank_money.exceptions;
import com.bitdubai.fermat_api.FermatException;
/**
* Created by Yordin Alayn on 18.09.15.
*/
public class CantTransactionBankMoneyException extends FermatException {
public static final String DEFAULT_MESSAGE = "Falled To Get Bank Transaction Wallet Bank Money.";
public CantTransactionBankMoneyException(String message, Exception cause, String context, String possibleReason) {
super(message, cause, context, possibleReason);
}
}
| fvasquezjatar/fermat-unused | fermat-bnk-api/src/main/java/com/bitdubai/fermat_bnk_api/layer/bnk_wallet/bank_money/exceptions/CantTransactionBankMoneyException.java | Java | mit | 533 |
<?php
namespace SMARTASK\HomeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SMARTASK\UserBundle\Entity\User ;
use FOS\ElasticaBundle\Configuration\Search;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Task
*
* @ORM\Table(name="task")
* @Search(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository")
* @ORM\Entity(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository")
*/
class Task
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Many Tasks have Many Users.
* @ORM\ManyToMany(targetEntity="SMARTASK\UserBundle\Entity\User", mappedBy="tasks")
*/
private $users;
/**
* @var string
*
* @ORM\Column(name="titre", type="string", length=255, unique=true)
* @Assert\Length(min=5)
* @Assert\NotBlank()
*/
private $titre;
/**
* @var string
*
* @ORM\Column(name="localisation", type="string", length=255, nullable=true)
*/
private $localisation;
/**
* One Task has One Groupe.
* @ORM\ManyToOne(targetEntity="SMARTASK\HomeBundle\Entity\Groupe")
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $group;
/**
* One Task has One resp.
* @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User")
* @ORM\JoinColumn(name="resp_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $resp;
/**
* One Task has One Manager.
* @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User")
* @ORM\JoinColumn(name="manager_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
private $manager;
/**
* @var datetime
*
* @ORM\Column(name="date", type="date", nullable=true)
*/
private $date;
/**
* @var time
*
* @ORM\Column(name="time", type="time", nullable=true)
* @Assert\DateTime()
*/
private $time;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var int
*
* @ORM\Column(name="isalarmeon", type="integer", nullable=true)
*/
private $isalarmeon;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* @param string $titre
*
* @return Task
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* @return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set localisation
*
* @param string $localisation
*
* @return Task
*/
public function setLocalisation($localisation)
{
$this->localisation = $localisation;
return $this;
}
/**
* Get localisation
*
* @return string
*/
public function getLocalisation()
{
return $this->localisation;
}
/**
* Set group
*
* @param Group $group
*
* @return Task
*/
public function setGroup($group)
{
$this->group = $group;
return $this;
}
/**
* Get group
*
* @return Group
*/
public function getGroup()
{
return $this->group;
}
/**
* Set resp
*
* @param Contact $resp
*
* @return Task
*/
public function setResp($resp)
{
$this->resp = $resp;
return $this;
}
/**
* Get manager
*
* @return User
*/
public function getManager()
{
return $this->manager;
}
/**
* Set manager
*
* @param Contact $manager
*
* @return Task
*/
public function setManager($manager)
{
$this->manager = $manager;
return $this;
}
/**
* Get resp
*
* @return Contact
*/
public function getResp()
{
return $this->resp;
}
/**
* Set date
*
* @param date $datetime
*
* @return Task
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get datetime
*
* @return datetime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* @param time $time
*
* @return Task
*/
public function setTime($time)
{
$this->time = $time;
return $this;
}
/**
* Get time
*
* @return time
*/
public function getTime()
{
return $this->time;
}
/**
* Set description
*
* @param string $description
*
* @return Task
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set isalarmeon
*
* @param integer $isalarmeon
*
* @return Task
*/
public function setIsalarmeon($isalarmeon)
{
$this->isalarmeon = $isalarmeon;
return $this;
}
/**
* Get isalarmeon
*
* @return int
*/
public function getIsalarmeon()
{
return $this->isalarmeon;
}
public function getUsers() {
return $this->users;
}
public function setUsers($users) {
$this->users = $users;
return $this;
}
}
| tonymayflower/smartask | src/SMARTASK/HomeBundle/Entity/Task.php | PHP | mit | 5,793 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Deivis
*/
public class Cotacao {
private int id;
private Date data;
private Double valor;
private TipoMoeda tipoMoeda;
public TipoMoeda getTipoMoeda() {
return tipoMoeda;
}
public void setTipoMoeda(TipoMoeda tipoMoeda) {
this.tipoMoeda = tipoMoeda;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getData() {
return data;
}
public String getDataString() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(this.data);
} else {
return null;
}
}
public String getDataStringBr() {
if (this.data != null) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
return df.format(this.data);
} else {
return null;
}
}
public void setData(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataBr(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public void setDataString(String data) throws ParseException {
if (!"".equals(data)) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
this.data = df.parse(data);
} else {
this.data = null;
}
}
public Double getValor() {
return valor;
}
public String getValorString() {
return valor.toString();
}
public void setValor(String valor) {
if (!"".equals(valor)) {
this.valor = Double.parseDouble(valor.replace(",", "."));
} else {
this.valor = null;
}
}
}
| deivisvieira/PosJava | src/java/modelo/Cotacao.java | Java | mit | 2,527 |
<?php
namespace MM\Util\Dummy;
trigger_error("simulating php error/warining");
class Dummy2 {
} | marianmeres/mm-php | mm-util/tests/MM/Util/Dummy/Dummy2.php | PHP | mit | 98 |
<?php
/*
Safe sample
input : Uses popen to read the file /tmp/tainted.txt using cat command
sanitize : settype (float)
construction : use of sprintf via a %d
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$handle = popen('/bin/cat /tmp/tainted.txt', 'r');
$tainted = fread($handle, 4096);
pclose($handle);
if(settype($tainted, "float"))
$tainted = $tainted ;
else
$tainted = 0.0 ;
$query = sprintf("SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, a.city, a.street & (' ' +a.housenum) AS address FROM Employees AS a WHERE a.supervisor=%d", $tainted);
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_89/safe/CWE_89__popen__CAST-func_settype_float__multiple_AS-sprintf_%d.php | PHP | mit | 1,780 |
'use strict';
angular.module('mean.settings').config(['$stateProvider',
function($stateProvider) {
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/');
}
});
return deferred.promise;
};
$stateProvider.state('settings', {
url: '/settings',
templateUrl: 'settings/views/index.html',
resolve: {
loggedin: checkLoggedin
}
});
}
]);
| indie-hackathon/dchat | packages/custom/settings/public/routes/settings.js | JavaScript | mit | 787 |
import Express = require("express");
import Geohash = require("latlon-geohash");
import Nconf = require("nconf");
import Path = require("path");
import * as multer from "multer";
import { Picnic } from "../../models/Picnic";
import { User } from "../../models/User";
import { Module } from "../Module";
import { UserModule } from "../user/UserModule";
// Load Configuration
Nconf.file(Path.join(__dirname, "../../../config.json"));
const picknicConfig = Nconf.get("picknic");
export class DataModule extends Module {
public addRoutes(app: Express.Application) {
// Tables
app.post("/data/tables/find/near", (req: Express.Request, res: Express.Response) => {
const bounds = req.body;
const query = Picnic.find({}).limit(picknicConfig.data.near.default).where("geometry").near(bounds).lean();
query.exec().then((tables: any) => {
res.send(tables);
});
});
app.post("/data/tables/find/within", (req: Express.Request, res: Express.Response) => {
const bounds = req.body;
Picnic.find({}).where("geometry").within(bounds).lean().exec().then((tables) => {
res.send(tables);
});
});
app.get("/data/tables/get", (req: Express.Request, res: Express.Response) => {
const id = req.query.id;
if (id) {
Picnic.findById(id).lean().exec().then((table) => {
res.send(table);
});
} else {
res.send("Error: No ID supplied.");
}
});
app.get("/data/tables/heatmap", (req: Express.Request, res: Express.Response) => {
// TODO: Add admin permissions, because this is quite computational.
Picnic.find().lean().exec().then((tables: any) => {
// Geohash the locations, and calculate the number of tables in each hashed area.
// TODO: Change this to a set?
const weightedSet: any = {};
const newWeightedSet: Set<string> = new Set<string>();
for (const table of tables) {
const lng: number = table.geometry.coordinates[0];
const lat: number = table.geometry.coordinates[1];
// TODO: This 4 was created by trial and error. If there are more than 10,000 results returned
// then decrease the number by one (i.e. change 4 to 3)
const geohash = Geohash.encode(lat, lng, 4);
newWeightedSet.add(geohash);
if (weightedSet.hasOwnProperty(geohash)) {
weightedSet[geohash] += 1;
} else {
weightedSet[geohash] = 1;
}
}
// Decode the geohashes and return a weighted heatmap
const returnSet = new Array();
newWeightedSet.forEach((table) => {
const point = Geohash.decode(table);
const numTables = weightedSet[table];
returnSet.push([point.lat, point.lon, numTables]);
});
res.send(JSON.stringify(returnSet));
});
});
app.post("/data/tables/add", multer().single(), (req: Express.Request, res: Express.Response) => {
// Authenticate
const user = UserModule.getLoggedInUser(req);
if (!user) {
res.send("Error: No user authentication.");
return;
}
const fields = req.body;
const table = new Picnic({
geometry: {
coordinates: [Number(fields.longitude), Number(fields.latitude)],
type: "Point",
},
properties: {
comment: fields.comment,
license: {
name: fields.license_name,
url: fields.license_url,
},
source: {
name: fields.source_name,
retrieved: Date.now(),
url: fields.source_url,
},
type: "table",
user,
},
type: "Feature",
});
// Switch form text (yes/no) to boolean
switch (fields.sheltered.toLowerCase()) {
case "yes":
table.properties.sheltered = true;
break;
case "no":
table.properties.sheltered = false;
break;
}
switch (fields.accessible.toLowerCase()) {
case "yes":
table.properties.accessible = true;
break;
case "no":
table.properties.accessible = false;
break;
}
// Add picnic table to database
Picnic.create(table, (error: any) => {
if (error) {
res.send("Error: " + error);
// console.log(error);
} else {
res.redirect(req.header("Referer"));
}
});
});
app.post("/data/tables/edit", multer().single(), (req: Express.Request, res: Express.Response) => {
// Authenticate
const user = UserModule.getLoggedInUser(req);
if (!user) {
res.send("Error: No user authentication.");
return;
}
// TODO: Authenticate the permission on the actual table.
User.findOne({ email: user }, async (userFindError) => {
if (userFindError) {
res.send("Error: There was an error checking permissions.");
}
const fields = req.body;
const table = await Picnic.findOne({ id: fields.id }).exec();
table.properties.comment = fields.comment;
table.properties.license.url = fields.license_url;
table.properties.license.name = fields.license_name;
// Switch form text (yes/no) to boolean
switch (fields.sheltered.toLowerCase()) {
case "yes":
table.properties.sheltered = true;
break;
case "no":
table.properties.sheltered = false;
break;
}
switch (fields.accessible.toLowerCase()) {
case "yes":
table.properties.accessible = true;
break;
case "no":
table.properties.accessible = false;
break;
}
table.save((err) => {
if (err) {
res.send("Error: Failed saving updated table.");
} else {
res.redirect(req.header("Referer"));
}
});
});
});
}
}
| earthiverse/picknic | source/modules/data/DataModule.ts | TypeScript | mit | 6,060 |
<!-- Modal ADD -->
<div class="modal fade" id="modal-form" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><small></small></h4>
</div>
<div class="modal-body">
<?php echo form_open('', 'id="form" class="form-horizontal"'); ?> <!-- form login -->
<div style="width: auto" align="center">
<h3>RSIA. LOMBOK DUA DUA</h3>
<h5>RINCIAN BIAYA</h5>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-3 control-label">Nama Pasien</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="nama_pasien" placeholder="Nama pasien" required>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-4 control-label">Kode Transaksi</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="kode_transaksi" value="<?= date('ymdhis') ?>" disabled="">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-3 control-label">Nama Suami</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="nama_suami" placeholder="Nama suami" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-3 control-label">Alamat</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="alamat" placeholder="Alamat" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-3 control-label">No Telp</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="telp" placeholder="No Telp" required>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-3 control-label">Tgl Masuk</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="tgl_masuk" value="<?= date('Y/m/d') ?>" disabled="">
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="col-sm-4 control-label">Tgl Keluar</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="tgl_keluar" data-inputmask="'alias': 'yyyy/mm/dd'" data-mask required placeholder="Tanggal Keluar">
</div>
</div>
</div>
</div>
<hr>
<div class="form-group">
<label class="col-sm-2 control-label">Dokter Utama</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="dokter_utama" placeholder="Dokter utama" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Perincian Biaya</label>
<div class="col-sm-8">
<input type="text" class="form-control" name="title" placeholder="Keterangan" required>
</div>
</div>
<hr>
<div style="margin: 40px">
<table class="table">
<tr>
<td><b><i>Keterangan</b></i></td>
<td width="20%"><b><i>Jumlah</b></i></td>
</tr>
<tr>
<td>Kartu Pasien</td>
<td><input type="number" class="form-control" name="kartu_pasien" placeholder="" required></td>
</tr>
<tr>
<td>Administrasi</td>
<td><input type="number" class="form-control" name="administrasi" placeholder="" required></td>
</tr>
<tr>
<td>Komponen OK Alat Anastesi</td>
<td><input type="number" class="form-control" name="komponen_ok" placeholder="" required></td>
</tr>
</table>
<hr><strong>Pemakaian Kamar</strong>
<table class="table">
<td>Jasa Pelayanan</td>
<td style="width: 20%"><input type="number" class="form-control" name="jasa_pelayanan" placeholder="" ></td>
</tr>
<tr>
<td>Kamar Inap</td>
<td><input type="number" class="form-control" name="kamar_inap" placeholder="" ></td>
</tr>
<tr>
<td>Kamar Operasi</td>
<td><input type="number" class="form-control" name="kamar_operasi" placeholder="" ></td>
</tr>
<tr>
<td>Kamar Bersalin</td>
<td><input type="number" class="form-control" name="kamar_bersali" placeholder="" ></td>
</tr>
</table>
<hr><strong>Penunjang Medis</strong>
<table class="table">
<td>Laboratorium</td>
<td style="width: 20%"><input type="number" class="form-control" name="laboratorium" placeholder="" ></td>
</tr>
</table>
<hr><strong>Pemakaian Obat dan Alkes</strong>
<table class="table">
<td>Luar Paket (Obat Dengan Resep)</td>
<td style="width: 20%"><input type="number" class="form-control" name="luar_paket" placeholder="" ></td>
</tr>
<tr>
<td>di Kamar Rawat Inap</td>
<td><input type="number" class="form-control" name="di_kamar_rawat_inap" placeholder="" ></td>
</tr>
<tr>
<td>di Kamar Operasi</td>
<td><input type="number" class="form-control" name="di_kamar_operasi" placeholder="" ></td>
</tr>
<tr>
<td>di Kamar Bersalin</td>
<td><input type="number" class="form-control" name="di_kamar_bersali" placeholder="" ></td>
</tr>
</table>
<hr><strong>Rincian Biaya Tindakan</strong>
<table class="table">
<td>NST</td>
<td style="width: 20%"><input type="number" class="form-control" name="nst" placeholder="" ></td>
</tr>
</table>
<hr><strong>Tindakan dan HR Dokter</strong>
<hr><strong>Lain - Lain</strong>
<table class="table">
<td>Lain - Lain</td>
<td style="width: 20%"><input type="number" class="form-control" name="lain_lain" placeholder="" ></td>
</tr>
</table>
</div>
<div class="box-footer">
<div class="pull-right">
<button type="reset" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success">Simpan</button>
</div>
</div><!-- /.box-footer -->
<?php echo form_close(); ?> <!-- form close -->
</div><!-- /.form-box -->
</div><!-- /.register-box -->
</div>
</div> | nizamiftahul/ci_p1 | application/views/rawat_jalan/_edit.php | PHP | mit | 7,969 |
#Attribute set in both superclass and subclass
class C(object):
def __init__(self):
self.var = 0
class D(C):
def __init__(self):
self.var = 1 # self.var will be overwritten
C.__init__(self)
#Attribute set in both superclass and subclass
class E(object):
def __init__(self):
self.var = 0 # self.var will be overwritten
class F(E):
def __init__(self):
E.__init__(self)
self.var = 1
| github/codeql | python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py | Python | mit | 451 |
#include <iostream>
#include <fftw3.h>
#include <omp.h>
#include <cstdlib>
#include <sweet/SimulationVariables.hpp>
class TestFFTPlans
{
public:
bool importWisdom(int i_reuse_spectral_transformation_plans)
{
static const char *wisdom_file = "sweet_fftw";
std::cout << "fftw_import_wisdom_from_filename(" << wisdom_file << ")" << std::endl;
int wisdom_plan_loaded = fftw_import_wisdom_from_filename(wisdom_file);
if (wisdom_plan_loaded == 0)
{
std::cerr << "Failed to load FFTW wisdom from file '" << wisdom_file << "'" << std::endl;
if (i_reuse_spectral_transformation_plans == 2)
exit(1);
}
std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl;
return true;
}
bool exportWisdom()
{
static const char *wisdom_file = "sweet_fftw";
std::cout << "fftw_export_wisdom_to_filename(" << wisdom_file << ")" << std::endl;
int wisdom_plan_stored = fftw_export_wisdom_to_filename(wisdom_file);
if (wisdom_plan_stored == 0)
{
std::cerr << "Failed to store FFTW wisdom to file " << wisdom_file << std::endl;
exit(1);
}
std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl;
return true;
}
bool printWisdom()
{
std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl;
return true;
}
int run(
int i_reuse_spectral_transformation_plans,
int i_res[2],
int i_nthreads
)
{
#if SWEET_THREADING
std::cout << "fftw_init_threads()" << std::endl;
int retval = fftw_init_threads();
if (retval == 0)
{
std::cerr << "ERROR: fftw_init_threads()" << std::endl;
exit(1);
}
std::cout << "fftw_plan_with_nthreads(" << i_nthreads << ")" << std::endl;
fftw_plan_with_nthreads(i_nthreads);
#endif
importWisdom(i_reuse_spectral_transformation_plans);
unsigned int num_cells = i_res[0]*i_res[1];
unsigned flags = 0;
if (i_reuse_spectral_transformation_plans == -1)
{
flags |= FFTW_ESTIMATE;
}
else
{
// estimation base don workload
if (num_cells < 32*32)
//flags |= FFTW_EXHAUSTIVE;
num_cells |= FFTW_MEASURE;
else if (num_cells < 128*128)
num_cells |= FFTW_MEASURE;
else
num_cells |= FFTW_PATIENT;
if (i_reuse_spectral_transformation_plans == 2)
{
std::cout << "Enforcing to use Wisdom" << std::endl;
flags |= FFTW_WISDOM_ONLY;
}
}
// allocate more data than necessary for spectral space
fftw_complex *data_spectral = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * i_res[0]*i_res[1]);
// physical space data
double *data_physical = (double*)fftw_malloc(sizeof(double)*2 * i_res[0]*i_res[1]);
std::cout << "fftw_plan_dft_r2c_2d(...)" << std::endl;
fftw_plan fftw_plan_forward;
fftw_plan_forward =
fftw_plan_dft_r2c_2d(
i_res[1],
i_res[0],
data_physical,
(fftw_complex*)data_spectral,
flags
);
printWisdom();
if (fftw_plan_forward == nullptr)
{
std::cout << "Wisdom: " << fftw_export_wisdom_to_string() << std::endl;
std::cerr << "Failed to get forward plan dft_r2c fftw" << std::endl;
exit(-1);
}
exportWisdom();
#if SWEET_THREADING
fftw_cleanup_threads();
#endif
fftw_cleanup();
return 0;
}
};
int main(int i_argc, char **i_argv)
{
SimulationVariables simVars;
simVars.setupFromMainParameters(i_argc, i_argv, nullptr, true);
simVars.outputConfig();
#if SWEET_THREADING
int nthreads = omp_get_max_threads();
std::cout << " + nthreads: " << nthreads << std::endl;
#else
int nthreads = 0;
#endif
TestFFTPlans t;
t.run(simVars.misc.reuse_spectral_transformation_plans, simVars.disc.space_res_physical, nthreads);
std::cout << "FIN" << std::endl;
return 0;
}
| schreiberx/sweet | src/unit_tests/test_plane_fftw_wisdom_import_export.cpp | C++ | mit | 3,655 |
class Comment < Sequel::Model
many_to_one :post
include Splam
splammable :body do |splam|
splam.threshold = 40
splam.rules = [:bad_words, :html, :bbcode, :href, :chinese, :line_length, :russian]
end
def before_save
return false if super == false
self.published = !self.splam?
true
end
end | whoisjake/thoughts | models/comment.rb | Ruby | mit | 329 |
namespace EVTC_Log_Parser.Model
{
public class Interval
{
public int Start { get; set; }
public int End { get; set; }
}
}
| M4xZ3r0/GW2RaidTool | GW2RaidTool/EVTC-Log-Parser/Model/Data/Skill/Interval.cs | C# | mit | 153 |
package br.com.dbsoft.rest.dados;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import br.com.dbsoft.rest.interfaces.IStatus;
@JsonInclude(value=Include.NON_NULL)
@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
public class DadosStatus implements IStatus {
private static final long serialVersionUID = -6552296817145232368L;
@JsonProperty("status")
private Boolean wStatus;
@Override
public Boolean getStatus() {
return wStatus;
}
@Override
public void setStatus(Boolean pStatus) {
wStatus = pStatus;
}
}
| dbsoftcombr/dbssdk | src/main/java/br/com/dbsoft/rest/dados/DadosStatus.java | Java | mit | 1,014 |
import PropTypes from 'prop-types'
import React from 'react'
import block from 'bem-cn-lite'
import { Field, reduxForm } from 'redux-form'
import { compose } from 'underscore'
import { connect } from 'react-redux'
import { renderTextInput } from '../text_input'
import { renderCheckboxInput } from '../checkbox_input'
import { signUp, updateAuthFormStateAndClearError } from '../../client/actions'
import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox'
function validate(values) {
const { accepted_terms_of_service, email, name, password } = values
const errors = {}
if (!name) errors.name = 'Required'
if (!email) errors.email = 'Required'
if (!password) errors.password = 'Required'
if (!accepted_terms_of_service)
errors.accepted_terms_of_service = 'Please agree to our terms to continue'
return errors
}
function SignUp(props) {
const {
error,
handleSubmit,
isLoading,
signUpAction,
updateAuthFormStateAndClearErrorAction,
} = props
const b = block('consignments-submission-sign-up')
return (
<div className={b()}>
<div className={b('title')}>Create an Account</div>
<div className={b('subtitle')}>
Already have an account?{' '}
<span
className={b('clickable')}
onClick={() => updateAuthFormStateAndClearErrorAction('logIn')}
>
Log in
</span>.
</div>
<form className={b('form')} onSubmit={handleSubmit(signUpAction)}>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="name"
component={renderTextInput}
item={'name'}
label={'Full Name'}
autofocus
/>
</div>
</div>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="email"
component={renderTextInput}
item={'email'}
label={'Email'}
type={'email'}
/>
</div>
</div>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="password"
component={renderTextInput}
item={'password'}
label={'Password'}
type={'password'}
/>
</div>
</div>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="accepted_terms_of_service"
component={renderCheckboxInput}
item={'accepted_terms_of_service'}
label={<GDPRMessage />}
value={false}
/>
</div>
</div>
<button
className={b
.builder()('sign-up-button')
.mix('avant-garde-button-black')()}
type="submit"
>
{isLoading ? <div className="loading-spinner-white" /> : 'Submit'}
</button>
{error && <div className={b('error')}>{error}</div>}
</form>
</div>
)
}
const mapStateToProps = state => {
return {
error: state.submissionFlow.error,
isLoading: state.submissionFlow.isLoading,
}
}
const mapDispatchToProps = {
signUpAction: signUp,
updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError,
}
SignUp.propTypes = {
error: PropTypes.string,
handleSubmit: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
signUpAction: PropTypes.func.isRequired,
updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired,
}
export default compose(
reduxForm({
form: 'signUp', // a unique identifier for this form
validate,
}),
connect(mapStateToProps, mapDispatchToProps)
)(SignUp)
| kanaabe/force | src/desktop/apps/consign/components/sign_up/index.js | JavaScript | mit | 3,781 |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System.Collections.Generic;
using DotSpatial.Data;
namespace DotSpatial.Symbology
{
/// <summary>
/// Interface for LayerProvider.
/// </summary>
public interface ILayerProvider
{
#region Properties
/// <summary>
/// Gets a basic description of what your provider does.
/// </summary>
string Description { get; }
/// <summary>
/// Gets a dialog read filter that lists each of the file type descriptions and file extensions, delimeted
/// by the | symbol. Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided
/// on this object.
/// </summary>
string DialogReadFilter { get; }
/// <summary>
/// Gets a dialog filter that lists each of the file type descriptions and extensions for a Save File Dialog.
/// Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided on this object.
/// </summary>
string DialogWriteFilter { get; }
/// <summary>
/// Gets a prefereably short name that identifies this data provider. Example might be GDAL.
/// This will be prepended to each of the DialogReadFilter members from this plugin.
/// </summary>
string Name { get; }
#endregion
#region Methods
/// <summary>
/// This open method is only called if this plugin has been given priority for one
/// of the file extensions supported in the DialogReadFilter property supplied by
/// this control. Failing to provide a DialogReadFilter will result in this plugin
/// being added to the list of DataProviders being supplied under the Add Other Data
/// option in the file menu.
/// </summary>
/// <param name="fileName">A string specifying the complete path and extension of the file to open.</param>
/// <param name="inRam">A boolean that, if ture, will request that the data be loaded into memory</param>
/// <param name="container">Any valid IContainer that should have the new layer automatically added to it</param>
/// <param name="progressHandler">An IProgressHandler interface for status messages</param>
/// <returns>A List of IDataSets to be added to the Map. These can also be groups of datasets.</returns>
ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler);
#endregion
}
} | CGX-GROUP/DotSpatial | Source/DotSpatial.Symbology/ILayerProvider.cs | C# | mit | 2,747 |
using System.Runtime.Serialization;
namespace PushbulletSharp.Models.Responses.Ephemerals
{
[DataContract]
public class DismissalEphemeral : IEphemeral
{
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>
/// The type.
/// </value>
[DataMember(Name = "type")]
public string Type { get; set; }
/// <summary>
/// Gets or sets the name of the package.
/// </summary>
/// <value>
/// The name of the package.
/// </value>
[DataMember(Name = "package_name")]
public string PackageName { get; set; }
/// <summary>
/// Gets or sets the source user iden.
/// </summary>
/// <value>
/// The source user iden.
/// </value>
[DataMember(Name = "source_user_iden")]
public string SourceUserIden { get; set; }
/// <summary>
/// Gets or sets the notification identifier.
/// </summary>
/// <value>
/// The notification identifier.
/// </value>
[DataMember(Name = "notification_id")]
public string NotificationId { get; set; }
/// <summary>
/// Gets or sets the notification tag.
/// </summary>
/// <value>
/// The notification tag.
/// </value>
[DataMember(Name = "notification_tag")]
public string NotificationTag { get; set; }
/// <summary>
/// Gets or sets the source device iden.
/// </summary>
/// <value>
/// The source device iden.
/// </value>
[DataMember(Name = "source_device_iden")]
public string SourceDeviceIden { get; set; }
}
} | adamyeager/PushbulletSharp | PushbulletSharp/Models/Responses/Ephemerals/DismissalEphemeral.cs | C# | mit | 1,753 |
package com.landenlabs.all_flipanimation;
/**
* Copyright (c) 2015 Dennis Lang (LanDen Labs) landenlabs@gmail.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @author Dennis Lang (3/21/2015)
* @see http://landenlabs.com
*
*/
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import android.widget.CheckBox;
import android.widget.TextView;
/**
* Demonstrate rotating View animation using two rotating animations.
*
* @author Dennis Lang (LanDen Labs)
* @see <a href="http://landenlabs.com/android/index-m.html"> author's web-site </a>
* // http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html
*/
public class ActivityRotAnimation extends Activity {
// ---- Layout ----
View mView1;
View mView2;
View mClickView;
DrawView mDrawView;
TextView mAngle1;
TextView mAngle2;
// ---- Data ----
float mCameraZ = -25;
Flip3dAnimation mRotation1;
Flip3dAnimation mRotation2;
boolean mRotateYaxis = true;
boolean mIsForward = true;
boolean mAutoMode = false;
MediaPlayer mSoundClick;
MediaPlayer mSoundShut;
// ---- Timer ----
private Handler m_handler = new Handler();
private int mDurationMsec = 3000;
private Runnable m_updateElapsedTimeTask = new Runnable() {
public void run() {
animateIt();
m_handler.postDelayed(this, mDurationMsec); // Re-execute after msec
}
};
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rot_animation);
mView1 = Ui.viewById(this, R.id.view1);
mView2 = Ui.viewById(this, R.id.view2);
// Create a new 3D rotation with the supplied parameter
mRotation1 = new Flip3dAnimation();
mRotation2 = new Flip3dAnimation();
Ui.<TextView>viewById(this, R.id.side_title).setText("Rotating Animation");
setupUI();
}
/**
* Start animation.
*/
public void animateIt() {
ObjectAnimator.ofFloat(mClickView, View.ALPHA, mClickView.getAlpha(), 0).start();
final float end = 90.0f;
if (mIsForward) {
mRotation1.mFromDegrees = 0.0f;
mRotation1.mToDegrees = end;
mRotation2.mFromDegrees = -end;
mRotation2.mToDegrees = 0.0f;
} else {
mRotation1.mFromDegrees = end;
mRotation1.mToDegrees = 0.0f;
mRotation2.mFromDegrees = 0.0f;
mRotation2.mToDegrees = -end;
}
mIsForward = !mIsForward;
if (mRotateYaxis) {
mRotation1.mCenterX = mView1.getWidth();
mRotation1.mCenterY = mView1.getHeight() / 2.0f;
mRotation2.mCenterX = 0.0f;
mRotation2.mCenterY = mView2.getHeight() / 2.0f;
} else {
mRotation1.mCenterY = 0.0f; // mView1.getHeight();
mRotation1.mCenterX = mView1.getWidth() / 2.0f;
mRotation2.mCenterY = mView1.getHeight(); // 0.0f;
mRotation2.mCenterX = mView2.getWidth() / 2.0f;
}
mRotation1.reset(mView1, mDurationMsec, mCameraZ);
mRotation2.reset(mView2, mDurationMsec, mCameraZ);
mRotation2.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) { }
@Override public void onAnimationEnd(Animation animation) {
mSoundShut.start();
}
@Override public void onAnimationRepeat(Animation animation) { }
});
// Run both animations in parallel.
AnimationSet animationSet = new AnimationSet(true);
animationSet.setInterpolator(new LinearInterpolator());
animationSet.addAnimation(mRotation1);
animationSet.addAnimation(mRotation2);
animationSet.start();
}
public class Flip3dAnimation extends Animation {
float mFromDegrees;
float mToDegrees;
float mCenterX = 0;
float mCenterY = 0;
float mCameraZ = -8;
Camera mCamera;
View mView;
public Flip3dAnimation() {
setFillEnabled(true);
setFillAfter(true);
setFillBefore(true);
}
public void reset(View view, int durationMsec, float cameraZ) {
mCameraZ = cameraZ;
setDuration(durationMsec);
view.clearAnimation(); // This is very important to get 2nd..nth run to work.
view.setAnimation(this);
mView = view;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation trans) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final Camera camera = mCamera;
final Matrix matrix = trans.getMatrix();
camera.save();
camera.setLocation(0, 0, mCameraZ);
if (mRotateYaxis)
camera.rotateY(degrees);
else
camera.rotateX(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-mCenterX, -mCenterY);
matrix.postTranslate(mCenterX, mCenterY);
final float degree3 = degrees;
if (mView == mView1) {
mDrawView.setAngle1(degree3);
mAngle1.setText(String.format("%.0f°", degree3));
} else {
mDrawView.setAngle2(degree3);
mAngle2.setText(String.format("%.0f°", degree3));
}
}
}
/**
* Build User Interface - setup callbacks.
*/
private void setupUI() {
mSoundClick = MediaPlayer.create(this, R.raw.click);
// mSoundClick.setVolume(0.5f, 0.5f);
mSoundShut = MediaPlayer.create(this, R.raw.shut);
// mSoundShut.setVolume(0.3f, 0.3f);
final TextView title = (TextView) this.findViewById(R.id.title);
mClickView = this.findViewById(R.id.click_view);
mClickView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mSoundClick.start();
animateIt();
}
});
final SlideBar seekspeedSB = new SlideBar(this.findViewById(R.id.seekSpeed), "Delay:");
seekspeedSB.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mDurationMsec = (int) (value = 100 + value * 100);
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final SlideBar cameraZpos = new SlideBar(this.findViewById(R.id.cameraZpos), "CamZ:");
cameraZpos.setProgress((int) (mCameraZ / -2 + 50));
cameraZpos.setValueChanged(new SlideBar.ValueChanged() {
@Override
public float onValueChanged(View v, float value) {
mCameraZ = value = (50 - value) * 2.0f;
title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ));
return value;
}
});
final CheckBox autoFlipCb = Ui.viewById(this, R.id.autoflip);
autoFlipCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAutoMode = ((CheckBox) v).isChecked();
if (mAutoMode) {
m_handler.postDelayed(m_updateElapsedTimeTask, 0);
} else {
m_handler.removeCallbacks(m_updateElapsedTimeTask);
}
}
});
final CheckBox yaxisCb = Ui.viewById(this, R.id.yaxis);
mRotateYaxis = yaxisCb.isChecked();
yaxisCb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean autoMode = mAutoMode;
if (autoMode)
autoFlipCb.performClick(); // Stop automatic animation.
mRotateYaxis = ((CheckBox) v).isChecked();
if (autoMode)
autoFlipCb.performClick(); // Restart automatic animation.
}
});
mDrawView = Ui.viewById(this, R.id.drawView);
mAngle1 = Ui.viewById(this, R.id.angle1);
mAngle2 = Ui.viewById(this, R.id.angle2);
}
} | landenlabs2/all_FlipAnimation | app/src/main/java/com/landenlabs/all_flipanimation/ActivityRotAnimation.java | Java | mit | 10,273 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DesktopCharacter.Model.Locator;
using DesktopCharacter.ViewModel.SettingTab;
namespace DesktopCharacter.ViewModel
{
class SettingViewModel : Livet.ViewModel
{
public LauncherSettingViewModel LauncherSetting { set; private get; }
public CharacterSettingViewModel CharacterSetting { set; private get; }
public TwitterSettingViewModel TwitterSetting { set; private get; }
public CodicSettingTabViewModel CodicSettingTab { set; private get; }
public SlackSettingViewModel SlackSetting { set; private get; }
public SettingViewModel()
{
}
public void ClosedEvent()
{
TwitterSetting.OnClose();
CodicSettingTab.OnClose();
CharacterSetting.OnClose();
SlackSetting.OnClose();
LauncherSetting.OnClose();
ServiceLocator.Instance.ClearConfigBaseContext();
}
}
}
| Babumi/DesktopCharacter | DesktopCharacter/ViewModel/SettingViewModel.cs | C# | mit | 1,063 |
TF.listen();
| rivers/tabfusion | src/listener.js | JavaScript | mit | 13 |
<?php
/**
* Close.io Api Wrapper - LLS Internet GmbH - Loopline Systems.
*
* @see https://github.com/loopline-systems/closeio-api-wrapper for the canonical source repository
*
* @copyright Copyright (c) 2014 LLS Internet GmbH - Loopline Systems (http://www.loopline-systems.com)
* @license https://github.com/loopline-systems/closeio-api-wrapper/blob/master/LICENSE (MIT Licence)
*/
declare(strict_types=1);
namespace LooplineSystems\CloseIoApiWrapper\Model;
use LooplineSystems\CloseIoApiWrapper\Library\Exception\InvalidParamException;
use LooplineSystems\CloseIoApiWrapper\Library\Exception\InvalidUrlException;
use LooplineSystems\CloseIoApiWrapper\Library\JsonSerializableHelperTrait;
use LooplineSystems\CloseIoApiWrapper\Library\ObjectHydrateHelperTrait;
class Lead implements \JsonSerializable
{
const LEAD_STATUS_POTENTIAL = 'Potential';
const LEAD_STATUS_BAD_FIT = 'Bad Fit';
const LEAD_STATUS_QUALIFIED = 'Qualified';
const LEAD_STATUS_CUSTOMER = 'Customer';
use ObjectHydrateHelperTrait;
use JsonSerializableHelperTrait;
/**
* @var string
*/
private $id;
/*
* @var string
*/
private $status_id;
/**
* @var string
*/
private $status;
/*
* @var string
*/
private $status_label;
/**
* @var string
*/
private $description;
/**
* @var string
*/
private $display_name;
/**
* @var Address[]
*/
private $addresses;
/**
* @var string
*/
private $organization;
/**
* @var string
*/
private $created_by;
/**
* @var string
*/
private $url;
/**
* @var Task[]
*/
private $tasks;
/**
* @var string
*/
private $name;
/**
* @var Contact[]
*/
private $contacts;
/**
* @var string
*/
private $date_created;
/**
* @var array
*/
private $custom;
/**
* @var string
*/
private $updated_by_name;
/**
* @var string
*/
private $created_by_name;
/**
* @var Opportunity[]
*/
private $opportunities;
/**
* @var string
*/
private $html_url;
/**
* @var string
*/
private $updated_by;
/**
* @var string
*/
private $date_updated;
/**
* @var string
*/
private $organization_id;
/**
* @param array $data
*
* @throws InvalidParamException
*/
public function __construct(array $data = null)
{
if ($data) {
// custom is not a class and should be set separately
if (isset($data['custom'])) {
$this->setCustom($data['custom']);
unset($data['custom']);
}
// child objects
$nestedObjects = ['contacts', 'tasks', 'addresses', 'opportunities', 'custom'];
$this->hydrate($data, $nestedObjects);
}
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param string $id
*
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return Address[]
*/
public function getAddresses()
{
return $this->addresses;
}
/**
* @param Address $address
*
* @return $this
*/
public function addAddress(Address $address)
{
$this->addresses[] = $address;
return $this;
}
/**
* @param Address[] $addresses
*
* @return $this
*/
public function setAddresses(array $addresses)
{
$this->addresses = $addresses;
return $this;
}
/**
* @return Contact[]
*/
public function getContacts()
{
return $this->contacts;
}
/**
* @param Contact $contact
*
* @return $this
*/
public function addContact(Contact $contact)
{
$this->contacts[] = $contact;
return $this;
}
/**
* @param Contact[] $contacts
*
* @return $this
*/
public function setContacts(array $contacts)
{
$this->contacts = $contacts;
return $this;
}
/**
* @return string
*/
public function getCreatedBy()
{
return $this->created_by;
}
/**
* @param string $created_by
*
* @return $this
*/
public function setCreatedBy($created_by)
{
$this->created_by = $created_by;
return $this;
}
/**
* @return array
*/
public function getCustom()
{
return $this->custom;
}
/**
* @param array $custom
*
* @return $this
*/
public function setCustom($custom)
{
$this->custom = $custom;
return $this;
}
/**
* Sets the value of a custom field. By passing a `null` value the field
* will be unset from the lead.
*
* @param string $name The name or ID of the field
* @param mixed $value The value
*
* @return $this
*/
public function setCustomField(string $name, $value)
{
$this->custom[$name] = $value;
return $this;
}
/**
* @return string
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* @param string $date_created
*
* @return $this
*/
public function setDateCreated($date_created)
{
$this->date_created = $date_created;
return $this;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string $description
*
* @return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* @return string
*/
public function getDisplayName()
{
return $this->display_name;
}
/**
* @param string $display_name
*
* @return $this
*/
public function setDisplayName($display_name)
{
$this->display_name = $display_name;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return Opportunity[]
*/
public function getOpportunities()
{
return $this->opportunities;
}
/**
* @param Opportunity[] $opportunities
*
* @return $this
*/
public function setOpportunities(array $opportunities)
{
$this->opportunities = $opportunities;
return $this;
}
/**
* @return string
*/
public function getOrganization()
{
return $this->organization;
}
/**
* @param string $organization
*
* @return $this
*/
public function setOrganization($organization)
{
$this->organization = $organization;
return $this;
}
/**
* @return string
*/
public function getStatusId()
{
return $this->status_id;
}
/**
* @param string $status
*
* @return $this
*/
public function setStatusId($status)
{
$this->status_id = $status;
return $this;
}
/**
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* @param string $status
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* @return string
*/
public function getStatusLabel()
{
return $this->status_label;
}
/**
* @param string $status_label
*
* @return $this
*/
public function setStatusLabel($status_label)
{
$this->status_label = $status_label;
return $this;
}
/**
* @return Task[]
*/
public function getTasks()
{
return $this->tasks;
}
/**
* @param Task[] $tasks
*
* @return $this
*/
public function setTasks($tasks)
{
$this->tasks = $tasks;
return $this;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
*
* @return $this
*
* @throws InvalidUrlException
*/
public function setUrl($url)
{
// validate url
if (filter_var($url, FILTER_VALIDATE_URL)) {
$this->url = $url;
} else {
throw new InvalidUrlException('"' . $url . '" is not a valid URL');
}
return $this;
}
/**
* @return string
*/
public function getCreatedByName()
{
return $this->created_by_name;
}
/**
* @param string $created_by_name
*
* @return $this
*/
public function setCreatedByName($created_by_name)
{
$this->created_by_name = $created_by_name;
return $this;
}
/**
* @return string
*/
public function getDateUpdated()
{
return $this->date_updated;
}
/**
* @param string $date_updated
*
* @return $this
*/
public function setDateUpdated($date_updated)
{
$this->date_updated = $date_updated;
return $this;
}
/**
* @return string
*/
public function getHtmlUrl()
{
return $this->html_url;
}
/**
* @param string $html_url
*
* @return $this
*/
public function setHtmlUrl($html_url)
{
$this->html_url = $html_url;
return $this;
}
/**
* @return string
*/
public function getOrganizationId()
{
return $this->organization_id;
}
/**
* @param string $organization_id
*
* @return $this
*/
public function setOrganizationId($organization_id)
{
$this->organization_id = $organization_id;
return $this;
}
/**
* @return string
*/
public function getUpdatedBy()
{
return $this->updated_by;
}
/**
* @param string $updated_by
*
* @return $this
*/
public function setUpdatedBy($updated_by)
{
$this->updated_by = $updated_by;
return $this;
}
/**
* @return string
*/
public function getUpdatedByName()
{
return $this->updated_by_name;
}
/**
* @param string $updated_by_name
*
* @return $this
*/
public function setUpdatedByName($updated_by_name)
{
$this->updated_by_name = $updated_by_name;
return $this;
}
public function __set(string $name, $value)
{
if (strpos($name, 'custom.') === 0) {
@trigger_error('Setting a custom field using the $object->$fieldName syntax is deprecated since version 0.8. Use the setCustomField() method instead.', E_USER_DEPRECATED);
$this->custom[substr($name, 7)] = $value;
} else {
$this->$name = $value;
}
}
}
| loopline-systems/closeio-api-wrapper | src/Model/Lead.php | PHP | mit | 11,400 |
package com.example.apahlavan1.top10downloader;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | AriaPahlavan/Android-Apps | Top10Downloader/app/src/androidTest/java/com/example/apahlavan1/top10downloader/ApplicationTest.java | Java | mit | 369 |
import pymongo
def connect ():
'''
Create the connection to the MongoDB and create 3 collections needed
'''
try:
# Create the connection to the local host
conn = pymongo.MongoClient()
print 'MongoDB Connection Successful'
except pymongo.errors.ConnectionFailure, err:
print 'MongoDB Connection Unsuccessful'
return False
# This is the name of the database -'GtownTwitter'
db = conn['GtownTwitter_PROD']
return db | Macemann/Georgetown-Capstone | app/db/connect.py | Python | mit | 493 |
require 'compiler_helper'
module Alf
class Compiler
describe Default, "join" do
subject{
compiler.call(expr)
}
let(:right){
compact(an_operand)
}
let(:expr){
join(an_operand(leaf), right)
}
it_should_behave_like "a traceable compiled"
it 'is a Join::Hash cog' do
subject.should be_a(Engine::Join::Hash)
end
it 'has the correct left sub-cog' do
subject.left.should be(leaf)
end
it 'has the correct right sub-cog' do
subject.right.should be_a(Engine::Compact)
end
end
end
end
| alf-tool/alf-core | spec/unit/alf-compiler/default/test_join.rb | Ruby | mit | 620 |
<?php
// This file assumes that you have included the nav walker from https://github.com/twittem/wp-bootstrap-navwalker
// somewhere in your theme.
?>
<?php if (!get_theme_mod('hide-header')) { ?>
<header class="container-fluid">
<div class="row">
<div class="banner navbar navbar-default navbar-static-top affix" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only"><?= __('Toggle navigation', 'sage'); ?></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="<?= esc_url(home_url('/')); ?>">
<?php
/**
* Display logo from Appearance > Customize or blog name if logo not set
*/
has_custom_logo() ? Roots\Sage\Extras\sage_the_custom_logo() : bloginfo('name'); ?>
</a>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu([
'theme_location' => 'primary_navigation'
, 'walker' => new wp_bootstrap_navwalker()
, 'menu_class' => 'nav navbar-nav pull-right'
]);
endif;
?>
</nav>
</div><!-- /.container -->
</div><!-- /.navbar -->
</div><!-- /.row -->
<?php
/**
* Pull in header content defined by ACF plugin
*/
if (class_exists('acf')) {
get_template_part('templates/components/header-content');
}
?>
</header><!-- /.container-fluid -->
<?php } ?>
| allurewebsolutions/sage-starter | templates/header.php | PHP | mit | 1,868 |
require_relative "../lib/stressfactor"
require "pry"
file = GPX::GPXFile.new(:gpx_file => "examples/data/sample.gpx")
pc = Stressfactor::PaceCalculator.new(file)
pace = pc.calculate
puts pace
binding.pry
| andrewhao/stressfactor | scripts/analyze_sample_gpx.rb | Ruby | mit | 204 |
$(document).ready(function() {
$(document).on('submit', '.status-button', function(e) {
e.preventDefault();
var joinButton = e.target
$.ajax(joinButton.action, {
method: 'PATCH',
data: $(this).serialize()
})
.done(function(data) {
gameDiv = $(joinButton).parent();
gameDiv.replaceWith(data);
})
.fail(function() {
alert("Failure!");
});
});
});
| nyc-dragonflies-2015/whos_got_next | app/assets/javascripts/players.js | JavaScript | mit | 412 |
require_relative 'spec_helper.rb'
feature "can deal cards" do
before do
create_and_join_room("jnmandal", "bsheridan12")
end
scenario "allows you to choose amount of cards dealt" do
in_browser(:one) do
expect(page).to have_field "initial-deal-count"
end
end
scenario "deal cards button deals cards" do
in_browser(:one) do
deal_cards(4)
within "div.player-hand" do
expect(page).to have_selector ".card"
end
end
end
scenario "dealt cards viewable by other user" do
in_browser(:one) do
deal_cards(4)
end
in_browser(:two) do
within "div.player-hand" do
expect(page).to have_selector ".card"
end
end
end
scenario "does not deal cards when user enters 0" do
in_browser(:one) do
deal_cards(0)
end
in_browser(:two) do
within "div.player-hand" do
page.assert_no_selector(".card")
end
end
end
scenario "deals correct number of cards" do
in_browser(:one) do
deal_cards(5)
within "div.player-hand" do
page.assert_selector(".card", count: 5)
end
end
end
end | KYoon/Stacks-on-Deck | spec/capybara/deal_cards_spec.rb | Ruby | mit | 1,146 |
function OrganizationController() {
// injetando dependência
'ngInject';
// ViewModel
const vm = this;
console.log('OrganizationController');
}
export default {
name: 'OrganizationController',
fn: OrganizationController
};
| dnaloco/digitala | app/erp/js/controllers/human-resource/organiz.js | JavaScript | mit | 242 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2016, Jianfeng Chen <jchen37@ncsu.edu>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import division
def dist(a, b):
return sum((i-j)**2 for i, j in zip(a, b))
def GD(PF0, PFc):
up = 0
for i in PFc:
up += min([dist(i, j) for j in PF0])
return up**0.5 / (len(PFc))
| Ginfung/FSSE | Metrics/gd.py | Python | mit | 1,445 |
import React, { Component } from 'react';
import Header from './Header';
import MainSection from './MainSection';
export default class App extends Component {
render() {
return (
<div>
<Header/>
<MainSection/>
</div>
);
}
}
| loggur/react-redux-provide | examples/todomvc/components/App.js | JavaScript | mit | 265 |
#!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib.request
import sys
ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})"
def iso8601_to_unix_timestamp(value):
try:
return int(value)
except ValueError:
pass
matches = re.match(ISO8601, value)
if not matches:
raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 "
"timestamp.")
return int(datetime.datetime(
*[int(m) for m in matches.groups()])).timestamp()
def hex_value(value):
value = value.replace("#", "")
if not re.match(r"^[a-f0-9]{6}$", value):
raise ArgumentTypeError("Argument is not a valid hex value.")
return value
parser = ArgumentParser(description="Send notifications using Slack")
parser.add_argument("--webhook-url", help="Webhook URL.", required=True)
parser.add_argument("--channel", help="Channel to post to (prefixed with #), "
"or a specific user (prefixed with @).")
parser.add_argument("--username", help="Username to post as")
parser.add_argument("--title", help="Notification title.")
parser.add_argument("--title_link", help="Notification title link.")
parser.add_argument("--color", help="Sidebar color (as a hex value).",
type=hex_value)
parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp "
"(will be converted to Unix timestamp).",
type=iso8601_to_unix_timestamp)
parser.add_argument("message", help="Notification message.")
args = parser.parse_args()
message = {}
for param in ["channel", "username"]:
value = getattr(args, param)
if value:
message[param] = value
attachment = {}
for param in ["title", "title_link", "color", "ts", "message"]:
value = getattr(args, param)
if value:
attachment[param] = value
attachment['fallback'] = attachment['message']
attachment['text'] = attachment['message']
del attachment['message']
message['attachments'] = [attachment]
payload = {"payload": json.dumps(message)}
try:
parameters = urllib.parse.urlencode(payload).encode('UTF-8')
url = urllib.request.Request(args.webhook_url, parameters)
responseData = urllib.request.urlopen(url).read()
except urllib.error.HTTPError as he:
print("Sending message to Slack failed: {}".format(he))
sys.exit(1)
| LordGaav/notification-scripts | slack.py | Python | mit | 3,578 |
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class MultilayerGeneratorServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
/*
|
|---------------------------------------------------------------------------------
| Please do not uncomment the commented lines, do not delete them, nor edit them.
| any action will result in serious damage to the package functionality.
|--------------------------------------------------------------------------------
|
*/
$this->app->booting(function(){
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
/*
|
| Interfaces
|
*/
//DummyAliasLoadingForInterfaces
/*
|
| Repositories Classes
|
*/
//DummyAliasLoadingForRepositories
/*
|
| Object Classes
|
*/
//DummyAliasLoadingForObjects
/*
|
| Traits
|
*/
$loader->alias('CRUDtrait', 'App\Http\Traits\CRUDtrait');
//DummyAliasLoadingForTraits
/*
|
| Motors
|
*/
$loader->alias('Motor', 'App\Http\Motors\Motor');
//DummyAliasLoadingForMotors
});
}
}
| HOuaghad/multilayering | src/providers/MultilayerGeneratorServiceProvider.php | PHP | mit | 1,662 |
class BlogPost < ActiveRecord::Base
end | heedspin/transactional-factories | test/lib/blog_post.rb | Ruby | mit | 39 |
#region License
// The MIT License (MIT)
//
// Copyright (c) 2016 João Simões
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
namespace EULex.SimpleSOAPClient.Helpers
{
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;
/// <summary>
/// Helper class with extensions for XML manipulation
/// </summary>
internal static class XmlHelpers
{
private static readonly XmlSerializerNamespaces EmptyXmlSerializerNamespaces;
static XmlHelpers ()
{
EmptyXmlSerializerNamespaces = new XmlSerializerNamespaces ();
EmptyXmlSerializerNamespaces.Add ("", "");
}
/// <summary>
/// Serializes the given object to a XML string
/// </summary>
/// <typeparam name="T">The object type</typeparam>
/// <param name="item">The item to serialize</param>
/// <returns>The XML string</returns>
public static string ToXmlString<T> (this T item)
{
if (item == null) return null;
using (var textWriter = new StringWriter ()) {
new XmlSerializer (item.GetType ()).Serialize (textWriter, item, EmptyXmlSerializerNamespaces);
var result = textWriter.ToString ();
return result;
}
}
/// <summary>
/// Serializes a given object to XML and returns the <see cref="XElement"/> representation.
/// </summary>
/// <typeparam name="T">The object type</typeparam>
/// <param name="item">The item to convert</param>
/// <returns>The object as a <see cref="XElement"/></returns>
public static XElement ToXElement<T> (this T item)
{
return item == null ? null : XElement.Parse (item.ToXmlString ());
}
/// <summary>
/// Deserializes a given XML string to a new object of the expected type.
/// If null or white spaces the default(T) will be returned;
/// </summary>
/// <typeparam name="T">The type to be deserializable</typeparam>
/// <param name="xml">The XML string to deserialize</param>
/// <returns>The deserialized object</returns>
public static T ToObject<T> (this string xml)
{
if (string.IsNullOrWhiteSpace (xml)) return default (T);
using (var textWriter = new StringReader (xml)) {
var result = (T)new XmlSerializer (typeof (T)).Deserialize (textWriter);
return result;
}
}
/// <summary>
/// Deserializes a given <see cref="XElement"/> to a new object of the expected type.
/// If null the default(T) will be returned.
/// </summary>
/// <typeparam name="T">The type to be deserializable</typeparam>
/// <param name="xml">The <see cref="XElement"/> to deserialize</param>
/// <returns>The deserialized object</returns>
public static T ToObject<T> (this XElement xml)
{
return xml == null ? default (T) : xml.ToString ().ToObject<T> ();
}
}
} | EULexNET/EULex.NET | src/EULex/SimpleSOAPClient/Helpers/XmlHelpers.cs | C# | mit | 4,158 |
#region Copyright (c) 2014 Orcomp development team.
// -------------------------------------------------------------------------------------------------------------------
// <copyright file="ParseException.cs" company="Orcomp development team">
// Copyright (c) 2014 Orcomp development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#endregion
namespace SolutionValidator.FolderStructure
{
#region using...
using System;
#endregion
public class ParseException : ApplicationException
{
public ParseException(string message, int lineNumber, int column)
: base(message)
{
LineNumber = lineNumber;
Column = column;
}
public int LineNumber { get; set; }
public int Column { get; set; }
}
} | Orcomp/SolutionValidator | src/SolutionValidator.Core/Validator/FolderStructure/Exceptions/ParseException.cs | C# | mit | 834 |
package com.kkk.retrofitdemo;
import com.kkk.retrofitdemo.bean.Repo;
import com.kkk.retrofitdemo.bean.SearchRepoResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Observable;
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
@GET("search/repositories")
Observable<SearchRepoResult> searchRepos(@Query("q") String keyword,
@Query("sort") String sort,
@Query("order") String order);
} | kylm53/learn-android | RetrofitDemo/src/main/java/com/kkk/retrofitdemo/GitHubService.java | Java | mit | 655 |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class ArticleProlongImageUrl extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('image_url', 768)->change();
$table->string('url', 768)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('image_url')->change();
$table->string('url')->change();
});
}
}
| remp2020/remp | Beam/database/migrations/2018_12_07_145030_article_prolong_image_url.php | PHP | mit | 761 |
version https://git-lfs.github.com/spec/v1
oid sha256:641860132ccb9772e708b19feb3d59bb6291f6c40eebbfcfa0982a4e8eeda219
size 69639
| yogeshsaroya/new-cdnjs | ajax/libs/holder/2.5.0/holder.js | JavaScript | mit | 130 |
(function(global) {
var vwl = {};
var receivePoster;
var receiveEntry;
var receiveLoadedList;
// vwl.init - advertise VWL info and register for VWL messages
//
// Parameters:
// left - (optional) url of this world's initial left entry image
// right - (optional) url of this world's initial right entry image
// receivePosterFunc - (optional) function to handle poster images from other
// worlds
// receiveEntryFunc - (optional) function to handle entry images from other
// worlds
// recevieLoadedListFunc - (optional) function to handle list of loaded worlds
vwl.init = function(left, right,
receivePosterFunc,
receiveEntryFunc,
receiveLoadedListFunc) {
receivePoster = receivePosterFunc;
receiveEntry = receiveEntryFunc;
receiveLoadedList = receiveLoadedListFunc;
receiveEntry && window.addEventListener('message', function(message) {
if (message.source != window || message.origin != window.location.origin)
return;
if (message.data.tabInfo) {
var left = null;
var right = null;
if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) {
left = message.data.tabInfo.info.entry_image.left_src;
right = message.data.tabInfo.info.entry_image.right_src;
}
receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded,
left, right);
}
if (message.data.loadedList !== undefined) {
receiveLoadedList(message.data.loadedList);
}
}, false);
window.postMessage({info:{entry_image:{
left_src:left, right_src:right}}}, '*');
}
// vwl.getInfo - get info (entry image and poster image) on a specific world
//
// Parameters:
// url - url of worlds to get info on
// getPoster - (optional) if true get the poster image
vwl.getInfo = function(url, getPoster) {
if (receivePoster && getPoster) {
var request = new XMLHttpRequest();
var dir = url.substr(0, url.lastIndexOf('/') + 1);
request.open('GET', dir + 'vwl_info.json');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var poster = JSON.parse(request.responseText).poster_image;
receivePoster(url,
poster.left_src ? dir + poster.left_src : null,
poster.right_src ? dir + poster.right_src : null,
poster._2d_src ? dir + poster._2d_src : null);
}
else {
receivePoster(url);
}
}
request.send(null);
}
receiveEntry && window.postMessage({getInfo:url}, '*');
}
// vwl.getLoadedList - get the list of loaded worlds
vwl.getLoadedList = function() {
window.postMessage({getLoadedList:true}, '*');
}
// vwl.open - load world
//
// Parameters:
// url - url of world to open
vwl.open = function(url) {
window.postMessage({open:url}, '*');
}
// vwl.navigate - navigate to a world
//
// Parameters:
// left - (optional) new left entry image for current world
// right - (optional) new right entry image for current world
// url - url of world to navigate to
vwl.navigate = function(left, right, url) {
var message = {navigate:url};
if (left && right) {
message.info = {entry_image:{left_src:left, right_src:right}};
}
window.postMessage(message, '*');
}
global.vwl = vwl;
}) (window);
| BigRobCoder/VirtualWorldLink | lib/vwl.js | JavaScript | mit | 3,364 |
# -*- coding: utf-8 -*-
"""The initialization file for the Pywikibot framework."""
#
# (C) Pywikibot team, 2008-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__release__ = '2.0b3'
__version__ = '$Id$'
__url__ = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Pywikibot'
import datetime
import math
import re
import sys
import threading
import json
if sys.version_info[0] > 2:
from queue import Queue
long = int
else:
from Queue import Queue
from warnings import warn
# Use pywikibot. prefix for all in-package imports; this is to prevent
# confusion with similarly-named modules in version 1 framework, for users
# who want to continue using both
from pywikibot import config2 as config
from pywikibot.bot import (
output, warning, error, critical, debug, stdout, exception,
input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui, log,
calledModuleName, Bot, CurrentPageBot, WikidataBot,
# the following are flagged as deprecated on usage
handleArgs,
)
from pywikibot.exceptions import (
Error, InvalidTitle, BadTitle, NoPage, NoMoveTarget, SectionError,
SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily,
UnknownExtension,
NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
PageSaveRelatedError, PageNotSaved, OtherPageSaveError,
LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
EditConflict, PageDeletedConflict, PageCreatedConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage,
WikiBaseError, CoordinateGlobeUnknownException,
)
from pywikibot.tools import PY2, UnicodeMixin, redirect_func
from pywikibot.i18n import translate
from pywikibot.data.api import UploadWarning
from pywikibot.diff import PatchManager
import pywikibot.textlib as textlib
import pywikibot.tools
textlib_methods = (
'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts',
'isDisabled', 'interwikiFormat', 'interwikiSort',
'getLanguageLinks', 'replaceLanguageLinks',
'removeLanguageLinks', 'removeLanguageLinksAndSeparator',
'getCategoryLinks', 'categoryFormat', 'replaceCategoryLinks',
'removeCategoryLinks', 'removeCategoryLinksAndSeparator',
'replaceCategoryInPlace', 'compileLinkR', 'extract_templates_and_params',
'TimeStripper',
)
__all__ = (
'config', 'ui', 'UnicodeMixin', 'translate',
'Page', 'FilePage', 'Category', 'Link', 'User',
'ItemPage', 'PropertyPage', 'Claim',
'html2unicode', 'url2unicode', 'unicode2html',
'stdout', 'output', 'warning', 'error', 'critical', 'debug',
'exception', 'input_choice', 'input', 'input_yn', 'inputChoice',
'handle_args', 'handleArgs', 'showHelp', 'ui', 'log',
'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot',
'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'NoMoveTarget',
'SectionError',
'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily',
'UnknownExtension',
'NoUsername', 'UserBlocked', 'UserActionRefuse',
'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage',
'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError',
'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError',
'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict',
'UploadWarning',
'ServerError', 'FatalServerError', 'Server504Error',
'CaptchaError', 'SpamfilterError', 'CircularRedirect',
'InterwikiRedirectPage',
'WikiBaseError', 'CoordinateGlobeUnknownException',
'QuitKeyboardInterrupt',
)
__all__ += textlib_methods
if PY2:
# T111615: Python 2 requires __all__ is bytes
globals()['__all__'] = tuple(bytes(item) for item in __all__)
for _name in textlib_methods:
target = getattr(textlib, _name)
wrapped_func = redirect_func(target)
globals()[_name] = wrapped_func
deprecated = redirect_func(pywikibot.tools.deprecated)
deprecate_arg = redirect_func(pywikibot.tools.deprecate_arg)
class Timestamp(datetime.datetime):
"""Class for handling MediaWiki timestamps.
This inherits from datetime.datetime, so it can use all of the methods
and operations of a datetime object. To ensure that the results of any
operation are also a Timestamp object, be sure to use only Timestamp
objects (and datetime.timedeltas) in any operation.
Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to
create Timestamp objects from MediaWiki string formats.
As these constructors are typically used to create objects using data
passed provided by site and page methods, some of which return a Timestamp
when previously they returned a MediaWiki string representation, these
methods also accept a Timestamp object, in which case they return a clone.
Use Site.getcurrenttime() for the current time; this is more reliable
than using Timestamp.utcnow().
"""
mediawikiTSFormat = "%Y%m%d%H%M%S"
ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
def clone(self):
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classmethod
def fromISOformat(cls, ts):
"""Convert an ISO 8601 timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.ISO8601Format)
@classmethod
def fromtimestampformat(cls, ts):
"""Convert a MediaWiki internal timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.mediawikiTSFormat)
def isoformat(self):
"""
Convert object to an ISO 8601 timestamp accepted by MediaWiki.
datetime.datetime.isoformat does not postfix the ISO formatted date
with a 'Z' unless a timezone is included, which causes MediaWiki
~1.19 and earlier to fail.
"""
return self.strftime(self.ISO8601Format)
toISOformat = redirect_func(isoformat, old_name='toISOformat',
class_name='Timestamp')
def totimestampformat(self):
"""Convert object to a MediaWiki internal timestamp."""
return self.strftime(self.mediawikiTSFormat)
def __str__(self):
"""Return a string format recognized by the API."""
return self.isoformat()
def __add__(self, other):
"""Perform addition, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__add__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
def __sub__(self, other):
"""Perform substraction, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__sub__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
class Coordinate(object):
"""
Class for handling and storing Coordinates.
For now its just being used for DataSite, but
in the future we can use it for the GeoData extension.
"""
def __init__(self, lat, lon, alt=None, precision=None, globe='earth',
typ="", name="", dim=None, site=None, entity=''):
"""
Represent a geo coordinate.
@param lat: Latitude
@type lat: float
@param lon: Longitude
@type lon: float
@param alt: Altitute? TODO FIXME
@param precision: precision
@type precision: float
@param globe: Which globe the point is on
@type globe: str
@param typ: The type of coordinate point
@type typ: str
@param name: The name
@type name: str
@param dim: Dimension (in meters)
@type dim: int
@param entity: The URL entity of a Wikibase item
@type entity: str
"""
self.lat = lat
self.lon = lon
self.alt = alt
self._precision = precision
if globe:
globe = globe.lower()
self.globe = globe
self._entity = entity
self.type = typ
self.name = name
self._dim = dim
if not site:
self.site = Site().data_repository()
else:
self.site = site
def __repr__(self):
string = 'Coordinate(%s, %s' % (self.lat, self.lon)
if self.globe != 'earth':
string += ', globe="%s"' % self.globe
string += ')'
return string
@property
def entity(self):
if self._entity:
return self._entity
return self.site.globes()[self.globe]
def toWikibase(self):
"""
Export the data to a JSON object for the Wikibase API.
FIXME: Should this be in the DataSite object?
"""
if self.globe not in self.site.globes():
raise CoordinateGlobeUnknownException(
u"%s is not supported in Wikibase yet."
% self.globe)
return {'latitude': self.lat,
'longitude': self.lon,
'altitude': self.alt,
'globe': self.entity,
'precision': self.precision,
}
@classmethod
def fromWikibase(cls, data, site):
"""Constructor to create an object from Wikibase's JSON output."""
globes = {}
for k in site.globes():
globes[site.globes()[k]] = k
globekey = data['globe']
if globekey:
globe = globes.get(data['globe'])
else:
# Default to earth or should we use None here?
globe = 'earth'
return cls(data['latitude'], data['longitude'],
data['altitude'], data['precision'],
globe, site=site, entity=data['globe'])
@property
def precision(self):
u"""
Return the precision of the geo coordinate.
The biggest error (in degrees) will be given by the longitudinal error;
the same error in meters becomes larger (in degrees) further up north.
We can thus ignore the latitudinal error.
The longitudinal can be derived as follows:
In small angle approximation (and thus in radians):
M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given latitude.
Δλ is the error in longitude.
M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude
Therefore::
precision = math.degrees(self._dim/(radius*math.cos(math.radians(self.lat))))
"""
if not self._precision:
radius = 6378137 # TODO: Support other globes
self._precision = math.degrees(
self._dim / (radius * math.cos(math.radians(self.lat))))
return self._precision
def precisionToDim(self):
"""Convert precision from Wikibase to GeoData's dim."""
raise NotImplementedError
class WbTime(object):
"""A Wikibase time representation."""
PRECISION = {'1000000000': 0,
'100000000': 1,
'10000000': 2,
'1000000': 3,
'100000': 4,
'10000': 5,
'millenia': 6,
'century': 7,
'decade': 8,
'year': 9,
'month': 10,
'day': 11,
'hour': 12,
'minute': 13,
'second': 14
}
FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
def __init__(self, year=None, month=None, day=None,
hour=None, minute=None, second=None,
precision=None, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
"""
Create a new WbTime object.
The precision can be set by the Wikibase int value (0-14) or by a human
readable string, e.g., 'hour'. If no precision is given, it is set
according to the given time units.
"""
if year is None:
raise ValueError('no year given')
self.precision = self.PRECISION['second']
if second is None:
self.precision = self.PRECISION['minute']
second = 0
if minute is None:
self.precision = self.PRECISION['hour']
minute = 0
if hour is None:
self.precision = self.PRECISION['day']
hour = 0
if day is None:
self.precision = self.PRECISION['month']
day = 1
if month is None:
self.precision = self.PRECISION['year']
month = 1
self.year = long(year)
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.after = after
self.before = before
self.timezone = timezone
if calendarmodel is None:
if site is None:
site = Site().data_repository()
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel
# if precision is given it overwrites the autodetection above
if precision is not None:
if (isinstance(precision, int) and
precision in self.PRECISION.values()):
self.precision = precision
elif precision in self.PRECISION:
self.precision = self.PRECISION[precision]
else:
raise ValueError('Invalid precision: "%s"' % precision)
@classmethod
def fromTimestr(cls, datetimestr, precision=14, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z',
datetimestr)
if not match:
raise ValueError(u"Invalid format: '%s'" % datetimestr)
t = match.groups()
return cls(long(t[0]), int(t[1]), int(t[2]),
int(t[3]), int(t[4]), int(t[5]),
precision, before, after, timezone, calendarmodel, site)
def toTimestr(self):
"""
Convert the data to a UTC date/time string.
@return: str
"""
return self.FORMATSTR.format(self.year, self.month, self.day,
self.hour, self.minute, self.second)
def toWikibase(self):
"""
Convert the data to a JSON object for the Wikibase API.
@return: dict
"""
json = {'time': self.toTimestr(),
'precision': self.precision,
'after': self.after,
'before': self.before,
'timezone': self.timezone,
'calendarmodel': self.calendarmodel
}
return json
@classmethod
def fromWikibase(cls, ts):
return cls.fromTimestr(ts[u'time'], ts[u'precision'],
ts[u'before'], ts[u'after'],
ts[u'timezone'], ts[u'calendarmodel'])
def __str__(self):
return json.dumps(self.toWikibase(), indent=4, sort_keys=True,
separators=(',', ': '))
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return u"WbTime(year=%(year)d, month=%(month)d, day=%(day)d, " \
u"hour=%(hour)d, minute=%(minute)d, second=%(second)d, " \
u"precision=%(precision)d, before=%(before)d, after=%(after)d, " \
u"timezone=%(timezone)d, calendarmodel='%(calendarmodel)s')" \
% self.__dict__
class WbQuantity(object):
"""A Wikibase quantity representation."""
def __init__(self, amount, unit=None, error=None):
u"""
Create a new WbQuantity object.
@param amount: number representing this quantity
@type amount: float
@param unit: not used (only unit-less quantities are supported)
@param error: the uncertainty of the amount (e.g. ±1)
@type error: float, or tuple of two floats, where the first value is
the upper error and the second is the lower error value.
"""
if amount is None:
raise ValueError('no amount given')
if unit is None:
unit = '1'
self.amount = amount
self.unit = unit
upperError = lowerError = 0
if isinstance(error, tuple):
upperError, lowerError = error
elif error is not None:
upperError = lowerError = error
self.upperBound = self.amount + upperError
self.lowerBound = self.amount - lowerError
def toWikibase(self):
"""Convert the data to a JSON object for the Wikibase API."""
json = {'amount': self.amount,
'upperBound': self.upperBound,
'lowerBound': self.lowerBound,
'unit': self.unit
}
return json
@classmethod
def fromWikibase(cls, wb):
"""
Create a WbQuanity from the JSON data given by the Wikibase API.
@param wb: Wikibase JSON
"""
amount = eval(wb['amount'])
upperBound = eval(wb['upperBound'])
lowerBound = eval(wb['lowerBound'])
error = (upperBound - amount, amount - lowerBound)
return cls(amount, wb['unit'], error)
def __str__(self):
return json.dumps(self.toWikibase(), indent=4, sort_keys=True,
separators=(',', ': '))
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __repr__(self):
return (u"WbQuantity(amount=%(amount)s, upperBound=%(upperBound)s, "
u"lowerBound=%(lowerBound)s, unit=%(unit)s)" % self.__dict__)
_sites = {}
_url_cache = {} # The code/fam pair for each URL
def Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None):
"""A factory method to obtain a Site object.
Site objects are cached and reused by this method.
By default rely on config settings. These defaults may all be overridden
using the method parameters.
@param code: language code (override config.mylang)
@type code: string
@param fam: family name or object (override config.family)
@type fam: string or Family
@param user: bot user name to use on this site (override config.usernames)
@type user: unicode
@param sysop: sysop user to use on this site (override config.sysopnames)
@type sysop: unicode
@param interface: site class or name of class in pywikibot.site
(override config.site_interface)
@type interface: subclass of L{pywikibot.site.BaseSite} or string
@param url: Instead of code and fam, does try to get a Site based on the
URL. Still requires that the family supporting that URL exists.
@type url: string
"""
# Either code and fam or only url
if url and (code or fam):
raise ValueError('URL to the wiki OR a pair of code and family name '
'should be provided')
_logger = "wiki"
if url:
if url not in _url_cache:
matched_sites = []
# Iterate through all families and look, which does apply to
# the given URL
for fam in config.family_files:
family = pywikibot.family.Family.load(fam)
code = family.from_url(url)
if code is not None:
matched_sites += [(code, fam)]
if matched_sites:
if len(matched_sites) > 1:
pywikibot.warning(
'Found multiple matches for URL "{0}": {1} (use first)'
.format(url, ', '.join(str(s) for s in matched_sites)))
_url_cache[url] = matched_sites[0]
else:
# TODO: As soon as AutoFamily is ready, try and use an
# AutoFamily
_url_cache[url] = None
cached = _url_cache[url]
if cached:
code = cached[0]
fam = cached[1]
else:
raise SiteDefinitionError("Unknown URL '{0}'.".format(url))
else:
# Fallback to config defaults
code = code or config.mylang
fam = fam or config.family
interface = interface or config.site_interface
# config.usernames is initialised with a dict for each family name
family_name = str(fam)
if family_name in config.usernames:
user = user or config.usernames[family_name].get(code) \
or config.usernames[family_name].get('*')
sysop = sysop or config.sysopnames[family_name].get(code) \
or config.sysopnames[family_name].get('*')
if not isinstance(interface, type):
# If it isnt a class, assume it is a string
try:
tmp = __import__('pywikibot.site', fromlist=[interface])
interface = getattr(tmp, interface)
except ImportError:
raise ValueError("Invalid interface name '%(interface)s'" % locals())
if not issubclass(interface, pywikibot.site.BaseSite):
warning('Site called with interface=%s' % interface.__name__)
user = pywikibot.tools.normalize_username(user)
key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user)
if key not in _sites or not isinstance(_sites[key], interface):
_sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop)
debug(u"Instantiated %s object '%s'"
% (interface.__name__, _sites[key]), _logger)
if _sites[key].code != code:
warn('Site %s instantiated using different code "%s"'
% (_sites[key], code), UserWarning, 2)
return _sites[key]
# alias for backwards-compability
getSite = pywikibot.tools.redirect_func(Site, old_name='getSite')
from pywikibot.page import (
Page,
FilePage,
Category,
Link,
User,
ItemPage,
PropertyPage,
Claim,
)
from pywikibot.page import html2unicode, url2unicode, unicode2html
link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]')
@pywikibot.tools.deprecated("comment parameter for page saving method")
def setAction(s):
"""Set a summary to use for changed page submissions."""
config.default_edit_summary = s
def showDiff(oldtext, newtext, context=0):
"""
Output a string showing the differences between oldtext and newtext.
The differences are highlighted (only on compatible systems) to show which
changes were made.
"""
PatchManager(oldtext, newtext, context=context).print_hunks()
# Throttle and thread handling
stopped = False
def stopme():
"""Drop this process from the throttle log, after pending threads finish.
Can be called manually if desired, but if not, will be called automatically
at Python exit.
"""
global stopped
_logger = "wiki"
if not stopped:
debug(u"stopme() called", _logger)
def remaining():
remainingPages = page_put_queue.qsize() - 1
# -1 because we added a None element to stop the queue
remainingSeconds = datetime.timedelta(
seconds=(remainingPages * config.put_throttle))
return (remainingPages, remainingSeconds)
page_put_queue.put((None, [], {}))
stopped = True
if page_put_queue.qsize() > 1:
num, sec = remaining()
format_values = dict(num=num, sec=sec)
output(u'\03{lightblue}'
u'Waiting for %(num)i pages to be put. '
u'Estimated time remaining: %(sec)s'
u'\03{default}' % format_values)
while(_putthread.isAlive()):
try:
_putthread.join(1)
except KeyboardInterrupt:
if input_yn('There are %i pages remaining in the queue. '
'Estimated time remaining: %s\nReally exit?'
% remaining(), default=False, automatic_quit=False):
return
# only need one drop() call because all throttles use the same global pid
try:
list(_sites.values())[0].throttle.drop()
log(u"Dropped throttle(s).")
except IndexError:
pass
import atexit
atexit.register(stopme)
# Create a separate thread for asynchronous page saves (and other requests)
def async_manager():
"""Daemon; take requests from the queue and execute them in background."""
while True:
(request, args, kwargs) = page_put_queue.get()
if request is None:
break
request(*args, **kwargs)
page_put_queue.task_done()
def async_request(request, *args, **kwargs):
"""Put a request on the queue, and start the daemon if necessary."""
if not _putthread.isAlive():
try:
page_put_queue.mutex.acquire()
try:
_putthread.start()
except (AssertionError, RuntimeError):
pass
finally:
page_put_queue.mutex.release()
page_put_queue.put((request, args, kwargs))
# queue to hold pending requests
page_put_queue = Queue(config.max_queue_size)
# set up the background thread
_putthread = threading.Thread(target=async_manager)
# identification for debugging purposes
_putthread.setName('Put-Thread')
_putthread.setDaemon(True)
wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__)
wrapper._add_deprecated_attr('ImagePage', FilePage)
wrapper._add_deprecated_attr(
'PageNotFound', pywikibot.exceptions.DeprecatedPageNotFoundError,
warning_message=('{0}.{1} is deprecated, and no longer '
'used by pywikibot; use http.fetch() instead.'))
wrapper._add_deprecated_attr(
'UserActionRefuse', pywikibot.exceptions._EmailUserError,
warning_message='UserActionRefuse is deprecated; '
'use UserRightsError and/or NotEmailableError')
wrapper._add_deprecated_attr(
'QuitKeyboardInterrupt', pywikibot.bot.QuitKeyboardInterrupt,
warning_message='pywikibot.QuitKeyboardInterrupt is deprecated; '
'use pywikibot.bot.QuitKeyboardInterrupt instead')
| icyflame/batman | pywikibot/__init__.py | Python | mit | 26,823 |
package gui;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.DefaultComboBoxModel;
import javax.swing.UIManager;
import app.Applikation;
import javax.swing.DropMode;
import parsers.*;
import java.io.IOException;
import java.util.Random;
public class GUI {
private JFrame frmImageDownloader;
private JTextField txtInsertTagHere;
private JTextArea textArea;
private JSpinner PageSpinner;
private JComboBox<Object> comboBox;
private ImageParser parser;
private JButton Parsebtn;
private JTextField DelayField;
private BufferedImage bgImage;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblTag;
private final String FOURCHAN_THREAD = "4chan-Thread - http://boards.4chan.org/x/res/123123";
private final String FOURCHAN_BOARD = "4chan-Board - http://boards.4chan.org/x/catalog";
private final String INFINITYCHAN_THREAD = "Infinity Chan Thread - https://8chan.co/BOARD/res/THREADNR.html";
private final String INFINITYCHAN_BOARD = "Infinity Chan Board - https://8chan.co/BOARDNR/";
private final String PAHEAL = "http://rule34.paheal.net/";
private final String XXX = "http://rule34.xxx/";
private final String GELBOORU = "http://gelbooru.com/";
private final String R34HENTAI = "http://rule34hentai.net/";
private final String TUMBLR = "Tumblr Artist - http://XxXxXxX.tumblr.com";
private final String IMGUR = "Imgur-Album - http://imgur.com/a/xXxXx";
private final String GE_HENTAI_SINGLE = "http://g.e-hentai.org/ - Single Album Page";
private final String GE_HENTAI_MORE = "http://g.e-hentai.org/ - >=1 Pages";
private final String ARCHIVE_MOE_THREAD = "archive.moe/fgts.jp (Thread) - https://archive.moe/BOARD/thread/THREADNR/";
private final String ARCHIVE_MOE_BOARD = "archive-moe (Board) - https://archive.moe/BOARD/";
private final String FGTS_JP_BOARD = "fgts.jp (Board) - http://fgts.jp/BOARD/";
private boolean parsing;
public GUI() {
System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
frmImageDownloader = new JFrame();
frmImageDownloader.setIconImage(Toolkit.getDefaultToolkit()
.getImage(this.getClass().getResource("/images/icon.png")));
frmImageDownloader.getContentPane().setBackground(
UIManager.getColor("Button.background"));
frmImageDownloader.setResizable(false);
frmImageDownloader.setTitle("Image Downloader v1.5.1");
frmImageDownloader.setBounds(100, 100, 761, 558);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmImageDownloader.getContentPane().setLayout(null);
JLabel lblMadeByLars = new JLabel("@ berserkingyadis");
lblMadeByLars.setFont(new Font("Dialog", Font.PLAIN, 12));
lblMadeByLars.setBounds(14, 468, 157, 40);
frmImageDownloader.getContentPane().add(lblMadeByLars);
JScrollPane scrollPane = new JScrollPane();
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(205, 185, 542, 331);
scrollPane.setAutoscrolls(true);
frmImageDownloader.getContentPane().add(scrollPane);
try {
bgImage = ImageIO.read(Applikation.class.getResource("/images/bg" + (new Random().nextInt(4) + 1) + ".png"));
} catch (IOException e) {
appendLog("Could not get Background Image", true);
}
textArea = new BackgroundArea(bgImage);
textArea.setEditable(false);
textArea.setDropMode(DropMode.INSERT);
textArea.setColumns(2);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 11));
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
txtInsertTagHere = new JTextField();
txtInsertTagHere.setText("insert tag here");
txtInsertTagHere.setFont(new Font("Dialog", Font.PLAIN, 14));
txtInsertTagHere.setBounds(14, 208, 181, 30);
frmImageDownloader.getContentPane().add(txtInsertTagHere);
txtInsertTagHere.setColumns(10);
lblTag = new JLabel("Tag:");
lblTag.setFont(new Font("Dialog", Font.BOLD, 12));
lblTag.setBounds(12, 183, 175, 24);
frmImageDownloader.getContentPane().add(lblTag);
Parsebtn = new JButton("start parsing");
Parsebtn.setBounds(12, 372, 181, 85);
frmImageDownloader.getContentPane().add(Parsebtn);
PageSpinner = new JSpinner();
PageSpinner.setModel(new SpinnerNumberModel(new Integer(1),
new Integer(1), null, new Integer(1)));
PageSpinner.setBounds(155, 249, 40, 30);
frmImageDownloader.getContentPane().add(PageSpinner);
lblNewLabel = new JLabel("Pages to parse:");
lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 11));
lblNewLabel.setBounds(12, 249, 123, 30);
frmImageDownloader.getContentPane().add(lblNewLabel);
lblNewLabel_1 = new JLabel("1 Page = 50-60 Pictures");
lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_1.setBounds(12, 290, 175, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_1);
comboBox = new JComboBox<Object>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
switch (comboBox.getSelectedItem().toString()) {
case GE_HENTAI_SINGLE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(false);
lblTag.setText("Page URL:");
txtInsertTagHere.setText("insert page URL here");
lblNewLabel.setEnabled(false);
break;
case GE_HENTAI_MORE:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Album URL:");
txtInsertTagHere.setText("insert album URL here");
break;
case PAHEAL:
case GELBOORU:
case R34HENTAI:
case XXX:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Tag:");
txtInsertTagHere.setText("insert tag here");
lblNewLabel.setText("Pages to parse:");
break;
case FOURCHAN_THREAD:
case INFINITYCHAN_THREAD:
case ARCHIVE_MOE_THREAD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setText("Pages to parse:");
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
lblTag.setText("Thread URL:");
txtInsertTagHere.setText("insert link here");
break;
case FOURCHAN_BOARD:
case INFINITYCHAN_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Threads to parse:");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case ARCHIVE_MOE_BOARD:
case FGTS_JP_BOARD:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("10");
lblNewLabel.setEnabled(true);
lblNewLabel.setText("Sites to parse(1 Site = 100 Threads):");
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(true);
lblTag.setText("Board(eg: v or e):");
txtInsertTagHere.setText("insert Board Letter here");
break;
case TUMBLR:
Parsebtn.setEnabled(true);
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setText("start parsing");
DelayField.setText("100");
lblNewLabel.setEnabled(true);
lblNewLabel_1.setEnabled(true);
PageSpinner.setEnabled(true);
lblTag.setText("Artist name:");
txtInsertTagHere.setText("insert artist name here");
lblNewLabel.setText("Pages to parse:");
break;
case IMGUR:
lblNewLabel.setEnabled(false);
lblNewLabel_1.setEnabled(false);
PageSpinner.setEnabled(false);
DelayField.setText("100");
lblTag.setText("Album Letters: (eg: \"Bl1QP\")");
txtInsertTagHere.setText("insert the letters here");
Parsebtn.setText("start parsing");
Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12));
Parsebtn.setEnabled(true);
break;
}
}
});
comboBox.setModel(new DefaultComboBoxModel<Object>(
new String[]{
PAHEAL,
XXX,
R34HENTAI,
GELBOORU,
GE_HENTAI_SINGLE,
GE_HENTAI_MORE,
FOURCHAN_THREAD,
FOURCHAN_BOARD,
//ARCHIVE_MOE_THREAD,
//ARCHIVE_MOE_BOARD,
//FGTS_JP_BOARD,
INFINITYCHAN_THREAD,
INFINITYCHAN_BOARD,
TUMBLR,
IMGUR
}));
comboBox.setBounds(434, 35, 313, 24);
comboBox.setFont(new Font("Dialog", Font.PLAIN, 11));
frmImageDownloader.getContentPane().add(comboBox);
JLabel lblNewLabel_2 = new JLabel("choose the Site to parse:");
lblNewLabel_2.setFont(new Font("Dialog", Font.BOLD, 12));
lblNewLabel_2.setBounds(434, 5, 268, 30);
frmImageDownloader.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_3 = new JLabel(
"<html>\nWelcome to the Image Downloader. <br>\nYour can enter the Tag of the images you are looking for below. <br>\nImgur is not supported yet. <br>\nWhen you click parse a folder with the name of the tag will be <br>\ncreated and the images will be downloaded into it. <br><br>\nI strongly advise you to not set the delay under 100 ms, <br>\nif you abuse this you will get banned from the site <br><br>\n\nhave fun :)\n\n\n</html>");
lblNewLabel_3.setVerticalAlignment(SwingConstants.TOP);
lblNewLabel_3.setFont(new Font("Dialog", Font.PLAIN, 12));
lblNewLabel_3.setBounds(12, 12, 404, 195);
frmImageDownloader.getContentPane().add(lblNewLabel_3);
JLabel lblDelay = new JLabel("Delay(ms):");
lblDelay.setFont(new Font("Dialog", Font.BOLD, 12));
lblDelay.setBounds(12, 331, 85, 30);
frmImageDownloader.getContentPane().add(lblDelay);
DelayField = new JTextField();
DelayField.setText("100");
DelayField.setBounds(140, 331, 55, 30);
frmImageDownloader.getContentPane().add(DelayField);
DelayField.setColumns(10);
JLabel lblPahealSearchFor = new JLabel(
"<html>\r\npaheal: Search for Characters or Artists\r\n\t\t eg: Tifa Lockhart, Fugtrup<br>\r\nrule34.xxx: Search for things\r\n\t\teg: long hair, hand on hip<br>\r\ngelbooru: Search for what you want<br>\r\n4chan/8chan: paste the Thread URL/Boardletter in the\r\n\t\tTextfield <br>\r\ntumblr: enter the artist's name<br>imgur: enter the album id</html>");
lblPahealSearchFor.setVerticalAlignment(SwingConstants.TOP);
lblPahealSearchFor.setFont(new Font("Dialog", Font.PLAIN, 11));
lblPahealSearchFor.setBounds(434, 71, 313, 109);
frmImageDownloader.getContentPane().add(lblPahealSearchFor);
Parsebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (parsing) {
parser.diePlease();
parser = null;
} else {
GUI g = getGUI();
textArea.setText("");
frmImageDownloader
.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
String tag = txtInsertTagHere.getText().replace(' ', '_');
int pages = (int) PageSpinner.getValue();
String site = comboBox.getSelectedItem().toString();
int delay = Integer.parseInt(DelayField.getText());
switch (site) {
case PAHEAL:
parser = new PahealParser();
parser.setup(tag, pages, g, delay);
break;
case XXX:
parser = new XXXParser();
parser.setup(tag, pages, g, delay);
break;
case R34HENTAI:
parser = new R34HentaiParser();
parser.setup(tag, pages, g, delay);
break;
case GELBOORU:
parser = new GelBooruParser();
parser.setup(tag, pages, g, delay);
break;
case FOURCHAN_THREAD:
parser = new FourChanParser(tag, delay, g, 0);
break;
case FOURCHAN_BOARD:
parser = new FourChanParser(tag, delay, g, 1, pages);
break;
case INFINITYCHAN_THREAD:
parser = new InfinityChanParser(tag, delay, g, 0);
break;
case INFINITYCHAN_BOARD:
parser = new InfinityChanParser(tag, delay, g, 1, pages);
break;
case ARCHIVE_MOE_THREAD:
parser = new ArchiveMoeParser(tag, delay, g, 0);
break;
case ARCHIVE_MOE_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 1, pages);
break;
case FGTS_JP_BOARD:
parser = new ArchiveMoeParser(tag, delay, g, 2, pages);
break;
case TUMBLR:
parser = new TumblrParser();
parser.setup(tag, pages, g, delay);
break;
case IMGUR:
parser = new ImgurParser(tag, delay, g);
break;
case GE_HENTAI_SINGLE:
parser = new GEHentaiParser(tag, delay, g, false, pages);
break;
case GE_HENTAI_MORE:
parser = new GEHentaiParser(tag, delay, g, true, pages);
}
parser.start();
parsing = true;
Parsebtn.setText("stop parsing");
}
}
});
frmImageDownloader.setVisible(true);
parsing = false;
}
public void appendLog(String txt, boolean brk) {
textArea.append(txt);
if (brk)
textArea.append("\n");
}
private GUI getGUI() {
return this;
}
public void reportback() {
Parsebtn.setEnabled(true);
frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Parsebtn.setText("start parsing");
parsing = false;
}
}
| berserkingyadis/ImageDownloader | src/main/java/gui/GUI.java | Java | mit | 18,735 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package curveavg;
/**
* Small helper class for computing the circular arc between two points.
* @author Sebastian Weiss
*/
public class CircularArc {
private static final float EPSILON = 1e-5f;
private final Vector3f P;
private final Vector3f A;
private final Vector3f B;
private Vector3f C;
private float r;
private Vector3f N;
private Vector3f CA;
private float angle;
/**
* Computes the circular arc between the points A and B, with the point P on the
* medial axis (i.e. |A-N|==|B-N|).
* @param P the point on the medial axis, A and B are at the same distance from P
* @param A the closest point from P on the first control curve
* @param B the closest point from P on the second control curve
*/
public CircularArc(Vector3f P, Vector3f A, Vector3f B) {
this.P = P;
this.A = A;
this.B = B;
computeCenter();
}
private void computeCenter() {
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
//check for degenerated case
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
r = 0;
return; //Degenerated to a line
}
//compute directions of A,B to the center C
N.normalizeLocal();
PA.normalizeLocal();
PB.normalizeLocal();
Vector3f U = N.cross(PA);
Vector3f V = N.cross(PB);
//C is now the intersection of A+aU and B+bV
Vector3f UxV = U.cross(V);
Vector3f rhs = (B.subtract(A)).cross(V);
float a1 = rhs.x / UxV.x;
float a2 = rhs.y / UxV.y;
float a3 = rhs.z / UxV.z; //all a1,a2,a3 have to be equal
C = A.addScaled(a1, U);
//compute radius and angle
r = C.distance(A);
CA = A.subtract(C);
angle = (CA.normalize()).angleBetween((B.subtract(C).normalizeLocal()));
}
private float computeCenter_old() {
//check for degenerated case
Vector3f PA = A.subtract(P);
Vector3f PB = B.subtract(P);
N = PA.cross(PB);
if (N.lengthSquared() <= EPSILON*EPSILON) {
// System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line");
return 0; //Degenerated to a line
}
//define orthonormal basis I,J,K
N.normalizeLocal();
Vector3f I = PA.normalize();
Vector3f J = N.cross(I);
Vector3f K = N;
Vector3f IxK = I.cross(K);
Vector3f JxK = J.cross(K);
//project points in the plane PAB
Vector3f PAxN = PA.cross(N);
Vector3f PBxN = PB.cross(N);
Vector2f P2 = new Vector2f(0, 0);
Vector2f A2 = new Vector2f(PA.dot(JxK)/I.dot(JxK), PA.dot(IxK)/J.dot(IxK));
Vector2f B2 = new Vector2f(PB.dot(JxK)/I.dot(JxK), PB.dot(IxK)/J.dot(IxK));
//compute time t of C=P+tPA°
float t;
if (B2.x == A2.x) {
t = (B2.y - A2.y) / (A2.x - B2.x);
} else {
t = (B2.x - A2.x) / (A2.y - B2.y);
}
//compute C
Vector2f PArot = new Vector2f(A.y-P.y, P.x-A.x);
Vector2f C2 = P2.addLocal(PArot.multLocal(t));
//project back
C = new Vector3f(P);
C.addScaledLocal(C2.x, I);
C.addScaledLocal(C2.y, J);
//Debug
// System.out.println("A="+A+", B="+B+" P="+P+" -> I="+I+", J="+J+", K="+K+", P'="+P2+", A'="+A2+", B'="+B2+", t="+t+", C'="+C2+", C="+C);
//set radius
return C.distance(A);
}
/**
* Computes a point on the actual circular arc from A to B.
* The vectors C and the float r are the result from
* {@link #computeCenter(curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f) }.
* It interpolates from A (alpha=0) to B (alpha=1) in a circular arc.
* @param alpha
* @return
*/
public Vector3f getPointOnArc(float alpha) {
if (isDegenerated()) {
Vector3f V = new Vector3f();
return V.interpolateLocal(A, B, alpha); //degenerated case
}
//normal case, rotate
Vector3f V = rotate(alpha*angle, CA, N);
return V.addLocal(C);
}
private static Vector3f rotate(float angle, Vector3f X, Vector3f N) {
Vector3f W = N.mult(N.dot(X));
Vector3f U = X.subtract(W);
return W.add(U.mult((float) Math.cos(angle)))
.subtract(N.cross(U).mult((float) Math.sin(angle)));
}
public boolean isDegenerated() {
return r==0;
}
public Vector3f getCenter() {
return C;
}
public float getRadius() {
return r;
}
public Vector3f getNormal() {
return N;
}
public float getAngle() {
return angle;
}
@Override
public String toString() {
return "CircularArc{" + "P=" + P + ", A=" + A + ", B=" + B + " -> C=" + C + ", r=" + r + ", N=" + N + ", angle=" + angle + '}';
}
}
| shamanDevel/CurveAverage | src/curveavg/CircularArc.java | Java | mit | 4,540 |
// These two object contain information about the state of Ebl
var GlobalState = Base.extend({
constructor: function() {
this.isAdmin = false;
this.authToken = null;
this.docTitle = null;
this.container = null;
// default config
this.config = {
template: 'default',
language: 'en',
postsPerPage: 5,
pageTitleFormat: "{ebl_title} | {doc_title}",
// callbacks
onBlogLoaded: null,
onPostOpened: null,
onPageChanged: null
};
}
});
var LocalState = Base.extend({
constructor: function() {
this.page = 0;
this.post = null;
this.editors = null;
}
});
var PostStatus = {
NEW: 0,
DRAFT: 1,
PUBLISHED: 2,
parse: function (s) {
if (s.toLowerCase() == "new") return 0;
if (s.toLowerCase() == "draft") return 1;
if (s.toLowerCase() == "published") return 2;
return null;
}
};
var gState = new GlobalState(); // state shared among the entire session
var lState = new LocalState(); // state of the current view
| alessandrofrancesconi/ebl | ebl/core/js_src/state/state.js | JavaScript | mit | 1,178 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DiveConditions.ViewModels.Manage
{
public class FactorViewModel
{
public string Purpose { get; set; }
}
}
| DiveConditions/DiveConditions | src/DiveConditions/ViewModels/Manage/FactorViewModel.cs | C# | mit | 237 |
//
// This file genenerated by the Buckle tool on 2/13/2015 at 8:27 AM.
//
// Contains strongly typed wrappers for resources in VacuumResources.resx
//
namespace Vacuum {
using System;
using System.Reflection;
using System.Resources;
using System.Diagnostics;
using System.Globalization;
/// <summary>
/// Strongly typed resource wrappers generated from VacuumResources.resx.
/// </summary>
public class VacuumResources
{
internal static readonly ResourceManager ResourceManager = new ResourceManager(typeof(VacuumResources));
/// <summary>
/// File '{0}' does not exist
/// </summary>
public static string FileNotFound(object param0)
{
string format = ResourceManager.GetString("FileNotFound", CultureInfo.CurrentUICulture);
return string.Format(CultureInfo.CurrentCulture, format, param0);
}
}
}
| jlyonsmith/Vacuum | VacuumLibrary/Resources/VacuumResources.cs | C# | mit | 847 |
<?php
include "config.php";
session_start();
if(!isset($_SESSION['username'])){
//header("location:login.php");
}
?>
<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>HOSPITAL MANAGMENT SYSTEM</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<!-- Main Header -->
<header class="main-header">
<!-- Logo -->
<a href="" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>H</b>MS</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>HMS</b></span>
</a>
<!-- Header Navbar -->
<nav class="navbar navbar-static-top" role="navigation">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user"></i>
<b class="caret hidden-sm hidden-xs"></b>
<span class="notification hidden-sm hidden-xs">2</span>
<p class="hidden-lg hidden-md">
5 Notifications
<b class="caret"></b>
</p>
</a>
<ul class="dropdown-menu">
<li><a href="login.php">Logout</a></li>
<li><a href="#">change password</a></li>
</ul>
</li>
<li class="separator hidden-lg hidden-md"></li>
</ul>
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
<span class="sr-only">Toggle navigation</span>
</a>
<!-- Navbar Right Menu -->
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!-- Messages: style can be found in dropdown.less-->
<li class="dropdown messages-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-envelope-o"></i>
<span class="label label-success"></span>
</a>
<ul class="dropdown-menu">
<!-- inner menu: contains the messages -->
<ul class="menu">
<li><!-- start message -->
<a href="#">
<div class="pull-left">
<!-- User Image -->
<i class=""></i>
</div>
</a>
</li>
<!-- end message -->
</ul>
<!-- /.menu -->
</li>
<li class="footer"><a href="#"></a></li>
</ul>
</li>
<!-- /.messages-menu -->
<!-- Notifications Menu -->
<li class="dropdown notifications-menu">
<!-- Menu toggle button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class=""></i>
<span class="label label-warning"></span>
</a>
<ul class="dropdown-menu">
<!-- Tasks Menu -->
<li class="dropdown tasks-menu">
<!-- Menu Toggle Button -->
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class=""></i>
<span class=""></span>
</a>
<ul class="dropdown-menu">
<li class="header"></li>
<li>
</li>
<!-- User Account Menu -->
<!-- Menu Body -->
<li class="user-body">
<!-- /.row -->
</li>
<!-- Menu Footer-->
</ul>
</li>
<!-- Control Sidebar Toggle Button -->
<li>
<a href="#" data-toggle="control-sidebar"><i class=""></i></a>
</li>
</ul>
</div>
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar">
<!-- sidebar: style can be found in sidebar.less -->
<section class="sidebar">
<!-- Sidebar Menu -->
<?php
include "sidebar.php";
?>
<!-- /.sidebar-menu -->
</section>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
</section>
<!-- Main content -->
<section class="content container-fluid">
<?php
include("xray_registration.php");
?>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="pull-right hidden-xs">
</div>
<!-- Default to the left -->
<strong>Copyright © 2017 <a href="#">Group</a>.</strong> All rights reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified control-sidebar-tabs">
<li class="active"><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane active" id="control-sidebar-home-tab">
<h3 class="control-sidebar-heading">Recent Activity</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:;">
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="control-sidebar-subheading">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
<h3 class="control-sidebar-heading">Tasks Progress</h3>
<ul class="control-sidebar-menu">
<li>
<a href="javascript:;">
<h4 class="control-sidebar-subheading">
Custom Template Design
<span class="pull-right-container">
<span class="label label-danger pull-right">70%</span>
</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
</ul>
<!-- /.control-sidebar-menu -->
</div>
<!-- /.tab-pane -->
<!-- Stats tab content -->
<div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="control-sidebar-settings-tab">
<form method="post">
<h3 class="control-sidebar-heading">General Settings</h3>
<div class="form-group">
<label class="control-sidebar-subheading">
Report panel usage
<input type="checkbox" class="pull-right" checked>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside>
<!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar -->
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- REQUIRED JS SCRIPTS -->
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<!-- Optionally, you can add Slimscroll and FastClick plugins.
Both of these plugins are recommended to enhance the
user experience. -->
</body>
</html> | abdiwahab-omar/team | xray_display.php | PHP | mit | 9,171 |
require "pact_broker/api/resources/can_i_deploy_pacticipant_version_by_tag_to_tag"
require "pact_broker/matrix/service"
module PactBroker
module Api
module Resources
describe CanIDeployPacticipantVersionByBranchToEnvironment do
include_context "stubbed services"
before do
allow(PactBroker::Deployments::EnvironmentService).to receive(:find_by_name).and_return(environment)
allow(PactBroker::Matrix::Service).to receive(:can_i_deploy).and_return([])
allow(pacticipant_service).to receive(:find_pacticipant_by_name).and_return(pacticipant)
allow(PactBroker::Api::Decorators::MatrixDecorator).to receive(:new).and_return(decorator)
allow(version_service).to receive(:find_latest_by_pacticipant_name_and_branch_name).and_return(version)
end
let(:pacticipant) { double("pacticipant") }
let(:version) { double("version") }
let(:json_response_body) { JSON.parse(subject.body, symbolize_names: true) }
let(:decorator) { double("decorator", to_json: "response_body") }
let(:selectors) { double("selectors") }
let(:options) { double("options") }
let(:environment) { double("environment") }
let(:path) { "/pacticipants/Foo/branches/main/latest-version/can-i-deploy/to-environment/dev" }
subject { get(path, nil, "Content-Type" => "application/hal+json") }
it "looks up the by branch" do
expect(version_service).to receive(:find_latest_by_pacticipant_name_and_branch_name).with("Foo", "main")
subject
end
it "checks if the version can be deployed to the environment" do
expect(PactBroker::Matrix::Service).to receive(:can_i_deploy).with(anything, hash_including(environment_name: "dev"))
subject
end
it { is_expected.to be_a_hal_json_success_response }
context "when the environment does not exist" do
let(:environment) { nil }
its(:status) { is_expected.to eq 404 }
end
end
end
end
end
| pact-foundation/pact_broker | spec/lib/pact_broker/api/resources/can_i_deploy_pacticipant_version_by_branch_to_environment_spec.rb | Ruby | mit | 2,071 |
import React from 'react'
import {
Container,
Group,
TabBar,
Icon,
Badge,
amStyles,
} from 'amazeui-touch'
import {Link} from 'react-router'
class App extends React.Component{
propsType ={
children:React.PropTypes.node
}
render(){
let {
location,
params,
children,
...props
} = this.props;
let transition = children.props.transition || 'sfr'
return (
<Container direction="column">
<Container
transition={transition}
>
{children}
</Container>
<TabBar
>
<TabBar.Item
component={Link}
eventKey = 'home'
active = {location.pathname === '/'}
icon = 'home'
title = '首页'
to='/'
/>
<TabBar.Item
component={Link}
active={location.pathname === '/class'}
eventKey="class"
icon="list"
title="课程"
to='/class'
/>
<TabBar.Item
active={location.pathname === '/search'}
eventKey="search"
icon="search"
title="发现"
/>
<TabBar.Item
component={Link}
active={location.pathname === '/me'}
eventKey="person"
icon="person"
title="我"
to='/me'
/>
</TabBar>
</Container>
)
}
}
export default App | yiweimatou/yiweimatou-mobile | src/components/pages/app.js | JavaScript | mit | 1,961 |
<?php
$article_excerpt_categories = get_the_category();
$article_excerpt_categories_output = "";
if ( ! empty( $article_excerpt_categories ) ) {
$article_excerpt_categories_output = esc_html( $article_excerpt_categories[0]->name );
}
?>
<article class="su-article su-article--divider su-article--<?php echo strtolower($article_excerpt_categories_output); ?>" id="post-<?php the_ID(); ?>">
<header class="su-header su-article__header">
<h2 class="su-heading su-heading--two su-article__title">
<a href="<?php the_permalink() ?>" rel="bookmark" class="su-heading__link">
<?php the_title() ?>
</a>
</h2>
<div class="su-article__date"><?php the_date() ?></div>
</header>
<div class="su-article__content">
<?php
the_excerpt();
?>
<a href="<?php the_permalink()?>" class="su-article__more">Continue reading <span class="su-article__more-sr-only"><?php the_title() ?></span></a>
</div>
<footer class="su-article__footer">
<div class="su-article-meta su-article-meta--short">
<?php sheru_entry_meta(); ?>
</div>
</footer>
</article>
| shellbryson/sheru | template-parts/excerpt.php | PHP | mit | 1,104 |
<?php
namespace framework\ext;
//xml解析成数组
class Xml
{
public static function decode($xml)
{
$values = array();
$index = array();
$array = array();
$parser = xml_parser_create('utf-8');
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = self::_struct_to_array($values, $i);
return $array;
}
private static function _struct_to_array($values, &$i)
{
$child = array();
if (isset($values[$i]['value']))
array_push($child, $values[$i]['value']);
while ($i++ < count($values))
{
switch ($values[$i]['type'])
{
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name))
{
$child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes']))
{
$child[$name] = $values[$i]['attributes'];
}
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = self::_struct_to_array($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
} | cyrilzhao/zqzirui | framework/ext/Xml.php | PHP | mit | 1,581 |
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;
import java.io.IOException;
public class SingleEmailMultipleRecipients {
public static void main(String[] args) throws IOException {
final Mail mail = new Mail();
mail.setFrom(new Email("test@example.com", "Example User"));
mail.setSubject("Sending with Twilio SendGrid is Fun");
final Personalization personalization = new Personalization();
personalization.addTo(new Email("test1@example.com", "Example User1"));
personalization.addTo(new Email("test2@example.com", "Example User2"));
personalization.addTo(new Email("test3@example.com", "Example User3"));
mail.addPersonalization(personalization);
mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java"));
mail.addContent(new Content("text/html", "<strong>and easy to do anywhere, even with Java</strong>"));
send(mail);
}
private static void send(final Mail mail) throws IOException {
final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY"));
final Request request = new Request();
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
final Response response = client.api(request);
System.out.println(response.getStatusCode());
System.out.println(response.getBody());
System.out.println(response.getHeaders());
}
}
| sendgrid/sendgrid-java | examples/helpers/mail/SingleEmailMultipleRecipients.java | Java | mit | 1,666 |
<?php
namespace BlogBundle\Document;
use Doctrine\ODM\MongoDB\DocumentRepository;
class TagRepository extends DocumentRepository
{
public function getTagByName($name = '')
{
$query = $this->createQueryBuilder()
->field('name')->equals($name);
return $query->getQuery()->getSingleResult();
}
public function getAllTags()
{
return $this->createQueryBuilder()
->hydrate(false)
->getQuery()
->toArray();
}
}
| haltaction/blog | src/BlogBundle/Document/TagRepository.php | PHP | mit | 505 |
<?php
/**
* Phinx
*
* (The MIT license)
* Copyright (c) 2014 Rob Morgan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated * documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* @package Phinx
* @subpackage Phinx\Db
*/
namespace Phinx\Db;
use Phinx\Db\Table\Column;
use Phinx\Db\Table\Index;
use Phinx\Db\Table\ForeignKey;
use Phinx\Db\Adapter\AdapterInterface;
/**
*
* This object is based loosely on: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
*/
class Table
{
/**
* @var string
*/
protected $name;
/**
* @var array
*/
protected $options = array();
/**
* @var AdapterInterface
*/
protected $adapter;
/**
* @var array
*/
protected $columns = array();
/**
* @var array
*/
protected $indexes = array();
/**
* @var ForeignKey[]
*/
protected $foreignKeys = array();
/**
* Class Constuctor.
*
* @param string $name Table Name
* @param array $options Options
* @param AdapterInterface $adapter Database Adapter
* @return void
*/
public function __construct($name, $options = array(), AdapterInterface $adapter = null)
{
$this->setName($name);
$this->setOptions($options);
if (null !== $adapter) {
$this->setAdapter($adapter);
}
}
/**
* Sets the table name.
*
* @param string $name Table Name
* @return Table
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Gets the table name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Sets the table options.
*
* @param array $options
* @return Table
*/
public function setOptions($options)
{
$this->options = $options;
return $this;
}
/**
* Gets the table options.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets the database adapter.
*
* @param AdapterInterface $adapter Database Adapter
* @return Table
*/
public function setAdapter(AdapterInterface $adapter)
{
$this->adapter = $adapter;
return $this;
}
/**
* Gets the database adapter.
*
* @return AdapterInterface
*/
public function getAdapter()
{
return $this->adapter;
}
/**
* Does the table exist?
*
* @return boolean
*/
public function exists()
{
return $this->getAdapter()->hasTable($this->getName());
}
/**
* Drops the database table.
*
* @return void
*/
public function drop()
{
$this->getAdapter()->dropTable($this->getName());
}
/**
* Renames the database table.
*
* @param string $newTableName New Table Name
* @return Table
*/
public function rename($newTableName)
{
$this->getAdapter()->renameTable($this->getName(), $newTableName);
$this->setName($newTableName);
return $this;
}
/**
* Sets an array of columns waiting to be committed.
* Use setPendingColumns
*
* @deprecated
* @param array $columns Columns
* @return Table
*/
public function setColumns($columns)
{
$this->setPendingColumns($columns);
}
/**
* Gets an array of the table columns.
*
* @return Column[]
*/
public function getColumns()
{
return $this->getAdapter()->getColumns($this->getName());
}
/**
* Sets an array of columns waiting to be committed.
*
* @param array $columns Columns
* @return Table
*/
public function setPendingColumns($columns)
{
$this->columns = $columns;
return $this;
}
/**
* Gets an array of columns waiting to be committed.
*
* @return array
*/
public function getPendingColumns()
{
return $this->columns;
}
/**
* Sets an array of columns waiting to be indexed.
*
* @param array $indexes Indexes
* @return Table
*/
public function setIndexes($indexes)
{
$this->indexes = $indexes;
return $this;
}
/**
* Gets an array of indexes waiting to be committed.
*
* @return array
*/
public function getIndexes()
{
return $this->indexes;
}
/**
* Gets an array of foreign keys waiting to be commited.
*
* @param ForeignKey[] $foreignKeys foreign keys
* @return Table
*/
public function setForeignKeys($foreignKeys)
{
$this->foreignKeys = $foreignKeys;
return $this;
}
/**
* Gets an array of foreign keys waiting to be commited.
*
* @return array|ForeignKey[]
*/
public function getForeignKeys()
{
return $this->foreignKeys;
}
/**
* Resets all of the pending table changes.
*
* @return void
*/
public function reset()
{
$this->setPendingColumns(array());
$this->setIndexes(array());
$this->setForeignKeys(array());
}
/**
* Add a table column.
*
* Type can be: primary_key, string, text, integer, float, decimal,
* datetime, timestamp, time, date, binary, boolean.
*
* Valid options can be: limit, default, null, precision or scale.
*
* @param string|Phinx\Db\Table\Column $columnName Column Name
* @param string $type Column Type
* @param array $options Column Options
* @return Table
*/
public function addColumn($columnName, $type = null, $options = array())
{
// we need an adapter set to add a column
if (null === $this->getAdapter()) {
throw new \RuntimeException('An adapter must be specified to add a column.');
}
// create a new column object if only strings were supplied
if (!$columnName instanceof Column) {
$column = new Column();
$column->setName($columnName);
$column->setType($type);
$column->setOptions($options); // map options to column methods
} else {
$column = $columnName;
}
// check column type
if (!in_array($column->getType(), $this->getAdapter()->getColumnTypes())) {
throw new \InvalidArgumentException("An invalid column type was specified: {$column->getName()}");
}
$this->columns[] = $column;
return $this;
}
/**
* Remove a table column.
*
* @param string $columnName Column Name
* @return Table
*/
public function removeColumn($columnName)
{
$this->getAdapter()->dropColumn($this->getName(), $columnName);
return $this;
}
/**
* Rename a table column.
*
* @param string $oldName Old Column Name
* @param string $newName New Column Name
* @return Table
*/
public function renameColumn($oldName, $newName)
{
$this->getAdapter()->renameColumn($this->getName(), $oldName, $newName);
return $this;
}
/**
* Change a table column type.
*
* @param string $columnName Column Name
* @param string|Column $newColumnType New Column Type
* @param array $options Options
* @return Table
*/
public function changeColumn($columnName, $newColumnType, $options = array())
{
// create a column object if one wasn't supplied
if (!$newColumnType instanceof Column) {
$newColumn = new Column();
$newColumn->setType($newColumnType);
$newColumn->setOptions($options);
} else {
$newColumn = $newColumnType;
}
// if the name was omitted use the existing column name
if (null === $newColumn->getName() || strlen($newColumn->getName()) == 0) {
$newColumn->setName($columnName);
}
$this->getAdapter()->changeColumn($this->getName(), $columnName, $newColumn);
return $this;
}
/**
* Checks to see if a column exists.
*
* @param string $columnName Column Name
* @param array $options Options
* @return boolean
*/
public function hasColumn($columnName, $options = array())
{
return $this->getAdapter()->hasColumn($this->getName(), $columnName, $options);
}
/**
* Add an index to a database table.
*
* In $options you can specific unique = true/false or name (index name).
*
* @param string|array|Index $columns Table Column(s)
* @param array $options Index Options
* @return Table
*/
public function addIndex($columns, $options = array())
{
// create a new index object if strings or an array of strings were supplied
if (!$columns instanceof Index) {
$index = new Index();
if (is_string($columns)) {
$columns = array($columns); // str to array
}
$index->setColumns($columns);
$index->setOptions($options);
} else {
$index = $columns;
}
$this->indexes[] = $index;
return $this;
}
/**
* Removes the given index from a table.
*
* @param array $columns Columns
* @param array $options Options
* @return Table
*/
public function removeIndex($columns, $options = array())
{
$this->getAdapter()->dropIndex($this->getName(), $columns, $options);
return $this;
}
/**
* Removes the given index identified by its name from a table.
*
* @param string $name Index name
* @return Table
*/
public function removeIndexByName($name)
{
$this->getAdapter()->dropIndexByName($this->getName(), $name);
return $this;
}
/**
* Checks to see if an index exists.
*
* @param string|array $columns Columns
* @param array $options Options
* @return boolean
*/
public function hasIndex($columns, $options = array())
{
return $this->getAdapter()->hasIndex($this->getName(), $columns, $options);
}
/**
* Add a foreign key to a database table.
*
* In $options you can specify on_delete|on_delete = cascade|no_action ..,
* on_update, constraint = constraint name.
*
* @param string|array $columns Columns
* @param string|Table $referencedTable Referenced Table
* @param string|array $referencedColumns Referenced Columns
* @param array $options Options
* @return Table
*/
public function addForeignKey($columns, $referencedTable, $referencedColumns = array('id'), $options = array())
{
if (is_string($referencedColumns)) {
$referencedColumns = array($referencedColumns); // str to array
}
$fk = new ForeignKey();
if ($referencedTable instanceof Table) {
$fk->setReferencedTable($referencedTable);
} else {
$fk->setReferencedTable(new Table($referencedTable, array(), $this->adapter));
}
$fk->setColumns($columns)
->setReferencedColumns($referencedColumns)
->setOptions($options);
$this->foreignKeys[] = $fk;
return $this;
}
/**
* Removes the given foreign key from the table.
*
* @param string|array $columns Column(s)
* @param null|string $constraint Constraint names
* @return Table
*/
public function dropForeignKey($columns, $constraint = null)
{
if (is_string($columns)) {
$columns = array($columns);
}
if ($constraint) {
$this->getAdapter()->dropForeignKey($this->getName(), array(), $constraint);
} else {
$this->getAdapter()->dropForeignKey($this->getName(), $columns);
}
return $this;
}
/**
* Checks to see if a foreign key exists.
*
* @param string|array $columns Column(s)
* @param null|string $constraint Constraint names
* @return boolean
*/
public function hasForeignKey($columns, $constraint = null)
{
return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
}
/**
* Add timestamp columns created_at and updated_at to the table.
*
* @return Table
*/
public function addTimestamps()
{
$this->addColumn('created_at', 'timestamp')
->addColumn('updated_at', 'timestamp', array(
'null' => true,
'default' => null
));
return $this;
}
/**
* Creates a table from the object instance.
*
* @return void
*/
public function create()
{
$this->getAdapter()->createTable($this);
$this->reset(); // reset pending changes
}
/**
* Updates a table from the object instance.
*
* @return void
*/
public function update()
{
if (!$this->exists()) {
throw new \RuntimeException('Cannot update a table that doesn\'t exist!');
}
// update table
foreach ($this->getPendingColumns() as $column) {
$this->getAdapter()->addColumn($this, $column);
}
foreach ($this->getIndexes() as $index) {
$this->getAdapter()->addIndex($this, $index);
}
foreach ($this->getForeignKeys() as $foreignKey) {
$this->getAdapter()->addForeignKey($this, $foreignKey);
}
$this->reset(); // reset pending changes
}
/**
* Commits the table changes.
*
* If the table doesn't exist it is created otherwise it is updated.
*
* @return void
*/
public function save()
{
if ($this->exists()) {
$this->update(); // update the table
} else {
$this->create(); // create the table
}
$this->reset(); // reset pending changes
}
}
| rsdevigo/phinx | src/Phinx/Db/Table.php | PHP | mit | 15,419 |
<?php
namespace Forge\Log;
/**
* Log_File
* File log writer. Writes out messages and stores them in a YYYY/MM directory.
*
* @package SuperFan
* @category Log
* @author Zach Jenkins <zach@superfanu.com>
* @copyright (c) 2017 SuperFan, Inc.
*/
class File extends Writer
{
// Directory to place log files in
protected $_directory;
// Creates a new file logger. Checks that the directory exists and
// is writable.
public function __construct( $directory )
{
if ( ! is_dir($directory) OR ! is_writable($directory))
{
die('Directory ' . Debug::path( $directory ) . ' must be writable');
}
// Determine the directory path
$this->_directory = realpath($directory).DIRECTORY_SEPARATOR;
}
// Writes each of the messages into the log file. The log file will be
// appended to the `YYYY/MM/DD.log.php` file, where YYYY is the current
// year, MM is the current month, and DD is the current day.
public function write(array $messages)
{
// Set the yearly directory name
$directory = $this->_directory.date('Y');
if ( ! is_dir($directory))
{
// Create the yearly directory
mkdir($directory, 02777);
// Set permissions (must be manually set to fix umask issues)
chmod($directory, 02777);
}
// Add the month to the directory
$directory .= DIRECTORY_SEPARATOR.date('m');
if ( ! is_dir($directory))
{
// Create the monthly directory
mkdir($directory, 02777);
// Set permissions (must be manually set to fix umask issues)
chmod($directory, 02777);
}
// Set the name of the log file
$filename = $directory.DIRECTORY_SEPARATOR.date('d').EXT;
if ( ! file_exists($filename))
{
// Create the log file
file_put_contents($filename, Aviana::FILE_SECURITY.' ?>'.PHP_EOL);
// Allow anyone to write to log files
chmod($filename, 0666);
}
foreach ($messages as $message)
{
// Write each message into the log file
// Format: time --- level: body
file_put_contents($filename, PHP_EOL.$message['time'].' --- '.$this->_log_levels[$message['level']].': '.$message['body'], FILE_APPEND);
}
}
}
| forgephp/core | classes/Log/File.php | PHP | mit | 2,101 |
/*
* unstrap v1.1.3
* https://unstrap.org
* 2015-2020
* MIT license
*/
const version = '1.1.3',
collection = {};
function extendUnstrap (v) {
var list;
if (!collection[v].selectors) {
collection[v].selectors = ['.' + collection[v].name];
}
collection[v].selectors.forEach(function (sel) {
list = document.querySelectorAll(sel);
for (var i = 0; i < list.length; i++) {
collection[v].extend && collection[v].extend(list.item(i));
}
})
}
function init () {
var observer = new MutationObserver(function (mut) {
mut.forEach(function (m) {
var n = m.addedNodes,
f;
for (var i=0; i<n.length; i++) {
var c = n.item(i).classList;
if (c) {
for (var j = 0; j < c.length; j++) {
if (f = collection[c.item(j)]) {
f.extend && f.extend(n.item(i));
}
}
}
}
});
});
Object.keys(collection).forEach(function (v) {
extendUnstrap(v);
})
observer.observe(document.body, {childList: true, subtree: true});
}
function register (...components) {
components.forEach((component) => {
if (component.name) {
collection[component.name] = component;
}
})
}
function unregister (...components) {
components.forEach((component) => {
delete collection[component.name];
})
}
function list () {
return Object.keys(collection).sort();
}
window.onload = init;
export default {
version,
register,
unregister,
list
} | unstrap/unstrap | unstrap.js | JavaScript | mit | 1,620 |
<?php
/* PgGsbFraisBundle::accueilCompta.html.twig */
class __TwigTemplate_6194dcf338f5cd969f229bda597abec8b69c1f8371639ebcadc7c86b484b4c01 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("PgGsbFraisBundle::layout.html.twig");
$this->blocks = array(
'body' => array($this, 'block_body'),
'section' => array($this, 'block_section'),
);
}
protected function doGetParent(array $context)
{
return "PgGsbFraisBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 2
public function block_body($context, array $blocks = array())
{
// line 3
echo "<nav>
<div class=\"row\">
<div class=\"col-lg-10\">
<nav class=\"navbar navbar-default\" role=\"navigation\">
<div class=\"container-fluid\">
<div class=\"navbar-header\">
<a class=\"navbar-brand\" href=\"";
// line 9
echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_home");
echo "\">Accueil</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\">
<ul class=\"nav navbar-nav\">
<li>
<a href=\"";
// line 15
echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_suivrefrais");
echo "\" title=\"Suivre fiche de frais \">Suivre fiche de frais</a>
</li>
<li>
<a href= \"";
// line 19
echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_validerfrais");
echo "\" title=\"Valider fiches de frais\">Valider fiches de frais</a>
</li>
</ul>
</div>
</nav>
</div>
<div class=\"col-lg-2\">
<nav class=\"navbar navbar-default\" role=\"deconnexion\">
<div class=\"container-fluid\">
";
// line 29
if ($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "session", array(), "any", false, true), "get", array(0 => "nom"), "method", true, true)) {
// line 30
echo " Bonjour ";
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session"), "get", array(0 => "nom"), "method"), "html", null, true);
echo " <br />
";
}
// line 32
echo " <a href=\"";
echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_deconnexion");
echo "\" title=\"Se déconnecter\">Déconnexion</a>
</div>
</nav>
</div>
</div>
</nav>
<section>
";
// line 39
$this->displayBlock('section', $context, $blocks);
// line 41
echo "</section>
";
}
// line 39
public function block_section($context, array $blocks = array())
{
// line 40
echo " ";
}
public function getTemplateName()
{
return "PgGsbFraisBundle::accueilCompta.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 98 => 40, 95 => 39, 90 => 41, 88 => 39, 77 => 32, 71 => 30, 69 => 29, 56 => 19, 49 => 15, 40 => 9, 32 => 3, 29 => 2, 31 => 3, 28 => 2,);
}
}
| FCalligaris/GSB | app/cache/dev/twig/61/94/dcf338f5cd969f229bda597abec8b69c1f8371639ebcadc7c86b484b4c01.php | PHP | mit | 4,000 |
'use strict';
const toBytes = s => [...s].map(c => c.charCodeAt(0));
const xpiZipFilename = toBytes('META-INF/mozilla.rsa');
const oxmlContentTypes = toBytes('[Content_Types].xml');
const oxmlRels = toBytes('_rels/.rels');
const fileType = input => {
const buf = input instanceof Uint8Array ? input : new Uint8Array(input);
if (!(buf && buf.length > 1)) {
return null;
}
const check = (header, options) => {
options = Object.assign({
offset: 0
}, options);
for (let i = 0; i < header.length; i++) {
// If a bitmask is set
if (options.mask) {
// If header doesn't equal `buf` with bits masked off
if (header[i] !== (options.mask[i] & buf[i + options.offset])) {
return false;
}
} else if (header[i] !== buf[i + options.offset]) {
return false;
}
}
return true;
};
const checkString = (header, options) => check(toBytes(header), options);
if (check([0xFF, 0xD8, 0xFF])) {
return {
ext: 'jpg',
mime: 'image/jpeg'
};
}
if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
return {
ext: 'png',
mime: 'image/png'
};
}
if (check([0x47, 0x49, 0x46])) {
return {
ext: 'gif',
mime: 'image/gif'
};
}
if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) {
return {
ext: 'webp',
mime: 'image/webp'
};
}
if (check([0x46, 0x4C, 0x49, 0x46])) {
return {
ext: 'flif',
mime: 'image/flif'
};
}
// Needs to be before `tif` check
if (
(check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) &&
check([0x43, 0x52], {offset: 8})
) {
return {
ext: 'cr2',
mime: 'image/x-canon-cr2'
};
}
if (
check([0x49, 0x49, 0x2A, 0x0]) ||
check([0x4D, 0x4D, 0x0, 0x2A])
) {
return {
ext: 'tif',
mime: 'image/tiff'
};
}
if (check([0x42, 0x4D])) {
return {
ext: 'bmp',
mime: 'image/bmp'
};
}
if (check([0x49, 0x49, 0xBC])) {
return {
ext: 'jxr',
mime: 'image/vnd.ms-photo'
};
}
if (check([0x38, 0x42, 0x50, 0x53])) {
return {
ext: 'psd',
mime: 'image/vnd.adobe.photoshop'
};
}
// Zip-based file formats
// Need to be before the `zip` check
if (check([0x50, 0x4B, 0x3, 0x4])) {
if (
check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30})
) {
return {
ext: 'epub',
mime: 'application/epub+zip'
};
}
// Assumes signed `.xpi` from addons.mozilla.org
if (check(xpiZipFilename, {offset: 30})) {
return {
ext: 'xpi',
mime: 'application/x-xpinstall'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) {
return {
ext: 'odt',
mime: 'application/vnd.oasis.opendocument.text'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) {
return {
ext: 'ods',
mime: 'application/vnd.oasis.opendocument.spreadsheet'
};
}
if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) {
return {
ext: 'odp',
mime: 'application/vnd.oasis.opendocument.presentation'
};
}
// https://github.com/file/file/blob/master/magic/Magdir/msooxml
if (check(oxmlContentTypes, {offset: 30}) || check(oxmlRels, {offset: 30})) {
const sliced = buf.subarray(4, 4 + 2000);
const nextZipHeaderIndex = arr => arr.findIndex((el, i, arr) => arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4);
const header2Pos = nextZipHeaderIndex(sliced);
if (header2Pos !== -1) {
const slicedAgain = buf.subarray(header2Pos + 8, header2Pos + 8 + 1000);
const header3Pos = nextZipHeaderIndex(slicedAgain);
if (header3Pos !== -1) {
const offset = 8 + header2Pos + header3Pos + 30;
if (checkString('word/', {offset})) {
return {
ext: 'docx',
mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
};
}
if (checkString('ppt/', {offset})) {
return {
ext: 'pptx',
mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
};
}
if (checkString('xl/', {offset})) {
return {
ext: 'xlsx',
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
};
}
}
}
}
}
if (
check([0x50, 0x4B]) &&
(buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) &&
(buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)
) {
return {
ext: 'zip',
mime: 'application/zip'
};
}
if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) {
return {
ext: 'tar',
mime: 'application/x-tar'
};
}
if (
check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) &&
(buf[6] === 0x0 || buf[6] === 0x1)
) {
return {
ext: 'rar',
mime: 'application/x-rar-compressed'
};
}
if (check([0x1F, 0x8B, 0x8])) {
return {
ext: 'gz',
mime: 'application/gzip'
};
}
if (check([0x42, 0x5A, 0x68])) {
return {
ext: 'bz2',
mime: 'application/x-bzip2'
};
}
if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {
return {
ext: '7z',
mime: 'application/x-7z-compressed'
};
}
if (check([0x78, 0x01])) {
return {
ext: 'dmg',
mime: 'application/x-apple-diskimage'
};
}
if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5
(
check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) &&
(
check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41
check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42
check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM
check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2
check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4
check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V
check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH
)
)) {
return {
ext: 'mp4',
mime: 'video/mp4'
};
}
if (check([0x4D, 0x54, 0x68, 0x64])) {
return {
ext: 'mid',
mime: 'audio/midi'
};
}
// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska
if (check([0x1A, 0x45, 0xDF, 0xA3])) {
const sliced = buf.subarray(4, 4 + 4096);
const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);
if (idPos !== -1) {
const docTypePos = idPos + 3;
const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));
if (findDocType('matroska')) {
return {
ext: 'mkv',
mime: 'video/x-matroska'
};
}
if (findDocType('webm')) {
return {
ext: 'webm',
mime: 'video/webm'
};
}
}
}
if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) ||
check([0x66, 0x72, 0x65, 0x65], {offset: 4}) ||
check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) ||
check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG
check([0x77, 0x69, 0x64, 0x65], {offset: 4})) {
return {
ext: 'mov',
mime: 'video/quicktime'
};
}
// RIFF file format which might be AVI, WAV, QCP, etc
if (check([0x52, 0x49, 0x46, 0x46])) {
if (check([0x41, 0x56, 0x49], {offset: 8})) {
return {
ext: 'avi',
mime: 'video/x-msvideo'
};
}
if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {
return {
ext: 'wav',
mime: 'audio/x-wav'
};
}
// QLCM, QCP file
if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {
return {
ext: 'qcp',
mime: 'audio/qcelp'
};
}
}
if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {
return {
ext: 'wmv',
mime: 'video/x-ms-wmv'
};
}
if (
check([0x0, 0x0, 0x1, 0xBA]) ||
check([0x0, 0x0, 0x1, 0xB3])
) {
return {
ext: 'mpg',
mime: 'video/mpeg'
};
}
if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) {
return {
ext: '3gp',
mime: 'video/3gpp'
};
}
// Check for MPEG header at different starting offsets
for (let start = 0; start < 2 && start < (buf.length - 16); start++) {
if (
check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header
check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header
) {
return {
ext: 'mp3',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header
) {
return {
ext: 'mp2',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS
) {
return {
ext: 'mp2',
mime: 'audio/mpeg'
};
}
if (
check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS
) {
return {
ext: 'mp4',
mime: 'audio/mpeg'
};
}
}
if (
check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) ||
check([0x4D, 0x34, 0x41, 0x20])
) {
return {
ext: 'm4a',
mime: 'audio/m4a'
};
}
// Needs to be before `ogg` check
if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) {
return {
ext: 'opus',
mime: 'audio/opus'
};
}
// If 'OggS' in first bytes, then OGG container
if (check([0x4F, 0x67, 0x67, 0x53])) {
// This is a OGG container
// If ' theora' in header.
if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) {
return {
ext: 'ogv',
mime: 'video/ogg'
};
}
// If '\x01video' in header.
if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) {
return {
ext: 'ogm',
mime: 'video/ogg'
};
}
// If ' FLAC' in header https://xiph.org/flac/faq.html
if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) {
return {
ext: 'oga',
mime: 'audio/ogg'
};
}
// 'Speex ' in header https://en.wikipedia.org/wiki/Speex
if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) {
return {
ext: 'spx',
mime: 'audio/ogg'
};
}
// If '\x01vorbis' in header
if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) {
return {
ext: 'ogg',
mime: 'audio/ogg'
};
}
// Default OGG container https://www.iana.org/assignments/media-types/application/ogg
return {
ext: 'ogx',
mime: 'application/ogg'
};
}
if (check([0x66, 0x4C, 0x61, 0x43])) {
return {
ext: 'flac',
mime: 'audio/x-flac'
};
}
if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {
return {
ext: 'amr',
mime: 'audio/amr'
};
}
if (check([0x25, 0x50, 0x44, 0x46])) {
return {
ext: 'pdf',
mime: 'application/pdf'
};
}
if (check([0x4D, 0x5A])) {
return {
ext: 'exe',
mime: 'application/x-msdownload'
};
}
if (
(buf[0] === 0x43 || buf[0] === 0x46) &&
check([0x57, 0x53], {offset: 1})
) {
return {
ext: 'swf',
mime: 'application/x-shockwave-flash'
};
}
if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {
return {
ext: 'rtf',
mime: 'application/rtf'
};
}
if (check([0x00, 0x61, 0x73, 0x6D])) {
return {
ext: 'wasm',
mime: 'application/wasm'
};
}
if (
check([0x77, 0x4F, 0x46, 0x46]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff',
mime: 'font/woff'
};
}
if (
check([0x77, 0x4F, 0x46, 0x32]) &&
(
check([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||
check([0x4F, 0x54, 0x54, 0x4F], {offset: 4})
)
) {
return {
ext: 'woff2',
mime: 'font/woff2'
};
}
if (
check([0x4C, 0x50], {offset: 34}) &&
(
check([0x00, 0x00, 0x01], {offset: 8}) ||
check([0x01, 0x00, 0x02], {offset: 8}) ||
check([0x02, 0x00, 0x02], {offset: 8})
)
) {
return {
ext: 'eot',
mime: 'application/octet-stream'
};
}
if (check([0x00, 0x01, 0x00, 0x00, 0x00])) {
return {
ext: 'ttf',
mime: 'font/ttf'
};
}
if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {
return {
ext: 'otf',
mime: 'font/otf'
};
}
if (check([0x00, 0x00, 0x01, 0x00])) {
return {
ext: 'ico',
mime: 'image/x-icon'
};
}
if (check([0x00, 0x00, 0x02, 0x00])) {
return {
ext: 'cur',
mime: 'image/x-icon'
};
}
if (check([0x46, 0x4C, 0x56, 0x01])) {
return {
ext: 'flv',
mime: 'video/x-flv'
};
}
if (check([0x25, 0x21])) {
return {
ext: 'ps',
mime: 'application/postscript'
};
}
if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {
return {
ext: 'xz',
mime: 'application/x-xz'
};
}
if (check([0x53, 0x51, 0x4C, 0x69])) {
return {
ext: 'sqlite',
mime: 'application/x-sqlite3'
};
}
if (check([0x4E, 0x45, 0x53, 0x1A])) {
return {
ext: 'nes',
mime: 'application/x-nintendo-nes-rom'
};
}
if (check([0x43, 0x72, 0x32, 0x34])) {
return {
ext: 'crx',
mime: 'application/x-google-chrome-extension'
};
}
if (
check([0x4D, 0x53, 0x43, 0x46]) ||
check([0x49, 0x53, 0x63, 0x28])
) {
return {
ext: 'cab',
mime: 'application/vnd.ms-cab-compressed'
};
}
// Needs to be before `ar` check
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {
return {
ext: 'deb',
mime: 'application/x-deb'
};
}
if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {
return {
ext: 'ar',
mime: 'application/x-unix-archive'
};
}
if (check([0xED, 0xAB, 0xEE, 0xDB])) {
return {
ext: 'rpm',
mime: 'application/x-rpm'
};
}
if (
check([0x1F, 0xA0]) ||
check([0x1F, 0x9D])
) {
return {
ext: 'Z',
mime: 'application/x-compress'
};
}
if (check([0x4C, 0x5A, 0x49, 0x50])) {
return {
ext: 'lz',
mime: 'application/x-lzip'
};
}
if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {
return {
ext: 'msi',
mime: 'application/x-msi'
};
}
if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {
return {
ext: 'mxf',
mime: 'application/mxf'
};
}
if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) {
return {
ext: 'mts',
mime: 'video/mp2t'
};
}
if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {
return {
ext: 'blend',
mime: 'application/x-blender'
};
}
if (check([0x42, 0x50, 0x47, 0xFB])) {
return {
ext: 'bpg',
mime: 'image/bpg'
};
}
if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {
// JPEG-2000 family
if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) {
return {
ext: 'jp2',
mime: 'image/jp2'
};
}
if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) {
return {
ext: 'jpx',
mime: 'image/jpx'
};
}
if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) {
return {
ext: 'jpm',
mime: 'image/jpm'
};
}
if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) {
return {
ext: 'mj2',
mime: 'image/mj2'
};
}
}
if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) {
return {
ext: 'aif',
mime: 'audio/aiff'
};
}
if (checkString('<?xml ')) {
return {
ext: 'xml',
mime: 'application/xml'
};
}
if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) {
return {
ext: 'mobi',
mime: 'application/x-mobipocket-ebook'
};
}
// File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format)
if (check([0x66, 0x74, 0x79, 0x70], {offset: 4})) {
if (check([0x6D, 0x69, 0x66, 0x31], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heif'
};
}
if (check([0x6D, 0x73, 0x66, 0x31], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heif-sequence'
};
}
if (check([0x68, 0x65, 0x69, 0x63], {offset: 8}) || check([0x68, 0x65, 0x69, 0x78], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heic'
};
}
if (check([0x68, 0x65, 0x76, 0x63], {offset: 8}) || check([0x68, 0x65, 0x76, 0x78], {offset: 8})) {
return {
ext: 'heic',
mime: 'image/heic-sequence'
};
}
}
return null;
};
| jmhmd/dat-lambda | client/lib/file-type.js | JavaScript | mit | 15,936 |
import logging
from abc import ABCMeta, abstractmethod
from collections import deque
from typing import List, Union, Iterable, Sequence
log = logging.getLogger(__name__)
class NoSensorsFoundException(RuntimeError):
pass
class Controller(metaclass=ABCMeta):
@abstractmethod
def run(self):
raise NotImplementedError
@abstractmethod
def enable(self):
raise NotImplementedError
@abstractmethod
def disable(self):
raise NotImplementedError
@abstractmethod
def valid(self) -> bool:
raise NotImplementedError
class InputDevice(metaclass=ABCMeta):
"""
Abstract class for input devices.
"""
def __init__(self, name):
self.name = name
self.values = ValueBuffer(name, 128)
@abstractmethod
def get_value(self) -> float:
raise NotImplementedError
class OutputDevice(metaclass=ABCMeta):
"""
Abstract class for output devices.
"""
def __init__(self, name):
self.name = name
self.values = ValueBuffer(name, 128)
def set_value(self, value: Union[int, float]):
self.values.update(value)
@abstractmethod
def apply(self):
raise NotImplementedError
@abstractmethod
def enable(self):
raise NotImplementedError
@abstractmethod
def disable(self):
raise NotImplementedError
class PassthroughController(Controller):
def __init__(self, inputs=Sequence[InputDevice], outputs=Sequence[OutputDevice], speeds=None):
self.inputs = list(inputs)
self.outputs = list(outputs)
def run(self):
for idx, input_reader in enumerate(self.inputs):
output = self.outputs[idx]
output.name = input_reader.name
output.values.name = input_reader.name
output.set_value(input_reader.get_value())
output.apply()
log.debug('ran loop')
def apply_candidates(self):
return self.outputs
def enable(self):
for output_dev in self.outputs:
output_dev.enable()
def disable(self):
for output_dev in self.outputs:
output_dev.disable()
def valid(self) -> bool:
return bool(self.inputs and self.outputs) and len(self.inputs) == len(self.outputs)
class DummyInput(InputDevice):
def __init__(self):
super().__init__('dummy')
self.temp = 0
def get_value(self):
return self.temp
def set_value(self, value):
self.temp = value
class DummyOutput(OutputDevice):
def __init__(self):
super().__init__('dummy')
self.speed = None
self.enabled = False
def apply(self):
if self.enabled:
self.speed = round(self.values.mean())
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def mean(seq: Iterable) -> float:
if not isinstance(seq, Iterable):
raise ValueError('provided sequence MUST be iterable')
if not isinstance(seq, Sequence):
seq = list(seq)
if len(seq) == 1:
return float(seq[0])
if len(seq) == 0:
raise ValueError('sequence must have at least one value.')
return sum(seq) / len(seq)
def lerp(value: Union[float, int], input_min: Union[float, int], input_max: Union[float, int], output_min: Union[float, int], output_max: Union[float, int]) -> float:
if value <= input_min:
return float(output_min)
if value >= input_max:
return float(output_max)
return (output_min * (input_max - value) + output_max * (value - input_min)) / (input_max - input_min)
def lerp_range(seq: Iterable[Union[float, int]], input_min, input_max, output_min, output_max) -> List[float]:
return [lerp(val, input_min, input_max, output_min, output_max) for val in seq]
class ValueBuffer:
def __init__(self, name, default_value=0.0):
self.name = name
self.buffer = deque(maxlen=32)
self._default_value = default_value
def update(self, value: float):
self.buffer.append(value)
def mean(self) -> float:
try:
return mean(self.buffer)
except (ValueError, ZeroDivisionError):
return self._default_value
| vrga/pyFanController | pyfc/common.py | Python | mit | 4,243 |
// PS4Macro (File: Forms/MainForm.cs)
//
// Copyright (c) 2018 Komefai
//
// Visit http://komefai.com for more information
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using PS4Macro.Classes;
using PS4Macro.Classes.GlobalHooks;
using PS4Macro.Classes.Remapping;
using PS4RemotePlayInterceptor;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PS4Macro.Forms
{
enum ControlMode
{
Macro,
Script,
Remapper,
StatusChecker
}
public partial class MainForm : Form
{
private const string CURRENT_TICK_DEFAULT_TEXT = "-";
private GlobalKeyboardHook m_GlobalKeyboardHook;
private GlobalMouseHook m_GlobalMouseHook;
private MacroPlayer m_MacroPlayer;
private Remapper m_Remapper;
private StatusChecker m_StatusChecker;
private ControlMode m_ControlMode;
private PS4MacroAPI.ScriptBase m_SelectedScript;
private ScriptHost m_ScriptHost;
private SaveLoadHelper m_SaveLoadHelper;
private Process m_RemotePlayProcess;
/* Constructor */
public MainForm()
{
InitializeComponent();
// Setup global keyboard hook
m_GlobalKeyboardHook = new GlobalKeyboardHook();
m_GlobalKeyboardHook.KeyboardPressed += OnKeyPressed;
// Setup global mouse hook
m_GlobalMouseHook = new GlobalMouseHook();
m_GlobalMouseHook.MouseEvent += OnMouseEvent;
// Create macro player
m_MacroPlayer = new MacroPlayer();
m_MacroPlayer.Loop = true;
m_MacroPlayer.RecordShortcut = true;
m_MacroPlayer.PropertyChanged += MacroPlayer_PropertyChanged;
// Create remapper
m_Remapper = new Remapper();
// Create status checker
m_StatusChecker = new StatusChecker();
// Set control mode
SetControlMode(ControlMode.Macro);
// Create save/load helper
m_SaveLoadHelper = new SaveLoadHelper(this, m_MacroPlayer);
m_SaveLoadHelper.PropertyChanged += SaveLoadHelper_PropertyChanged;
// Initialize interceptor
InitInterceptor();
}
private void InitInterceptor()
{
// Set controller emulation based on settings
Interceptor.EmulateController = Program.Settings.EmulateController;
emulatedToolStripStatusLabel.Visible = Program.Settings.EmulateController;
// Enable watchdog based on settings
if (!Program.Settings.AutoInject)
{
Interceptor.InjectionMode = InjectionMode.Compatibility;
}
// Inject if not bypassed
if (!Program.Settings.BypassInjection)
{
// Attempt to inject into PS4 Remote Play
try
{
int pid = Interceptor.Inject();
m_RemotePlayProcess = Process.GetProcessById(pid);
// Set process
ForwardRemotePlayProcess();
}
// Injection failed
catch (InterceptorException ex)
{
// Only handle when PS4 Remote Play is in used by another injection
if (ex.InnerException != null && ex.InnerException.Message.Equals("STATUS_INTERNAL_ERROR: Unknown error in injected C++ completion routine. (Code: 15)"))
{
MessageBox.Show("The process has been injected by another executable. Restart PS4 Remote Play and try again.", "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
else
{
// Handle exception if watchdog is disabled
if (!Program.Settings.AutoInject)
{
MessageBox.Show(string.Format("[{0}] - {1}", ex.GetType(), ex.Message), "Injection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
Environment.Exit(-1);
}
}
}
// Start watchdog to automatically inject when possible
if (Program.Settings.AutoInject)
{
Interceptor.Watchdog.Start();
// Watchdog callbacks
Interceptor.Watchdog.OnInjectionSuccess = () =>
{
ForwardRemotePlayProcess();
};
Interceptor.Watchdog.OnInjectionFailure = () =>
{
};
}
}
}
private void SetControlMode(ControlMode controlMode)
{
m_ControlMode = controlMode;
if (m_ControlMode == ControlMode.Macro)
{
// Stop script and remove
if (m_ScriptHost != null && m_ScriptHost.IsRunning)
{
m_ScriptHost.Stop();
m_ScriptHost = null;
}
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_MacroPlayer.OnReceiveData);
recordButton.Enabled = true;
recordToolStripMenuItem.Enabled = true;
loopCheckBox.Enabled = true;
loopCheckBox.Checked = m_MacroPlayer.Loop;
loopToolStripMenuItem.Enabled = true;
recordOnTouchToolStripMenuItem.Enabled = true;
scriptButton.Enabled = false;
saveToolStripMenuItem.Enabled = true;
saveAsToolStripMenuItem.Enabled = true;
clearMacroToolStripMenuItem.Enabled = true;
trimMacroToolStripMenuItem.Enabled = true;
}
else if (m_ControlMode == ControlMode.Script)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_ScriptHost.OnReceiveData);
recordButton.Enabled = false;
recordToolStripMenuItem.Enabled = false;
loopCheckBox.Enabled = false;
loopCheckBox.Checked = false;
loopToolStripMenuItem.Enabled = false;
recordOnTouchToolStripMenuItem.Enabled = false;
scriptButton.Enabled = true;
saveToolStripMenuItem.Enabled = false;
saveAsToolStripMenuItem.Enabled = false;
clearMacroToolStripMenuItem.Enabled = false;
trimMacroToolStripMenuItem.Enabled = false;
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
else if (m_ControlMode == ControlMode.Remapper)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_Remapper.OnReceiveData);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
// Stop macro player
if (m_MacroPlayer.IsRecording) m_MacroPlayer.Record();
m_MacroPlayer.Stop();
// Stop script
if (m_ScriptHost != null && m_ScriptHost.IsRunning) m_ScriptHost.Stop();
// Setup callback to interceptor
Interceptor.Callback = new InterceptionDelegate(m_StatusChecker.OnReceiveData);
}
}
private void TemporarilySetControlMode(ControlMode controlMode, Action action)
{
// Store current control mode and temporarily set it
ControlMode oldControlMode = m_ControlMode;
SetControlMode(controlMode);
// Invoke action
action?.Invoke();
// Restore control mode
SetControlMode(oldControlMode);
}
private void ForwardRemotePlayProcess()
{
m_Remapper.RemotePlayProcess = m_RemotePlayProcess;
m_StatusChecker.RemotePlayProcess = m_RemotePlayProcess;
}
public void LoadMacro(string path)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.LoadFile(path);
}
public void LoadScript(string path)
{
var script = PS4MacroAPI.Internal.ScriptUtility.LoadScript(path);
m_SelectedScript = script;
m_ScriptHost = new ScriptHost(this, m_SelectedScript);
m_ScriptHost.PropertyChanged += ScriptHost_PropertyChanged;
SetControlMode(ControlMode.Script);
}
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnKeyPressed(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnKeyPressed(sender, e);
}
}
private void OnMouseEvent(object sender, GlobalMouseHookEventArgs e)
{
if (m_ControlMode == ControlMode.Remapper)
{
m_Remapper.OnMouseEvent(sender, e);
}
else if (m_ControlMode == ControlMode.StatusChecker)
{
m_StatusChecker.OnMouseEvent(sender, e);
}
}
private void MainForm_Load(object sender, EventArgs e)
{
// Load startup file
if (!string.IsNullOrWhiteSpace(Program.Settings.StartupFile))
m_SaveLoadHelper.DirectLoad(Program.Settings.StartupFile);
}
/* Macro Player */
#region MacroPlayer_PropertyChanged
private void UpdateCurrentTick()
{
BeginInvoke((MethodInvoker)delegate
{
// Invalid sequence
if (m_MacroPlayer.Sequence == null || m_MacroPlayer.Sequence.Count <= 0)
{
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
// Valid sequence
else
{
currentTickToolStripStatusLabel.Text = string.Format("{0}/{1}",
m_MacroPlayer.CurrentTick.ToString(),
m_MacroPlayer.Sequence.Count.ToString()
);
}
});
}
private void MacroPlayer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsPlaying":
{
playButton.ForeColor = m_MacroPlayer.IsPlaying ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
playButton.ForeColor = m_MacroPlayer.IsPaused ? DefaultForeColor : playButton.ForeColor;
break;
}
case "IsRecording":
{
recordButton.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
currentTickToolStripStatusLabel.ForeColor = m_MacroPlayer.IsRecording ? Color.Red : DefaultForeColor;
break;
}
case "CurrentTick":
{
UpdateCurrentTick();
break;
}
case "Sequence":
{
UpdateCurrentTick();
break;
}
case "Loop":
{
loopCheckBox.Checked = m_MacroPlayer.Loop;
loopToolStripMenuItem.Checked = m_MacroPlayer.Loop;
break;
}
case "RecordShortcut":
{
recordOnTouchToolStripMenuItem.Checked = m_MacroPlayer.RecordShortcut;
break;
}
}
}
#endregion
/* Script Host */
#region ScriptHost_PropertyChanged
private void ScriptHost_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsRunning":
{
playButton.ForeColor = m_ScriptHost.IsRunning ? Color.Green : DefaultForeColor;
break;
}
case "IsPaused":
{
if (m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = DefaultForeColor;
}
else if (!m_ScriptHost.IsPaused && m_ScriptHost.IsRunning)
{
playButton.ForeColor = Color.Green;
}
break;
}
}
}
#endregion
/* Save/Load Helper */
#region SaveLoadHelper_PropertyChanged
private void SaveLoadHelper_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentFile")
{
if (m_SaveLoadHelper.CurrentFile == null)
{
fileNameToolStripStatusLabel.Text = SaveLoadHelper.DEFAULT_FILE_NAME;
currentTickToolStripStatusLabel.Text = CURRENT_TICK_DEFAULT_TEXT;
}
else
{
fileNameToolStripStatusLabel.Text = System.IO.Path.GetFileName(m_SaveLoadHelper.CurrentFile);
}
}
}
#endregion
/* Playback buttons methods */
#region Playback Buttons
private void playButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Play();
}
}
private void pauseButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Pause();
}
}
private void stopButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
else if (m_ControlMode == ControlMode.Script)
{
m_ScriptHost.Stop();
}
}
private void recordButton_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void loopCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = loopCheckBox.Checked;
}
}
#endregion
/* Script buttons methods */
#region Script Buttons
private void scriptButton_Click(object sender, EventArgs e)
{
m_ScriptHost.ShowForm(this);
}
#endregion
/* Menu strip methods */
#region Menu Strip
#region File
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
SetControlMode(ControlMode.Macro);
m_MacroPlayer.Clear();
m_SaveLoadHelper.ClearCurrentFile();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.Load();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.Save();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
m_SaveLoadHelper.SaveAs();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Edit
private void clearMacroToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Clear();
}
}
private void trimMacroToolStripMenuItem_Click(object sender, EventArgs e)
{
m_MacroPlayer.Stop();
var oldSequenceLength = m_MacroPlayer.Sequence.Count;
m_MacroPlayer.Sequence = MacroUtility.TrimMacro(m_MacroPlayer.Sequence);
// Show results
var difference = oldSequenceLength - m_MacroPlayer.Sequence.Count;
MessageBox.Show(
$"{difference} frames removed" + "\n\n" +
$"Before: {oldSequenceLength} frames" + "\n" +
$"After: {m_MacroPlayer.Sequence.Count} frames", "Trim Macro",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region Playback
private void playToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Play();
}
}
private void pauseToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Pause();
}
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Stop();
}
}
private void recordToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Record();
}
}
private void loopToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.Loop = !loopToolStripMenuItem.Checked;
}
}
private void recordOnTouchToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_ControlMode == ControlMode.Macro)
{
m_MacroPlayer.RecordShortcut = !recordOnTouchToolStripMenuItem.Checked;
}
}
#endregion
#region Tools
private void screenshotToolStripMenuItem_Click(object sender, EventArgs e)
{
var backgroundMode = !(ModifierKeys == Keys.Shift);
var frame = PS4MacroAPI.Internal.ScriptUtility.CaptureFrame(backgroundMode);
var folder = "screenshots";
// Create folder if not exist
Directory.CreateDirectory(folder);
if (frame != null)
{
var fileName = folder + @"\" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
frame.Save(fileName);
Console.WriteLine($"{DateTime.Now.ToString()} - Screenshot saved to {Path.GetFullPath(fileName)}");
}
else
{
MessageBox.Show("Unable to capture screenshot!");
}
}
private void imageHashToolToolStripMenuItem_Click(object sender, EventArgs e)
{
new ImageHashForm().Show(this);
}
private void resizeRemotePlayToolStripMenuItem_Click(object sender, EventArgs e)
{
new ResizeRemotePlayForm().ShowDialog(this);
}
private void macroCompressorToolStripMenuItem_Click(object sender, EventArgs e)
{
new MacroCompressorForm().ShowDialog(this);
}
private void remapperToolStripMenuItem_Click(object sender, EventArgs e)
{
TemporarilySetControlMode(ControlMode.Remapper, () =>
{
new RemapperForm(m_Remapper).ShowDialog(this);
});
}
#endregion
#region Help
private void statusCheckerToolStripMenuItem_Click(object sender, EventArgs e)
{
TemporarilySetControlMode(ControlMode.StatusChecker, () =>
{
m_StatusChecker.SetActive(true);
new StatusCheckerForm(m_StatusChecker).ShowDialog(this);
m_StatusChecker.SetActive(false);
});
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
var aboutForm = new AboutForm();
aboutForm.ShowDialog(this);
}
#endregion
#endregion
/* Status strip methods */
#region Status Strip
#endregion
}
}
| komefai/PS4Macro | PS4Macro/Forms/MainForm.cs | C# | mit | 23,676 |
let fs = require("fs");
let path = require("path");
let cp = require("child_process");
function runCommand(folder, args) {
cp.spawn("npm", args, { env: process.env, cwd: folder, stdio: "inherit" });
}
function getPackages(category) {
let folder = path.join(__dirname, category);
return fs
.readdirSync(folder)
.map(function(dir) {
let fullPath = path.join(folder, dir);
// check for a package.json file
if (!fs.existsSync(path.join(fullPath, "package.json"))) {
return;
}
return fullPath;
})
.filter(function(pkg) {
return pkg !== undefined;
});
}
function runCommandInCategory(category, args) {
let pkgs = getPackages(category);
pkgs.forEach(function(pkg) {
runCommand(pkg, args);
});
}
let CATEGORIES = ["react", "vue", "svelte", "misc"];
let category = process.argv[2];
let args = process.argv.slice(3);
if (category === "all") {
CATEGORIES.forEach(function(c) {
runCommandInCategory(c, args);
});
} else {
runCommandInCategory(category, args);
}
| pshrmn/curi | examples/updateCategory.js | JavaScript | mit | 1,046 |
// download the contents of a url
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
)
func main() {
res, err := http.Get("http://www.google.com/robots.txt")
if err != nil {
log.Fatal(err)
}
robots, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s", robots)
}
| andrew/go-experiments | get.go | GO | mit | 333 |