file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
dom_adapter.js
/** * @license * Copyright Google Inc. 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 { isBlank } from '../facade/lang'; var _DOM = null; export function getDOM() { return _DOM; } export function setDOM(adapter) { _DOM = adapter; } export function setRootDomAdapter(adapter) { if (isBlank(_DOM)) { _DOM = adapter; } } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ export class DomAdapter { constructor() { this.xhrType = null; } /** @deprecated */ getXHR() { return this.xhrType; } /** * Maps attribute names to their corresponding property names for cases * where attribute name doesn't match property name. */ get attrToPropMap() { return this._attrToPropMap; } ; set
(value) { this._attrToPropMap = value; } ; } //# sourceMappingURL=dom_adapter.js.map
attrToPropMap
identifier_name
dom_adapter.js
/** * @license * Copyright Google Inc. 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 { isBlank } from '../facade/lang'; var _DOM = null; export function getDOM() { return _DOM; } export function setDOM(adapter) { _DOM = adapter; } export function setRootDomAdapter(adapter) { if (isBlank(_DOM))
} /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ export class DomAdapter { constructor() { this.xhrType = null; } /** @deprecated */ getXHR() { return this.xhrType; } /** * Maps attribute names to their corresponding property names for cases * where attribute name doesn't match property name. */ get attrToPropMap() { return this._attrToPropMap; } ; set attrToPropMap(value) { this._attrToPropMap = value; } ; } //# sourceMappingURL=dom_adapter.js.map
{ _DOM = adapter; }
conditional_block
dom_adapter.js
/** * @license * Copyright Google Inc. 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 { isBlank } from '../facade/lang'; var _DOM = null; export function getDOM() { return _DOM; } export function setDOM(adapter) { _DOM = adapter;
} } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. */ export class DomAdapter { constructor() { this.xhrType = null; } /** @deprecated */ getXHR() { return this.xhrType; } /** * Maps attribute names to their corresponding property names for cases * where attribute name doesn't match property name. */ get attrToPropMap() { return this._attrToPropMap; } ; set attrToPropMap(value) { this._attrToPropMap = value; } ; } //# sourceMappingURL=dom_adapter.js.map
} export function setRootDomAdapter(adapter) { if (isBlank(_DOM)) { _DOM = adapter;
random_line_split
MasonryLayout.tsx
import React from 'react'; interface IElementProps { component: string | JSX.Element; size: number; } interface IMasonryLayoutProps { elements: IElementProps[]; numPerRow: number; minWidth?: number; gutter?: number; customizeStyle?: React.CSSProperties; totalWidth?: number; } const MasonryLayout = ({ customizeStyle = {}, // Replace it with your own style elements, gutter = 0.7, // percentage minWidth = 354, // px numPerRow = 3, totalWidth = 100, // percentage }: IMasonryLayoutProps) => { const width = (totalWidth - numPerRow * gutter) / numPerRow; return ( <ul className="masonry" > {elements.map((element: IElementProps, i: number) => { return ( <li className="masonry-brick" key={`element${i}`} style={{ flex: `${element.size} ${0} ${element.size * minWidth}px`, minWidth: `${element.size * width + (element.size - 1) * gutter}%`, ...customizeStyle, }} > {element.component} </li>
); }; export default MasonryLayout;
); })} </ul>
random_line_split
gamelib.js
/** * Game class library, utility functions and globals. * * (C) 2010 Kevin Roast kevtoast@yahoo.com @kevinroast * * Please see: license.txt * You are welcome to use this code, but I would appreciate an email or tweet * if you do anything interesting with it! * * 30/04/09 Initial version. * 12/05/09 Refactored to remove globals into GameHandler instance and added FPS controller game loop. * 17/01/11 Full screen resizable canvas * 26/01/11 World to screen transformation - no longer unit=pixel * 25/11/11 Refactored to use requestAnimationFrame - 60fps and frame multipler calculation */ var iOS = (navigator.userAgent.indexOf("iPhone;") != -1 || navigator.userAgent.indexOf("iPod;") != -1 || navigator.userAgent.indexOf("iPad;") != -1); var isFireFox = (navigator.userAgent.indexOf(" Firefox/") != -1); /** * Game Handler. * * Singleton instance responsible for managing the main game loop and * maintaining a few global references such as the canvas and frame counters. */ var GameHandler = { /** * The single Game.Main derived instance */ game: null, /** * True if the game is in pause state, false if running */ paused: false, /** * The single canvas play field element reference */ canvas: null, /** * Width of the canvas play field */ width: 0, /** * Height of the canvas play field */ height: 0, /** * Canvas element offset for absolute mouse position calculations */ offsetX: 0, offsetY: 0, /** * Frame counter */ frameCount: 0, /** * Frame multiplier - i.e. against the ideal fps */ frameMultipler: 1, /** * Last frame start time in ms */ frameStart: 0, /** * Debugging output */ maxfps: 0, frametime: 0, /** * Ideal FPS constant */ FPSMS: 1000/60, /** * Gamepad API button keycode offset */ GAMEPAD: 1000, /** * Gamepad API support */ gamepad: null, gamepadButtons: {}, /** * Audio API support */ audioContext: null, hasAudio: function() {return this.audioContext !== null;}, audioComp: null, audioGain: null, sounds: {}, /** * Sound on/off */ soundEnabled: true, /** * Keycode constants */ KEY: { SHIFT:16, CTRL:17, ESC:27, RIGHT:39, UP:38, LEFT:37, DOWN:40, SPACE:32, A:65, D:68, E:69, G:71, L:76, P:80, R:82, S:83, T:84, W:87, Z:90, OPENBRACKET:219, CLOSEBRACKET:221 }, /** * Init function called once by a window.onload handler */ init: function(minimumSize, padding) { var canvas = document.getElementById('canvas'); if (!minimumSize) { canvas.width = this.width; canvas.height = this.height; } this.canvas = canvas; this.minimumSize = minimumSize; this.padding = padding; if (!iOS) { window.addEventListener('resize', this.resizeHandler, false); window.addEventListener('scroll', this.resizeHandler, false); } // calculate the initial canvas offsets by manually calling the resize handler this.resizeHandler(); // GamePad API detection this.gamepad = (typeof navigator.getGamepads === "function"); // HTML5 Audio API detection this.audioContext = typeof AudioContext === "function" ? new AudioContext() : null; if (this.audioContext) { this.audioGain = this.audioContext.createGain(); this.audioGain.gain.value = 0.333; this.audioComp = this.audioContext.createDynamicsCompressor(); this.audioGain.connect(this.audioComp); this.audioComp.connect(this.audioContext.destination); } }, /** * Handler to compute canvas size based on current window size and offset */ resizeHandler: function() { var me = GameHandler; var el = me.canvas, x = 0, y = 0; do { y += el.offsetTop; x += el.offsetLeft; } while (el = el.offsetParent); // compute offset including page view position me.offsetX = x - window.pageXOffset; me.offsetY = y - window.pageYOffset; // canvas size may be controlled by window height if minimum size set if (me.minimumSize) { var size = window.innerHeight > me.minimumSize + me.padding ? window.innerHeight - me.padding : me.minimumSize; if (me.width !== size) { //if (DEBUG) console.log("Updating canvas size: " + size + " offsets: " + x + "," + y); me.width = me.height = me.canvas.width = me.canvas.height = size; } } //if (DEBUG) console.log("Canvas offset: " + x + "," + y); }, /** * Game start method - begins the main game loop. * Pass in the object that represent the game to execute. * Also called each frame by the main game loop unless paused. * * @param {Game.Main} game main derived object handler */ start: function(game) { if (game instanceof Game.Main) { // first time init this.game = game; GameHandler.frameStart = Date.now(); } GameHandler.game.frame.call(GameHandler.game); }, /** * Game pause toggle method. */ pause: function() { if (this.paused) { this.paused = false; GameHandler.frameStart = Date.now(); GameHandler.game.frame.call(GameHandler.game); } else { this.paused = true; } }, /** * Load sound helper */ loadSound: function(url, id) { if (this.hasAudio()) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; // fancy binary XHR2 request var me = this; request.onload = function() { me.audioContext.decodeAudioData(request.response, function(buffer) { me.sounds[id] = buffer; }); }; request.send(); }
/** * Play sound helper */ playSound: function(id) { if (this.soundEnabled && this.hasAudio() && this.sounds[id]) { var source = this.audioContext.createBufferSource(); source.buffer = this.sounds[id]; source.connect(this.audioGain); source.start(0); } } }; /** * Game root namespace. * * @namespace Game */ if (typeof Game == "undefined" || !Game) { var Game = {}; } /** * Transform a vector from world coordinates to screen * * @method worldToScreen * @return Vector or null if non visible */ Game.worldToScreen = function worldToScreen(vector, world, radiusx, radiusy) { // transform a vector from the world to the screen radiusx = (radiusx ? radiusx : 0); radiusy = (radiusy ? radiusy : radiusx); var screenvec = null, viewx = vector.x - world.viewx, viewy = vector.y - world.viewy; if (viewx < world.viewsize + radiusx && viewy < world.viewsize + radiusy && viewx > -radiusx && viewy > -radiusy) { screenvec = new Vector(viewx, viewy).scale(world.scale); } return screenvec; }; /** * Game main loop class. * * @namespace Game * @class Game.Main */ (function() { Game.Main = function() { var me = this; document.onkeydown = function(event) { var keyCode = event.keyCode; if (me.sceneIndex !== -1) { if (me.scenes[me.sceneIndex].onKeyDownHandler(keyCode)) { // the key is handled, prevent any further events event.preventDefault(); event.stopPropagation(); } } else { // default handler to stop some annoying browser behavior if (keyCode === GameHandler.KEY.SPACE) { event.preventDefault(); event.stopPropagation(); } } }; document.onkeyup = function(event) { var keyCode = event.keyCode; if (me.sceneIndex !== -1) { if (me.scenes[me.sceneIndex].onKeyUpHandler(keyCode)) { // the key is handled, prevent any further events event.preventDefault(); event.stopPropagation(); } } else { // default handler to stop some annoying browser behavior if (keyCode === GameHandler.KEY.SPACE) { event.preventDefault(); event.stopPropagation(); } } }; }; Game.Main.prototype = { scenes: [], startScene: null, endScene: null, currentScene: null, sceneIndex: -1, interval: null, /** * Game frame execute method - called by anim handler timeout */ frame: function frame() { var frameStart = Date.now(); GameHandler.resizeHandler(); // Gamepad support - does not support events - probe manually for values if (GameHandler.gamepad && this.sceneIndex !== -1) { for (var i=0,pad; i<navigator.getGamepads().length; i++) { if (pad = navigator.getGamepads()[i]) { for (var b=0; b<pad.buttons.length; b++) { if (pad.buttons[b].pressed) { //console.log(b + " := " + pad.buttons[b].pressed); GameHandler.gamepadButtons[b] = true; this.scenes[this.sceneIndex].onKeyDownHandler(GameHandler.GAMEPAD + b); } // deal with button up to ensure orthogonal button press events else if (GameHandler.gamepadButtons[b]) { //console.log(b + " := " + pad.buttons[b].pressed); GameHandler.gamepadButtons[b] = false; this.scenes[this.sceneIndex].onKeyUpHandler(GameHandler.GAMEPAD + b); } } for (var a=0; a<pad.axes.length; a++) { //console.log("axes" + a + " := " + pad.axes[a]); this.scenes[this.sceneIndex].onAxisHandler(a, pad.axes[a]); } break; } } } // calculate scene transition and current scene var currentScene = this.currentScene; if (currentScene === null) { // set to scene zero (game init) this.sceneIndex = 0; currentScene = this.scenes[0]; currentScene.onInitScene(); } else if (this.isGameOver()) { this.sceneIndex = -1; currentScene = this.endScene; currentScene.onInitScene(); } if ((!currentScene.interval || currentScene.interval.complete) && currentScene.isComplete()) { //alert("scene interval complete and scene completed."); this.sceneIndex++; if (this.sceneIndex < this.scenes.length) { currentScene = this.scenes[this.sceneIndex]; } else { this.sceneIndex = 0; currentScene = this.scenes[0]; } currentScene.onInitScene(); } // get canvas context for a render pass var ctx = GameHandler.canvas.getContext('2d'); // calculate viewport transform and offset against the world // we want to show a fixed number of world units in our viewport // so calculate the scaling factor to transform world to view currentScene.world.scale = GameHandler.width / currentScene.world.viewsize; // render the game and current scene; if (!currentScene.interval || currentScene.interval.complete) { currentScene.onBeforeRenderScene(); currentScene.onRenderScene(ctx); } else { this.onRenderGame(ctx); if (currentScene.interval) { currentScene.interval.intervalRenderer.call(currentScene, currentScene.interval, ctx); } } // update global frame counter and current scene reference this.currentScene = currentScene; GameHandler.frameCount++; // calculate frame total time interval and frame multiplier required for smooth animation var frameInterval = frameStart - GameHandler.frameStart; if (frameInterval === 0) frameInterval = 1; if (DEBUG) { if (GameHandler.frameCount % 16 === 0) GameHandler.maxfps = ~~(1000 / frameInterval); } GameHandler.frametime = Date.now() - frameStart; GameHandler.frameMultipler = frameInterval / GameHandler.FPSMS; GameHandler.frameStart = frameStart; // for browsers not supporting requestAnimationFrame natively, we calculate the offset // between each frame to attempt to maintain a smooth fps var frameOffset = ~~(GameHandler.FPSMS - GameHandler.frametime); if (!GameHandler.paused) requestAnimFrame(GameHandler.start, frameOffset); }, onRenderGame: function onRenderGame(ctx) { }, isGameOver: function isGameOver() { return false; } }; })(); /** * Game scene base class. * * @namespace Game * @class Game.Scene */ (function() { Game.Scene = function(game, interval) { this.game = game; this.interval = interval; }; Game.Scene.prototype = { game: null, interval: null, world: { size: 1500, // total units vertically and horizontally viewx: 0, // current view left corner xpos viewy: 0, // current view left corner ypos viewsize: 1000, // size of the viewable area scale: 1000/1500 // scale for world->view transformation - calculated based on physical viewport size }, onInitScene: function onInitScene() { if (this.interval !== null) { // reset interval flag this.interval.reset(); } }, onBeforeRenderScene: function onBeforeRenderScene() { }, onRenderScene: function onRenderScene(ctx) { }, onRenderInterval: function onRenderInterval(ctx) { }, onKeyDownHandler: function onKeyDownHandler(keyCode) { }, onKeyUpHandler: function onKeyUpHandler(keyCode) { }, onAxisHandler: function onAxisHandler(axis, delta) { }, isComplete: function isComplete() { return false; } }; })(); (function() { Game.Interval = function(label, intervalRenderer) { this.label = label; this.intervalRenderer = intervalRenderer; this.framecounter = 0; this.complete = false; }; Game.Interval.prototype = { label: null, intervalRenderer: null, framecounter: 0, complete: false, reset: function reset() { this.framecounter = 0; this.complete = false; } }; })(); /** * Actor base class. * * Game actors have a position in the game world and a current vector to indicate * direction and speed of travel per frame. They each support the onUpdate() and * onRender() event methods, finally an actor has an expired() method which should * return true when the actor object should be removed from play. * * An actor can be hit and destroyed by bullets or similar. The class supports a hit() * method which should return true when the actor should be removed from play. * * @namespace Game * @class Game.Actor */ (function() { Game.Actor = function(p, v) { this.position = p; this.vector = v; return this; }; Game.Actor.prototype = { /** * Actor position * * @property position * @type Vector */ position: null, /** * Actor vector * * @property vector * @type Vector */ vector: null, /** * Alive flag * * @property alive * @type boolean */ alive: true, /** * Radius - default is zero to imply that it is not affected by collision tests etc. * * @property radius * @type int */ radius: 0, /** * Actor expiration test * * @method expired * @return true if expired and to be removed from the actor list, false if still in play */ expired: function expired() { return !(this.alive); }, /** * Hit by bullet * * @param force of the impacting bullet (as the actor may support health) * @return true if destroyed, false otherwise */ hit: function hit(force) { this.alive = false; return true; }, /** * Transform current position vector from world coordinates to screen. * Applies the appropriate translation and scaling to the canvas context. * * @method worldToScreen * @return Vector or null if non visible */ worldToScreen: function worldToScreen(ctx, world, radius) { var viewposition = Game.worldToScreen(this.position, world, radius); if (viewposition) { // scale ALL graphics... - translate to position apply canvas scaling ctx.translate(viewposition.x, viewposition.y); ctx.scale(world.scale, world.scale); } return viewposition; }, /** * Actor game loop update event method. Called for each actor * at the start of each game loop cycle. * * @method onUpdate */ onUpdate: function onUpdate() { }, /** * Actor rendering event method. Called for each actor to * render for each frame. * * @method onRender * @param ctx {object} Canvas rendering context * @param world {object} World metadata */ onRender: function onRender(ctx, world) { } }; })(); /** * SpriteActor base class. * * An actor that can be rendered by a bitmap. The sprite handling code deals with the increment * of the current frame within the supplied bitmap sprite strip image, based on animation direction, * animation speed and the animation length before looping. Call renderSprite() each frame. * * NOTE: by default sprites source images are 64px wide 64px by N frames high and scaled to the * appropriate final size. Any other size input source should be set in the constructor. * * @namespace Game * @class Game.SpriteActor */ (function() { Game.SpriteActor = function(p, v, s) { Game.SpriteActor.superclass.constructor.call(this, p, v); if (s) this.frameSize = s; return this; }; extend(Game.SpriteActor, Game.Actor, { /** * Size in pixels of the width/height of an individual frame in the image */ frameSize: 64, /** * Animation image sprite reference. * Sprite image sources are all currently 64px wide 64px by N frames high. */ animImage: null, /** * Length in frames of the sprite animation */ animLength: 0, /** * Animation direction, true for forward, false for reverse. */ animForward: true, /** * Animation frame inc/dec speed. */ animSpeed: 1.0, /** * Current animation frame index */ animFrame: 0, /** * TODO: convert to use new world->view transformation! * * Render sprite graphic based on current anim image, frame and anim direction * Automatically updates the current anim frame. * * Optionally this method will automatically correct for objects moving on/off * a cyclic canvas play area - if so it will render the appropriate stencil * sections of the sprite top/bottom/left/right as needed to complete the image. * Note that this feature can only be used if the sprite is absolutely positioned * and not translated/rotated into position by canvas operations. */ renderSprite: function renderSprite(ctx, x, y, w, cyclic) { var offset = this.animFrame << 6, fs = this.frameSize; ctx.drawImage(this.animImage, 0, offset, fs, fs, x, y, w, w); if (cyclic) { if (x < 0 || y < 0) { ctx.drawImage(this.animImage, 0, offset, fs, fs, (x < 0 ? (GameHandler.width + x) : x), (y < 0 ? (GameHandler.height + y) : y), w, w); } if (x + w >= GameHandler.width || y + w >= GameHandler.height) { ctx.drawImage(this.animImage, 0, offset, fs, fs, (x + w >= GameHandler.width ? (x - GameHandler.width) : x), (y + w >= GameHandler.height ? (y - GameHandler.height) : y), w, w); } } // update animation frame index if (this.animForward) { this.animFrame += this.animSpeed; if (this.animFrame >= this.animLength) { this.animFrame = 0; } } else { this.animFrame -= this.animSpeed; if (this.animFrame < 0) { this.animFrame = this.animLength - 1; } } } }); })(); /** * EffectActor base class. * * An actor representing a transient instance in the game world. An effect automatically expires * after a set lifespan, generally the rendering of the effect is based on the remaining lifespan. * The effect class provides a number of methods to return stepped values based on the remaining * lifespan of the effect. * * @namespace Game * @class Game.EffectActor */ (function() { Game.EffectActor = function(p, v, lifespan) { Game.EffectActor.superclass.constructor.call(this, p, v); this.lifespan = lifespan; this.effectStart = GameHandler.frameStart; return this; }; extend(Game.EffectActor, Game.Actor, { /** * Effect lifespan in ms */ lifespan: 0, /** * Effect start time */ effectStart: 0, /** * Actor expiration test * * @return true if expired and to be removed from the actor list, false if still in play */ expired: function expired() { // test to see if the effect has expired return (GameHandler.frameStart - this.effectStart > this.lifespan); }, /** * Helper to return a value multiplied by the ratio of the remaining lifespan with an optional * offset within which to apply the ratio. * * @param val value to apply to the ratio of remaining lifespan * @param offset optional offset at which to begin applying the ratio */ effectValue: function effectValue(val, offset) { if (!offset) offset = this.lifespan; var rem = this.lifespan - (GameHandler.frameStart - this.effectStart), result = val; if (rem < offset) { result = (val / offset) * rem; // this is not a simple counter - so we need to crop the value // as the time between frames is not determinate if (result < 0) result = 0; else if (result > val) result = val; } return result; } }); })(); /** * Image Preloader class. Executes the supplied callback function once all * registered images are loaded by the browser. * * @namespace Game * @class Game.Preloader */ (function() { Game.Preloader = function() { this.images = []; return this; }; Game.Preloader.prototype = { /** * Image list * * @property images * @type Array */ images: null, /** * Callback function * * @property callback * @type Function */ callback: null, /** * Images loaded so far counter */ counter: 0, /** * Add an image to the list of images to wait for */ addImage: function addImage(img, url) { var me = this; img.url = url; // attach closure to the image onload handler img.onload = function() { me.counter++; if (me.counter === me.images.length) { // all images are loaded - execute callback function me.callback.call(me); } }; this.images.push(img); }, /** * Load the images and call the supplied function when ready */ onLoadCallback: function onLoadCallback(fn) { this.counter = 0; this.callback = fn; // load the images for (var i=0, j=this.images.length; i<j; i++) { this.images[i].src = this.images[i].url; } } }; })(); /** * Render text into the canvas context. * Compatible with FF3.5, SF4, GC4, OP10 * * @method Game.drawText * @static */ Game.drawText = function(g, txt, font, x, y, col) { g.save(); if (col) g.strokeStyle = col; g.font = font; g.strokeText(txt, x, y); g.restore(); }; Game.centerDrawText = function(g, txt, font, y, col) { g.save(); if (col) g.strokeStyle = col; g.font = font; g.strokeText(txt, (GameHandler.width - g.measureText(txt).width) / 2, y); g.restore(); }; Game.fillText = function(g, txt, font, x, y, col) { g.save(); if (col) g.fillStyle = col; g.font = font; g.fillText(txt, x, y); g.restore(); }; Game.centerFillText = function(g, txt, font, y, col) { g.save(); if (col) g.fillStyle = col; g.font = font; g.fillText(txt, (GameHandler.width - g.measureText(txt).width) / 2, y); g.restore(); }; Game.fontSize = function fontSize(world, size) { var s = ~~(size * world.scale * 2); if (s > 20) s = 20; else if (s < 8) s = 8; return s; }; Game.fontFamily = function fontFamily(world, size, font) { return Game.fontSize(world, size) + "pt " + (font ? font : "Courier New"); }; /** * Game prerenderer class. * * @namespace Game * @class Game.Prerenderer */ (function() { Game.Prerenderer = function() { this.images = []; this._renderers = []; return this; }; Game.Prerenderer.prototype = { /** * Image list. Keyed by renderer ID - returning an array also. So to get * the first image output by prerenderer with id "default": images["default"][0] * * @public * @property images * @type Array */ images: null, _renderers: null, /** * Add a renderer function to the list of renderers to execute * * @param fn {function} Callback to execute to perform prerender * Passed canvas element argument - to execute against - the * callback is responsible for setting appropriate width/height * of the buffer and should not assume it is cleared. * Should return Array of images from prerender process * @param id {string} Id of the prerender - used to lookup images later */ addRenderer: function addRenderer(fn, id) { this._renderers[id] = fn; }, /** * Execute all prerender functions - call once all renderers have been added */ execute: function execute(fnCallback, fnCompleted) { var me = this, buffer = document.createElement('canvas'), renderKeys = Object.keys(this._renderers), renderCount = 0; // function to execute a renderer, return handling to the browser UI thread - then call back var fn = function() { var id = renderKeys[renderCount++]; me.images[id] = me._renderers[id].call(me, buffer); if (fnCallback) { var percentComplete = ~~(100 / renderKeys.length) * renderCount; fnCallback.call(me, percentComplete); } if (renderCount < renderKeys.length) { setTimeout(function() {fn()}, 0); } else if (fnCompleted) { fnCompleted.call(me); } }; fn(); } }; })(); // requestAnimFrame shim window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, frameOffset) { window.setTimeout(callback, frameOffset); }; })();
},
random_line_split
gamelib.js
/** * Game class library, utility functions and globals. * * (C) 2010 Kevin Roast kevtoast@yahoo.com @kevinroast * * Please see: license.txt * You are welcome to use this code, but I would appreciate an email or tweet * if you do anything interesting with it! * * 30/04/09 Initial version. * 12/05/09 Refactored to remove globals into GameHandler instance and added FPS controller game loop. * 17/01/11 Full screen resizable canvas * 26/01/11 World to screen transformation - no longer unit=pixel * 25/11/11 Refactored to use requestAnimationFrame - 60fps and frame multipler calculation */ var iOS = (navigator.userAgent.indexOf("iPhone;") != -1 || navigator.userAgent.indexOf("iPod;") != -1 || navigator.userAgent.indexOf("iPad;") != -1); var isFireFox = (navigator.userAgent.indexOf(" Firefox/") != -1); /** * Game Handler. * * Singleton instance responsible for managing the main game loop and * maintaining a few global references such as the canvas and frame counters. */ var GameHandler = { /** * The single Game.Main derived instance */ game: null, /** * True if the game is in pause state, false if running */ paused: false, /** * The single canvas play field element reference */ canvas: null, /** * Width of the canvas play field */ width: 0, /** * Height of the canvas play field */ height: 0, /** * Canvas element offset for absolute mouse position calculations */ offsetX: 0, offsetY: 0, /** * Frame counter */ frameCount: 0, /** * Frame multiplier - i.e. against the ideal fps */ frameMultipler: 1, /** * Last frame start time in ms */ frameStart: 0, /** * Debugging output */ maxfps: 0, frametime: 0, /** * Ideal FPS constant */ FPSMS: 1000/60, /** * Gamepad API button keycode offset */ GAMEPAD: 1000, /** * Gamepad API support */ gamepad: null, gamepadButtons: {}, /** * Audio API support */ audioContext: null, hasAudio: function() {return this.audioContext !== null;}, audioComp: null, audioGain: null, sounds: {}, /** * Sound on/off */ soundEnabled: true, /** * Keycode constants */ KEY: { SHIFT:16, CTRL:17, ESC:27, RIGHT:39, UP:38, LEFT:37, DOWN:40, SPACE:32, A:65, D:68, E:69, G:71, L:76, P:80, R:82, S:83, T:84, W:87, Z:90, OPENBRACKET:219, CLOSEBRACKET:221 }, /** * Init function called once by a window.onload handler */ init: function(minimumSize, padding) { var canvas = document.getElementById('canvas'); if (!minimumSize) { canvas.width = this.width; canvas.height = this.height; } this.canvas = canvas; this.minimumSize = minimumSize; this.padding = padding; if (!iOS) { window.addEventListener('resize', this.resizeHandler, false); window.addEventListener('scroll', this.resizeHandler, false); } // calculate the initial canvas offsets by manually calling the resize handler this.resizeHandler(); // GamePad API detection this.gamepad = (typeof navigator.getGamepads === "function"); // HTML5 Audio API detection this.audioContext = typeof AudioContext === "function" ? new AudioContext() : null; if (this.audioContext) { this.audioGain = this.audioContext.createGain(); this.audioGain.gain.value = 0.333; this.audioComp = this.audioContext.createDynamicsCompressor(); this.audioGain.connect(this.audioComp); this.audioComp.connect(this.audioContext.destination); } }, /** * Handler to compute canvas size based on current window size and offset */ resizeHandler: function() { var me = GameHandler; var el = me.canvas, x = 0, y = 0; do { y += el.offsetTop; x += el.offsetLeft; } while (el = el.offsetParent); // compute offset including page view position me.offsetX = x - window.pageXOffset; me.offsetY = y - window.pageYOffset; // canvas size may be controlled by window height if minimum size set if (me.minimumSize) { var size = window.innerHeight > me.minimumSize + me.padding ? window.innerHeight - me.padding : me.minimumSize; if (me.width !== size) { //if (DEBUG) console.log("Updating canvas size: " + size + " offsets: " + x + "," + y); me.width = me.height = me.canvas.width = me.canvas.height = size; } } //if (DEBUG) console.log("Canvas offset: " + x + "," + y); }, /** * Game start method - begins the main game loop. * Pass in the object that represent the game to execute. * Also called each frame by the main game loop unless paused. * * @param {Game.Main} game main derived object handler */ start: function(game) { if (game instanceof Game.Main) { // first time init this.game = game; GameHandler.frameStart = Date.now(); } GameHandler.game.frame.call(GameHandler.game); }, /** * Game pause toggle method. */ pause: function() { if (this.paused) { this.paused = false; GameHandler.frameStart = Date.now(); GameHandler.game.frame.call(GameHandler.game); } else { this.paused = true; } }, /** * Load sound helper */ loadSound: function(url, id) { if (this.hasAudio()) { var request = new XMLHttpRequest(); request.open("GET", url, true); request.responseType = "arraybuffer"; // fancy binary XHR2 request var me = this; request.onload = function() { me.audioContext.decodeAudioData(request.response, function(buffer) { me.sounds[id] = buffer; }); }; request.send(); } }, /** * Play sound helper */ playSound: function(id) { if (this.soundEnabled && this.hasAudio() && this.sounds[id]) { var source = this.audioContext.createBufferSource(); source.buffer = this.sounds[id]; source.connect(this.audioGain); source.start(0); } } }; /** * Game root namespace. * * @namespace Game */ if (typeof Game == "undefined" || !Game) { var Game = {}; } /** * Transform a vector from world coordinates to screen * * @method worldToScreen * @return Vector or null if non visible */ Game.worldToScreen = function worldToScreen(vector, world, radiusx, radiusy) { // transform a vector from the world to the screen radiusx = (radiusx ? radiusx : 0); radiusy = (radiusy ? radiusy : radiusx); var screenvec = null, viewx = vector.x - world.viewx, viewy = vector.y - world.viewy; if (viewx < world.viewsize + radiusx && viewy < world.viewsize + radiusy && viewx > -radiusx && viewy > -radiusy) { screenvec = new Vector(viewx, viewy).scale(world.scale); } return screenvec; }; /** * Game main loop class. * * @namespace Game * @class Game.Main */ (function() { Game.Main = function() { var me = this; document.onkeydown = function(event) { var keyCode = event.keyCode; if (me.sceneIndex !== -1) { if (me.scenes[me.sceneIndex].onKeyDownHandler(keyCode)) { // the key is handled, prevent any further events event.preventDefault(); event.stopPropagation(); } } else { // default handler to stop some annoying browser behavior if (keyCode === GameHandler.KEY.SPACE) { event.preventDefault(); event.stopPropagation(); } } }; document.onkeyup = function(event) { var keyCode = event.keyCode; if (me.sceneIndex !== -1) { if (me.scenes[me.sceneIndex].onKeyUpHandler(keyCode)) { // the key is handled, prevent any further events event.preventDefault(); event.stopPropagation(); } } else { // default handler to stop some annoying browser behavior if (keyCode === GameHandler.KEY.SPACE) { event.preventDefault(); event.stopPropagation(); } } }; }; Game.Main.prototype = { scenes: [], startScene: null, endScene: null, currentScene: null, sceneIndex: -1, interval: null, /** * Game frame execute method - called by anim handler timeout */ frame: function frame() { var frameStart = Date.now(); GameHandler.resizeHandler(); // Gamepad support - does not support events - probe manually for values if (GameHandler.gamepad && this.sceneIndex !== -1) { for (var i=0,pad; i<navigator.getGamepads().length; i++) { if (pad = navigator.getGamepads()[i]) { for (var b=0; b<pad.buttons.length; b++) { if (pad.buttons[b].pressed) { //console.log(b + " := " + pad.buttons[b].pressed); GameHandler.gamepadButtons[b] = true; this.scenes[this.sceneIndex].onKeyDownHandler(GameHandler.GAMEPAD + b); } // deal with button up to ensure orthogonal button press events else if (GameHandler.gamepadButtons[b]) { //console.log(b + " := " + pad.buttons[b].pressed); GameHandler.gamepadButtons[b] = false; this.scenes[this.sceneIndex].onKeyUpHandler(GameHandler.GAMEPAD + b); } } for (var a=0; a<pad.axes.length; a++) { //console.log("axes" + a + " := " + pad.axes[a]); this.scenes[this.sceneIndex].onAxisHandler(a, pad.axes[a]); } break; } } } // calculate scene transition and current scene var currentScene = this.currentScene; if (currentScene === null) { // set to scene zero (game init) this.sceneIndex = 0; currentScene = this.scenes[0]; currentScene.onInitScene(); } else if (this.isGameOver()) { this.sceneIndex = -1; currentScene = this.endScene; currentScene.onInitScene(); } if ((!currentScene.interval || currentScene.interval.complete) && currentScene.isComplete()) { //alert("scene interval complete and scene completed."); this.sceneIndex++; if (this.sceneIndex < this.scenes.length) { currentScene = this.scenes[this.sceneIndex]; } else { this.sceneIndex = 0; currentScene = this.scenes[0]; } currentScene.onInitScene(); } // get canvas context for a render pass var ctx = GameHandler.canvas.getContext('2d'); // calculate viewport transform and offset against the world // we want to show a fixed number of world units in our viewport // so calculate the scaling factor to transform world to view currentScene.world.scale = GameHandler.width / currentScene.world.viewsize; // render the game and current scene; if (!currentScene.interval || currentScene.interval.complete) { currentScene.onBeforeRenderScene(); currentScene.onRenderScene(ctx); } else { this.onRenderGame(ctx); if (currentScene.interval)
} // update global frame counter and current scene reference this.currentScene = currentScene; GameHandler.frameCount++; // calculate frame total time interval and frame multiplier required for smooth animation var frameInterval = frameStart - GameHandler.frameStart; if (frameInterval === 0) frameInterval = 1; if (DEBUG) { if (GameHandler.frameCount % 16 === 0) GameHandler.maxfps = ~~(1000 / frameInterval); } GameHandler.frametime = Date.now() - frameStart; GameHandler.frameMultipler = frameInterval / GameHandler.FPSMS; GameHandler.frameStart = frameStart; // for browsers not supporting requestAnimationFrame natively, we calculate the offset // between each frame to attempt to maintain a smooth fps var frameOffset = ~~(GameHandler.FPSMS - GameHandler.frametime); if (!GameHandler.paused) requestAnimFrame(GameHandler.start, frameOffset); }, onRenderGame: function onRenderGame(ctx) { }, isGameOver: function isGameOver() { return false; } }; })(); /** * Game scene base class. * * @namespace Game * @class Game.Scene */ (function() { Game.Scene = function(game, interval) { this.game = game; this.interval = interval; }; Game.Scene.prototype = { game: null, interval: null, world: { size: 1500, // total units vertically and horizontally viewx: 0, // current view left corner xpos viewy: 0, // current view left corner ypos viewsize: 1000, // size of the viewable area scale: 1000/1500 // scale for world->view transformation - calculated based on physical viewport size }, onInitScene: function onInitScene() { if (this.interval !== null) { // reset interval flag this.interval.reset(); } }, onBeforeRenderScene: function onBeforeRenderScene() { }, onRenderScene: function onRenderScene(ctx) { }, onRenderInterval: function onRenderInterval(ctx) { }, onKeyDownHandler: function onKeyDownHandler(keyCode) { }, onKeyUpHandler: function onKeyUpHandler(keyCode) { }, onAxisHandler: function onAxisHandler(axis, delta) { }, isComplete: function isComplete() { return false; } }; })(); (function() { Game.Interval = function(label, intervalRenderer) { this.label = label; this.intervalRenderer = intervalRenderer; this.framecounter = 0; this.complete = false; }; Game.Interval.prototype = { label: null, intervalRenderer: null, framecounter: 0, complete: false, reset: function reset() { this.framecounter = 0; this.complete = false; } }; })(); /** * Actor base class. * * Game actors have a position in the game world and a current vector to indicate * direction and speed of travel per frame. They each support the onUpdate() and * onRender() event methods, finally an actor has an expired() method which should * return true when the actor object should be removed from play. * * An actor can be hit and destroyed by bullets or similar. The class supports a hit() * method which should return true when the actor should be removed from play. * * @namespace Game * @class Game.Actor */ (function() { Game.Actor = function(p, v) { this.position = p; this.vector = v; return this; }; Game.Actor.prototype = { /** * Actor position * * @property position * @type Vector */ position: null, /** * Actor vector * * @property vector * @type Vector */ vector: null, /** * Alive flag * * @property alive * @type boolean */ alive: true, /** * Radius - default is zero to imply that it is not affected by collision tests etc. * * @property radius * @type int */ radius: 0, /** * Actor expiration test * * @method expired * @return true if expired and to be removed from the actor list, false if still in play */ expired: function expired() { return !(this.alive); }, /** * Hit by bullet * * @param force of the impacting bullet (as the actor may support health) * @return true if destroyed, false otherwise */ hit: function hit(force) { this.alive = false; return true; }, /** * Transform current position vector from world coordinates to screen. * Applies the appropriate translation and scaling to the canvas context. * * @method worldToScreen * @return Vector or null if non visible */ worldToScreen: function worldToScreen(ctx, world, radius) { var viewposition = Game.worldToScreen(this.position, world, radius); if (viewposition) { // scale ALL graphics... - translate to position apply canvas scaling ctx.translate(viewposition.x, viewposition.y); ctx.scale(world.scale, world.scale); } return viewposition; }, /** * Actor game loop update event method. Called for each actor * at the start of each game loop cycle. * * @method onUpdate */ onUpdate: function onUpdate() { }, /** * Actor rendering event method. Called for each actor to * render for each frame. * * @method onRender * @param ctx {object} Canvas rendering context * @param world {object} World metadata */ onRender: function onRender(ctx, world) { } }; })(); /** * SpriteActor base class. * * An actor that can be rendered by a bitmap. The sprite handling code deals with the increment * of the current frame within the supplied bitmap sprite strip image, based on animation direction, * animation speed and the animation length before looping. Call renderSprite() each frame. * * NOTE: by default sprites source images are 64px wide 64px by N frames high and scaled to the * appropriate final size. Any other size input source should be set in the constructor. * * @namespace Game * @class Game.SpriteActor */ (function() { Game.SpriteActor = function(p, v, s) { Game.SpriteActor.superclass.constructor.call(this, p, v); if (s) this.frameSize = s; return this; }; extend(Game.SpriteActor, Game.Actor, { /** * Size in pixels of the width/height of an individual frame in the image */ frameSize: 64, /** * Animation image sprite reference. * Sprite image sources are all currently 64px wide 64px by N frames high. */ animImage: null, /** * Length in frames of the sprite animation */ animLength: 0, /** * Animation direction, true for forward, false for reverse. */ animForward: true, /** * Animation frame inc/dec speed. */ animSpeed: 1.0, /** * Current animation frame index */ animFrame: 0, /** * TODO: convert to use new world->view transformation! * * Render sprite graphic based on current anim image, frame and anim direction * Automatically updates the current anim frame. * * Optionally this method will automatically correct for objects moving on/off * a cyclic canvas play area - if so it will render the appropriate stencil * sections of the sprite top/bottom/left/right as needed to complete the image. * Note that this feature can only be used if the sprite is absolutely positioned * and not translated/rotated into position by canvas operations. */ renderSprite: function renderSprite(ctx, x, y, w, cyclic) { var offset = this.animFrame << 6, fs = this.frameSize; ctx.drawImage(this.animImage, 0, offset, fs, fs, x, y, w, w); if (cyclic) { if (x < 0 || y < 0) { ctx.drawImage(this.animImage, 0, offset, fs, fs, (x < 0 ? (GameHandler.width + x) : x), (y < 0 ? (GameHandler.height + y) : y), w, w); } if (x + w >= GameHandler.width || y + w >= GameHandler.height) { ctx.drawImage(this.animImage, 0, offset, fs, fs, (x + w >= GameHandler.width ? (x - GameHandler.width) : x), (y + w >= GameHandler.height ? (y - GameHandler.height) : y), w, w); } } // update animation frame index if (this.animForward) { this.animFrame += this.animSpeed; if (this.animFrame >= this.animLength) { this.animFrame = 0; } } else { this.animFrame -= this.animSpeed; if (this.animFrame < 0) { this.animFrame = this.animLength - 1; } } } }); })(); /** * EffectActor base class. * * An actor representing a transient instance in the game world. An effect automatically expires * after a set lifespan, generally the rendering of the effect is based on the remaining lifespan. * The effect class provides a number of methods to return stepped values based on the remaining * lifespan of the effect. * * @namespace Game * @class Game.EffectActor */ (function() { Game.EffectActor = function(p, v, lifespan) { Game.EffectActor.superclass.constructor.call(this, p, v); this.lifespan = lifespan; this.effectStart = GameHandler.frameStart; return this; }; extend(Game.EffectActor, Game.Actor, { /** * Effect lifespan in ms */ lifespan: 0, /** * Effect start time */ effectStart: 0, /** * Actor expiration test * * @return true if expired and to be removed from the actor list, false if still in play */ expired: function expired() { // test to see if the effect has expired return (GameHandler.frameStart - this.effectStart > this.lifespan); }, /** * Helper to return a value multiplied by the ratio of the remaining lifespan with an optional * offset within which to apply the ratio. * * @param val value to apply to the ratio of remaining lifespan * @param offset optional offset at which to begin applying the ratio */ effectValue: function effectValue(val, offset) { if (!offset) offset = this.lifespan; var rem = this.lifespan - (GameHandler.frameStart - this.effectStart), result = val; if (rem < offset) { result = (val / offset) * rem; // this is not a simple counter - so we need to crop the value // as the time between frames is not determinate if (result < 0) result = 0; else if (result > val) result = val; } return result; } }); })(); /** * Image Preloader class. Executes the supplied callback function once all * registered images are loaded by the browser. * * @namespace Game * @class Game.Preloader */ (function() { Game.Preloader = function() { this.images = []; return this; }; Game.Preloader.prototype = { /** * Image list * * @property images * @type Array */ images: null, /** * Callback function * * @property callback * @type Function */ callback: null, /** * Images loaded so far counter */ counter: 0, /** * Add an image to the list of images to wait for */ addImage: function addImage(img, url) { var me = this; img.url = url; // attach closure to the image onload handler img.onload = function() { me.counter++; if (me.counter === me.images.length) { // all images are loaded - execute callback function me.callback.call(me); } }; this.images.push(img); }, /** * Load the images and call the supplied function when ready */ onLoadCallback: function onLoadCallback(fn) { this.counter = 0; this.callback = fn; // load the images for (var i=0, j=this.images.length; i<j; i++) { this.images[i].src = this.images[i].url; } } }; })(); /** * Render text into the canvas context. * Compatible with FF3.5, SF4, GC4, OP10 * * @method Game.drawText * @static */ Game.drawText = function(g, txt, font, x, y, col) { g.save(); if (col) g.strokeStyle = col; g.font = font; g.strokeText(txt, x, y); g.restore(); }; Game.centerDrawText = function(g, txt, font, y, col) { g.save(); if (col) g.strokeStyle = col; g.font = font; g.strokeText(txt, (GameHandler.width - g.measureText(txt).width) / 2, y); g.restore(); }; Game.fillText = function(g, txt, font, x, y, col) { g.save(); if (col) g.fillStyle = col; g.font = font; g.fillText(txt, x, y); g.restore(); }; Game.centerFillText = function(g, txt, font, y, col) { g.save(); if (col) g.fillStyle = col; g.font = font; g.fillText(txt, (GameHandler.width - g.measureText(txt).width) / 2, y); g.restore(); }; Game.fontSize = function fontSize(world, size) { var s = ~~(size * world.scale * 2); if (s > 20) s = 20; else if (s < 8) s = 8; return s; }; Game.fontFamily = function fontFamily(world, size, font) { return Game.fontSize(world, size) + "pt " + (font ? font : "Courier New"); }; /** * Game prerenderer class. * * @namespace Game * @class Game.Prerenderer */ (function() { Game.Prerenderer = function() { this.images = []; this._renderers = []; return this; }; Game.Prerenderer.prototype = { /** * Image list. Keyed by renderer ID - returning an array also. So to get * the first image output by prerenderer with id "default": images["default"][0] * * @public * @property images * @type Array */ images: null, _renderers: null, /** * Add a renderer function to the list of renderers to execute * * @param fn {function} Callback to execute to perform prerender * Passed canvas element argument - to execute against - the * callback is responsible for setting appropriate width/height * of the buffer and should not assume it is cleared. * Should return Array of images from prerender process * @param id {string} Id of the prerender - used to lookup images later */ addRenderer: function addRenderer(fn, id) { this._renderers[id] = fn; }, /** * Execute all prerender functions - call once all renderers have been added */ execute: function execute(fnCallback, fnCompleted) { var me = this, buffer = document.createElement('canvas'), renderKeys = Object.keys(this._renderers), renderCount = 0; // function to execute a renderer, return handling to the browser UI thread - then call back var fn = function() { var id = renderKeys[renderCount++]; me.images[id] = me._renderers[id].call(me, buffer); if (fnCallback) { var percentComplete = ~~(100 / renderKeys.length) * renderCount; fnCallback.call(me, percentComplete); } if (renderCount < renderKeys.length) { setTimeout(function() {fn()}, 0); } else if (fnCompleted) { fnCompleted.call(me); } }; fn(); } }; })(); // requestAnimFrame shim window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, frameOffset) { window.setTimeout(callback, frameOffset); }; })();
{ currentScene.interval.intervalRenderer.call(currentScene, currentScene.interval, ctx); }
conditional_block
ncbo-selection.js
function getSelectedInformation(txt, element) { txt = txt.toString(); text = jQuery.trim(txt); len = text.length; full = jQuery.trim($(element).text()); field_name = $(element).attr("id"); start = full.indexOf(text)+1; end = start+len-1; return {'from':start, 'to':end, 'text':text, 'field_name':field_name}; } function displayResult(data) { $("#annotation-result").removeClass(); $("#annotation-result").addClass(data.status); $("#annotation-result").text(data.message); $("#annotation-result").fadeIn("slow").fadeTo(2000, 1).fadeOut("slow"); $(".annotation-table:not(:has(a))").hide(); $(".annotation-table:has(a)").show(); bindCurate(); bindRightClicks(); } function getSelectedText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); // FireFox } else if (document.getSelection) { txt = document.getSelection(); // IE 6/7 } else if (document.selection) { txt = document.selection.createRange().text; } return txt; } function unbindEvents() { $("input[class*='bp_form_complete']").each(function(){ $(this).unbind(); }); } function submit_annotation()
$(function() { // rightClickMenu(); $("#new_annotation").bind("submit", submit_annotation); $("input#annotation_cancel").bind("click", function(){ $("#new-annotation").hide(); return false; }); $(".dataTable span").contextMenu({ menu: 'annotation-menu' }, function(ontology, el, pos) { var txt = getSelectedText(); if (txt != '') { hash = getSelectedInformation(txt, el); $('#new-annotation').css({top: (pos.docY-125), left: (pos.docX-250)}); ontology_class = "bp_form_complete-"+ontology+"-shortid"; $("input#annotation_ncbo_term_id").removeClass(); $("input#annotation_ncbo_term_id").addClass(ontology_class); unbindEvents(); setup_functions(); $("input#annotation_ncbo_term_id").val(hash.text); $("input#annotation_ncbo_id").val(ontology); $("input#annotation_from").val(hash.from); $("input#annotation_to").val(hash.to); $("input#annotation_field_name").val(hash.field_name); $("#new-annotation").show(); $("input#annotation_ncbo_term_id").focus(); $("input#annotation_ncbo_term_id").keydown(); } return false; }); });
{ $.post("/annotations", $("#new_annotation input").serialize(), function() { load_curators(); }, "script"); return false; }
identifier_body
ncbo-selection.js
function getSelectedInformation(txt, element) { txt = txt.toString(); text = jQuery.trim(txt); len = text.length; full = jQuery.trim($(element).text()); field_name = $(element).attr("id"); start = full.indexOf(text)+1; end = start+len-1; return {'from':start, 'to':end, 'text':text, 'field_name':field_name}; } function displayResult(data) { $("#annotation-result").removeClass(); $("#annotation-result").addClass(data.status); $("#annotation-result").text(data.message); $("#annotation-result").fadeIn("slow").fadeTo(2000, 1).fadeOut("slow"); $(".annotation-table:not(:has(a))").hide(); $(".annotation-table:has(a)").show(); bindCurate(); bindRightClicks(); } function getSelectedText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); // FireFox } else if (document.getSelection) { txt = document.getSelection(); // IE 6/7 } else if (document.selection)
return txt; } function unbindEvents() { $("input[class*='bp_form_complete']").each(function(){ $(this).unbind(); }); } function submit_annotation() { $.post("/annotations", $("#new_annotation input").serialize(), function() { load_curators(); }, "script"); return false; } $(function() { // rightClickMenu(); $("#new_annotation").bind("submit", submit_annotation); $("input#annotation_cancel").bind("click", function(){ $("#new-annotation").hide(); return false; }); $(".dataTable span").contextMenu({ menu: 'annotation-menu' }, function(ontology, el, pos) { var txt = getSelectedText(); if (txt != '') { hash = getSelectedInformation(txt, el); $('#new-annotation').css({top: (pos.docY-125), left: (pos.docX-250)}); ontology_class = "bp_form_complete-"+ontology+"-shortid"; $("input#annotation_ncbo_term_id").removeClass(); $("input#annotation_ncbo_term_id").addClass(ontology_class); unbindEvents(); setup_functions(); $("input#annotation_ncbo_term_id").val(hash.text); $("input#annotation_ncbo_id").val(ontology); $("input#annotation_from").val(hash.from); $("input#annotation_to").val(hash.to); $("input#annotation_field_name").val(hash.field_name); $("#new-annotation").show(); $("input#annotation_ncbo_term_id").focus(); $("input#annotation_ncbo_term_id").keydown(); } return false; }); });
{ txt = document.selection.createRange().text; }
conditional_block
ncbo-selection.js
function getSelectedInformation(txt, element) { txt = txt.toString(); text = jQuery.trim(txt); len = text.length; full = jQuery.trim($(element).text()); field_name = $(element).attr("id"); start = full.indexOf(text)+1; end = start+len-1; return {'from':start, 'to':end, 'text':text, 'field_name':field_name}; } function displayResult(data) { $("#annotation-result").removeClass(); $("#annotation-result").addClass(data.status); $("#annotation-result").text(data.message); $("#annotation-result").fadeIn("slow").fadeTo(2000, 1).fadeOut("slow"); $(".annotation-table:not(:has(a))").hide(); $(".annotation-table:has(a)").show(); bindCurate(); bindRightClicks(); } function getSelectedText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); // FireFox } else if (document.getSelection) { txt = document.getSelection(); // IE 6/7 } else if (document.selection) { txt = document.selection.createRange().text; } return txt; } function unbindEvents() { $("input[class*='bp_form_complete']").each(function(){ $(this).unbind(); }); } function
() { $.post("/annotations", $("#new_annotation input").serialize(), function() { load_curators(); }, "script"); return false; } $(function() { // rightClickMenu(); $("#new_annotation").bind("submit", submit_annotation); $("input#annotation_cancel").bind("click", function(){ $("#new-annotation").hide(); return false; }); $(".dataTable span").contextMenu({ menu: 'annotation-menu' }, function(ontology, el, pos) { var txt = getSelectedText(); if (txt != '') { hash = getSelectedInformation(txt, el); $('#new-annotation').css({top: (pos.docY-125), left: (pos.docX-250)}); ontology_class = "bp_form_complete-"+ontology+"-shortid"; $("input#annotation_ncbo_term_id").removeClass(); $("input#annotation_ncbo_term_id").addClass(ontology_class); unbindEvents(); setup_functions(); $("input#annotation_ncbo_term_id").val(hash.text); $("input#annotation_ncbo_id").val(ontology); $("input#annotation_from").val(hash.from); $("input#annotation_to").val(hash.to); $("input#annotation_field_name").val(hash.field_name); $("#new-annotation").show(); $("input#annotation_ncbo_term_id").focus(); $("input#annotation_ncbo_term_id").keydown(); } return false; }); });
submit_annotation
identifier_name
ncbo-selection.js
function getSelectedInformation(txt, element) { txt = txt.toString(); text = jQuery.trim(txt); len = text.length; full = jQuery.trim($(element).text()); field_name = $(element).attr("id"); start = full.indexOf(text)+1; end = start+len-1; return {'from':start, 'to':end, 'text':text, 'field_name':field_name}; } function displayResult(data) { $("#annotation-result").removeClass(); $("#annotation-result").addClass(data.status); $("#annotation-result").text(data.message); $("#annotation-result").fadeIn("slow").fadeTo(2000, 1).fadeOut("slow"); $(".annotation-table:not(:has(a))").hide(); $(".annotation-table:has(a)").show(); bindCurate(); bindRightClicks(); }
var txt = ''; if (window.getSelection) { txt = window.getSelection(); // FireFox } else if (document.getSelection) { txt = document.getSelection(); // IE 6/7 } else if (document.selection) { txt = document.selection.createRange().text; } return txt; } function unbindEvents() { $("input[class*='bp_form_complete']").each(function(){ $(this).unbind(); }); } function submit_annotation() { $.post("/annotations", $("#new_annotation input").serialize(), function() { load_curators(); }, "script"); return false; } $(function() { // rightClickMenu(); $("#new_annotation").bind("submit", submit_annotation); $("input#annotation_cancel").bind("click", function(){ $("#new-annotation").hide(); return false; }); $(".dataTable span").contextMenu({ menu: 'annotation-menu' }, function(ontology, el, pos) { var txt = getSelectedText(); if (txt != '') { hash = getSelectedInformation(txt, el); $('#new-annotation').css({top: (pos.docY-125), left: (pos.docX-250)}); ontology_class = "bp_form_complete-"+ontology+"-shortid"; $("input#annotation_ncbo_term_id").removeClass(); $("input#annotation_ncbo_term_id").addClass(ontology_class); unbindEvents(); setup_functions(); $("input#annotation_ncbo_term_id").val(hash.text); $("input#annotation_ncbo_id").val(ontology); $("input#annotation_from").val(hash.from); $("input#annotation_to").val(hash.to); $("input#annotation_field_name").val(hash.field_name); $("#new-annotation").show(); $("input#annotation_ncbo_term_id").focus(); $("input#annotation_ncbo_term_id").keydown(); } return false; }); });
function getSelectedText() {
random_line_split
test_connect_combo_selection.py
import pytest import numpy as np from qtpy import QtWidgets from echo.core import CallbackProperty from echo.selection import SelectionCallbackProperty, ChoiceSeparator from echo.qt.connect import connect_combo_selection class Example(object):
def test_connect_combo_selection(): t = Example() a_prop = getattr(type(t), 'a') a_prop.set_choices(t, [4, 3.5]) a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x)) combo = QtWidgets.QComboBox() c1 = connect_combo_selection(t, 'a', combo) # noqa assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 3.5 combo.setCurrentIndex(1) assert t.a == 3.5 combo.setCurrentIndex(0) assert t.a == 4 combo.setCurrentIndex(-1) assert t.a is None t.a = 3.5 assert combo.currentIndex() == 1 t.a = 4 assert combo.currentIndex() == 0 with pytest.raises(ValueError) as exc: t.a = 2 assert exc.value.args[0] == 'value 2 is not in valid choices: [4, 3.5]' t.a = None assert combo.currentIndex() == -1 # Changing choices should change Qt combo box. Let's first try with a case # in which there is a matching data value in the new combo box t.a = 3.5 assert combo.currentIndex() == 1 a_prop.set_choices(t, (4, 5, 3.5)) assert combo.count() == 3 assert t.a == 3.5 assert combo.currentIndex() == 2 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 3.5 # Now we change the choices so that there is no matching data - in this case # the index should change to that given by default_index a_prop.set_choices(t, (4, 5, 6)) assert t.a == 5 assert combo.currentIndex() == 1 assert combo.count() == 3 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 6' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 6 # Finally, if there are too few choices for the default_index to be valid, # pick the last item in the combo a_prop.set_choices(t, (9,)) assert t.a == 9 assert combo.currentIndex() == 0 assert combo.count() == 1 assert combo.itemText(0) == 'value: 9' assert combo.itemData(0).data == 9 # Now just make sure that ChoiceSeparator works separator = ChoiceSeparator('header') a_prop.set_choices(t, (separator, 1, 2)) assert combo.count() == 3 assert combo.itemText(0) == 'header' assert combo.itemData(0).data is separator # And setting choices to an empty iterable shouldn't cause issues a_prop.set_choices(t, ()) assert combo.count() == 0 # Try including an array in the choices a_prop.set_choices(t, (4, 5, np.array([1, 2, 3]))) def test_connect_combo_selection_invalid(): t = Example() combo = QtWidgets.QComboBox() with pytest.raises(TypeError) as exc: connect_combo_selection(t, 'b', combo) assert exc.value.args[0] == 'connect_combo_selection requires a SelectionCallbackProperty'
a = SelectionCallbackProperty(default_index=1) b = CallbackProperty()
identifier_body
test_connect_combo_selection.py
import pytest import numpy as np from qtpy import QtWidgets from echo.core import CallbackProperty from echo.selection import SelectionCallbackProperty, ChoiceSeparator from echo.qt.connect import connect_combo_selection class Example(object): a = SelectionCallbackProperty(default_index=1) b = CallbackProperty() def
(): t = Example() a_prop = getattr(type(t), 'a') a_prop.set_choices(t, [4, 3.5]) a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x)) combo = QtWidgets.QComboBox() c1 = connect_combo_selection(t, 'a', combo) # noqa assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 3.5 combo.setCurrentIndex(1) assert t.a == 3.5 combo.setCurrentIndex(0) assert t.a == 4 combo.setCurrentIndex(-1) assert t.a is None t.a = 3.5 assert combo.currentIndex() == 1 t.a = 4 assert combo.currentIndex() == 0 with pytest.raises(ValueError) as exc: t.a = 2 assert exc.value.args[0] == 'value 2 is not in valid choices: [4, 3.5]' t.a = None assert combo.currentIndex() == -1 # Changing choices should change Qt combo box. Let's first try with a case # in which there is a matching data value in the new combo box t.a = 3.5 assert combo.currentIndex() == 1 a_prop.set_choices(t, (4, 5, 3.5)) assert combo.count() == 3 assert t.a == 3.5 assert combo.currentIndex() == 2 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 3.5 # Now we change the choices so that there is no matching data - in this case # the index should change to that given by default_index a_prop.set_choices(t, (4, 5, 6)) assert t.a == 5 assert combo.currentIndex() == 1 assert combo.count() == 3 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 6' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 6 # Finally, if there are too few choices for the default_index to be valid, # pick the last item in the combo a_prop.set_choices(t, (9,)) assert t.a == 9 assert combo.currentIndex() == 0 assert combo.count() == 1 assert combo.itemText(0) == 'value: 9' assert combo.itemData(0).data == 9 # Now just make sure that ChoiceSeparator works separator = ChoiceSeparator('header') a_prop.set_choices(t, (separator, 1, 2)) assert combo.count() == 3 assert combo.itemText(0) == 'header' assert combo.itemData(0).data is separator # And setting choices to an empty iterable shouldn't cause issues a_prop.set_choices(t, ()) assert combo.count() == 0 # Try including an array in the choices a_prop.set_choices(t, (4, 5, np.array([1, 2, 3]))) def test_connect_combo_selection_invalid(): t = Example() combo = QtWidgets.QComboBox() with pytest.raises(TypeError) as exc: connect_combo_selection(t, 'b', combo) assert exc.value.args[0] == 'connect_combo_selection requires a SelectionCallbackProperty'
test_connect_combo_selection
identifier_name
test_connect_combo_selection.py
import pytest import numpy as np
from echo.selection import SelectionCallbackProperty, ChoiceSeparator from echo.qt.connect import connect_combo_selection class Example(object): a = SelectionCallbackProperty(default_index=1) b = CallbackProperty() def test_connect_combo_selection(): t = Example() a_prop = getattr(type(t), 'a') a_prop.set_choices(t, [4, 3.5]) a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x)) combo = QtWidgets.QComboBox() c1 = connect_combo_selection(t, 'a', combo) # noqa assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 3.5 combo.setCurrentIndex(1) assert t.a == 3.5 combo.setCurrentIndex(0) assert t.a == 4 combo.setCurrentIndex(-1) assert t.a is None t.a = 3.5 assert combo.currentIndex() == 1 t.a = 4 assert combo.currentIndex() == 0 with pytest.raises(ValueError) as exc: t.a = 2 assert exc.value.args[0] == 'value 2 is not in valid choices: [4, 3.5]' t.a = None assert combo.currentIndex() == -1 # Changing choices should change Qt combo box. Let's first try with a case # in which there is a matching data value in the new combo box t.a = 3.5 assert combo.currentIndex() == 1 a_prop.set_choices(t, (4, 5, 3.5)) assert combo.count() == 3 assert t.a == 3.5 assert combo.currentIndex() == 2 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 3.5' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 3.5 # Now we change the choices so that there is no matching data - in this case # the index should change to that given by default_index a_prop.set_choices(t, (4, 5, 6)) assert t.a == 5 assert combo.currentIndex() == 1 assert combo.count() == 3 assert combo.itemText(0) == 'value: 4' assert combo.itemText(1) == 'value: 5' assert combo.itemText(2) == 'value: 6' assert combo.itemData(0).data == 4 assert combo.itemData(1).data == 5 assert combo.itemData(2).data == 6 # Finally, if there are too few choices for the default_index to be valid, # pick the last item in the combo a_prop.set_choices(t, (9,)) assert t.a == 9 assert combo.currentIndex() == 0 assert combo.count() == 1 assert combo.itemText(0) == 'value: 9' assert combo.itemData(0).data == 9 # Now just make sure that ChoiceSeparator works separator = ChoiceSeparator('header') a_prop.set_choices(t, (separator, 1, 2)) assert combo.count() == 3 assert combo.itemText(0) == 'header' assert combo.itemData(0).data is separator # And setting choices to an empty iterable shouldn't cause issues a_prop.set_choices(t, ()) assert combo.count() == 0 # Try including an array in the choices a_prop.set_choices(t, (4, 5, np.array([1, 2, 3]))) def test_connect_combo_selection_invalid(): t = Example() combo = QtWidgets.QComboBox() with pytest.raises(TypeError) as exc: connect_combo_selection(t, 'b', combo) assert exc.value.args[0] == 'connect_combo_selection requires a SelectionCallbackProperty'
from qtpy import QtWidgets from echo.core import CallbackProperty
random_line_split
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } }
test_variants!(); test_variants2!(); }
x!(test_variants, test_variants2, MyEnum, Variant); pub fn check_variants() {
random_line_split
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } } x!(test_variants, test_variants2, MyEnum, Variant); pub fn
() { test_variants!(); test_variants2!(); }
check_variants
identifier_name
variants.rs
#![feature(decl_macro)] #[rustfmt::skip] macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) { #[repr(u8)] pub enum $type_name { Variant = 0, $variant_name = 1, } #[macro_export] macro_rules! $macro_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}; } pub macro $macro2_name { () => {{ assert_eq!($type_name::Variant as u8, 0); assert_eq!($type_name::$variant_name as u8, 1); assert_eq!(<$type_name>::Variant as u8, 0); assert_eq!(<$type_name>::$variant_name as u8, 1); }}, } } x!(test_variants, test_variants2, MyEnum, Variant); pub fn check_variants()
{ test_variants!(); test_variants2!(); }
identifier_body
test_preparers.py
import unittest from restkiss.preparers import Preparer, FieldsPreparer class InstaObj(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class LookupDataTestCase(unittest.TestCase): def setUp(self): super(LookupDataTestCase, self).setUp() self.preparer = FieldsPreparer(fields=None) self.obj_data = InstaObj( say='what', count=453, moof={ 'buried': { 'id': 7, 'data': InstaObj(yes='no') } }, parent=None ) self.dict_data = { 'hello': 'world', 'abc': 123, 'more': { 'things': 'here', 'nested': InstaObj( awesome=True, depth=3 ), }, 'parent': None, } def test_dict_simple(self): self.assertEqual(self.preparer.lookup_data('hello', self.dict_data), 'world') self.assertEqual(self.preparer.lookup_data('abc', self.dict_data), 123) def test_obj_simple(self): self.assertEqual(self.preparer.lookup_data('say', self.obj_data), 'what') self.assertEqual(self.preparer.lookup_data('count', self.obj_data), 453) def test_dict_nested(self): self.assertEqual(self.preparer.lookup_data('more.things', self.dict_data), 'here') self.assertEqual(self.preparer.lookup_data('more.nested.depth', self.dict_data), 3) def test_obj_nested(self): self.assertEqual(self.preparer.lookup_data('moof.buried.id', self.obj_data), 7) self.assertEqual(self.preparer.lookup_data('moof.buried.data.yes', self.obj_data), 'no')
with self.assertRaises(AttributeError): self.preparer.lookup_data('whee', self.obj_data) def test_dict_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.dict_data), None) def test_obj_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.obj_data), None) def test_empty_lookup(self): # We could possibly get here in the recursion. self.assertEqual(self.preparer.lookup_data('', 'Last value'), 'Last value') def test_complex_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('more.nested.nope', self.dict_data)
def test_dict_miss(self): with self.assertRaises(KeyError): self.preparer.lookup_data('another', self.dict_data) def test_obj_miss(self):
random_line_split
test_preparers.py
import unittest from restkiss.preparers import Preparer, FieldsPreparer class InstaObj(object): def __init__(self, **kwargs): for k, v in kwargs.items():
class LookupDataTestCase(unittest.TestCase): def setUp(self): super(LookupDataTestCase, self).setUp() self.preparer = FieldsPreparer(fields=None) self.obj_data = InstaObj( say='what', count=453, moof={ 'buried': { 'id': 7, 'data': InstaObj(yes='no') } }, parent=None ) self.dict_data = { 'hello': 'world', 'abc': 123, 'more': { 'things': 'here', 'nested': InstaObj( awesome=True, depth=3 ), }, 'parent': None, } def test_dict_simple(self): self.assertEqual(self.preparer.lookup_data('hello', self.dict_data), 'world') self.assertEqual(self.preparer.lookup_data('abc', self.dict_data), 123) def test_obj_simple(self): self.assertEqual(self.preparer.lookup_data('say', self.obj_data), 'what') self.assertEqual(self.preparer.lookup_data('count', self.obj_data), 453) def test_dict_nested(self): self.assertEqual(self.preparer.lookup_data('more.things', self.dict_data), 'here') self.assertEqual(self.preparer.lookup_data('more.nested.depth', self.dict_data), 3) def test_obj_nested(self): self.assertEqual(self.preparer.lookup_data('moof.buried.id', self.obj_data), 7) self.assertEqual(self.preparer.lookup_data('moof.buried.data.yes', self.obj_data), 'no') def test_dict_miss(self): with self.assertRaises(KeyError): self.preparer.lookup_data('another', self.dict_data) def test_obj_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('whee', self.obj_data) def test_dict_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.dict_data), None) def test_obj_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.obj_data), None) def test_empty_lookup(self): # We could possibly get here in the recursion. self.assertEqual(self.preparer.lookup_data('', 'Last value'), 'Last value') def test_complex_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('more.nested.nope', self.dict_data)
setattr(self, k, v)
conditional_block
test_preparers.py
import unittest from restkiss.preparers import Preparer, FieldsPreparer class InstaObj(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class LookupDataTestCase(unittest.TestCase): def setUp(self): super(LookupDataTestCase, self).setUp() self.preparer = FieldsPreparer(fields=None) self.obj_data = InstaObj( say='what', count=453, moof={ 'buried': { 'id': 7, 'data': InstaObj(yes='no') } }, parent=None ) self.dict_data = { 'hello': 'world', 'abc': 123, 'more': { 'things': 'here', 'nested': InstaObj( awesome=True, depth=3 ), }, 'parent': None, } def test_dict_simple(self): self.assertEqual(self.preparer.lookup_data('hello', self.dict_data), 'world') self.assertEqual(self.preparer.lookup_data('abc', self.dict_data), 123) def test_obj_simple(self): self.assertEqual(self.preparer.lookup_data('say', self.obj_data), 'what') self.assertEqual(self.preparer.lookup_data('count', self.obj_data), 453) def test_dict_nested(self): self.assertEqual(self.preparer.lookup_data('more.things', self.dict_data), 'here') self.assertEqual(self.preparer.lookup_data('more.nested.depth', self.dict_data), 3) def test_obj_nested(self): self.assertEqual(self.preparer.lookup_data('moof.buried.id', self.obj_data), 7) self.assertEqual(self.preparer.lookup_data('moof.buried.data.yes', self.obj_data), 'no') def test_dict_miss(self): with self.assertRaises(KeyError): self.preparer.lookup_data('another', self.dict_data) def test_obj_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('whee', self.obj_data) def test_dict_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.dict_data), None) def test_obj_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.obj_data), None) def test_empty_lookup(self): # We could possibly get here in the recursion. self.assertEqual(self.preparer.lookup_data('', 'Last value'), 'Last value') def test_complex_miss(self):
with self.assertRaises(AttributeError): self.preparer.lookup_data('more.nested.nope', self.dict_data)
identifier_body
test_preparers.py
import unittest from restkiss.preparers import Preparer, FieldsPreparer class InstaObj(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class LookupDataTestCase(unittest.TestCase): def setUp(self): super(LookupDataTestCase, self).setUp() self.preparer = FieldsPreparer(fields=None) self.obj_data = InstaObj( say='what', count=453, moof={ 'buried': { 'id': 7, 'data': InstaObj(yes='no') } }, parent=None ) self.dict_data = { 'hello': 'world', 'abc': 123, 'more': { 'things': 'here', 'nested': InstaObj( awesome=True, depth=3 ), }, 'parent': None, } def test_dict_simple(self): self.assertEqual(self.preparer.lookup_data('hello', self.dict_data), 'world') self.assertEqual(self.preparer.lookup_data('abc', self.dict_data), 123) def
(self): self.assertEqual(self.preparer.lookup_data('say', self.obj_data), 'what') self.assertEqual(self.preparer.lookup_data('count', self.obj_data), 453) def test_dict_nested(self): self.assertEqual(self.preparer.lookup_data('more.things', self.dict_data), 'here') self.assertEqual(self.preparer.lookup_data('more.nested.depth', self.dict_data), 3) def test_obj_nested(self): self.assertEqual(self.preparer.lookup_data('moof.buried.id', self.obj_data), 7) self.assertEqual(self.preparer.lookup_data('moof.buried.data.yes', self.obj_data), 'no') def test_dict_miss(self): with self.assertRaises(KeyError): self.preparer.lookup_data('another', self.dict_data) def test_obj_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('whee', self.obj_data) def test_dict_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.dict_data), None) def test_obj_nullable_fk(self): self.assertEqual(self.preparer.lookup_data('parent.id', self.obj_data), None) def test_empty_lookup(self): # We could possibly get here in the recursion. self.assertEqual(self.preparer.lookup_data('', 'Last value'), 'Last value') def test_complex_miss(self): with self.assertRaises(AttributeError): self.preparer.lookup_data('more.nested.nope', self.dict_data)
test_obj_simple
identifier_name
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self { W(writer) } } #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> {
self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
#[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W {
random_line_split
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn
(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self { W(writer) } } #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
deref_mut
identifier_name
dsv2.rs
#[doc = "Register `DSV2` reader"] pub struct R(crate::R<DSV2_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DSV2_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DSV2_SPEC>) -> Self { R(reader) } } #[doc = "Register `DSV2` writer"] pub struct W(crate::W<DSV2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<DSV2_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<DSV2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<DSV2_SPEC>) -> Self
} #[doc = "Field `DSV2` reader - DAC reference value 2"] pub struct DSV2_R(crate::FieldReader<u16, u16>); impl DSV2_R { pub(crate) fn new(bits: u16) -> Self { DSV2_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DSV2_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DSV2` writer - DAC reference value 2"] pub struct DSV2_W<'a> { w: &'a mut W, } impl<'a> DSV2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff); self.w } } impl R { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&self) -> DSV2_R { DSV2_R::new((self.bits & 0x03ff) as u16) } } impl W { #[doc = "Bits 0:9 - DAC reference value 2"] #[inline(always)] pub fn dsv2(&mut self) -> DSV2_W { DSV2_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "DAC reference value 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dsv2](index.html) module"] pub struct DSV2_SPEC; impl crate::RegisterSpec for DSV2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [dsv2::R](R) reader structure"] impl crate::Readable for DSV2_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [dsv2::W](W) writer structure"] impl crate::Writable for DSV2_SPEC { type Writer = W; } #[doc = "`reset()` method sets DSV2 to value 0"] impl crate::Resettable for DSV2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
{ W(writer) }
identifier_body
models.py
from django.db import models from django.contrib.auth.models import User class OrganisationType(models.Model): type_desc = models.CharField(max_length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.CharField(max_length=10) province = models.CharField(max_length=100) nationality = models.CharField(max_length=100) def __unicode__(self): return self.street_address + ',' + self.city class HattiUser(models.Model): user = models.OneToOneField(User) address = models.ForeignKey(Address) telephone = models.CharField(max_length=500) date_joined = models.DateTimeField(auto_now_add=True) fax = models.CharField(max_length=100) avatar = models.CharField(max_length=100, null=True, blank=True) tagline = models.CharField(max_length=140) class Meta: abstract = True class
(HattiUser): title = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def __unicode__(self): return self.title class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return unicode(self.user)
AdminOrganisations
identifier_name
models.py
from django.db import models from django.contrib.auth.models import User class OrganisationType(models.Model): type_desc = models.CharField(max_length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.CharField(max_length=10) province = models.CharField(max_length=100) nationality = models.CharField(max_length=100) def __unicode__(self): return self.street_address + ',' + self.city class HattiUser(models.Model): user = models.OneToOneField(User) address = models.ForeignKey(Address) telephone = models.CharField(max_length=500) date_joined = models.DateTimeField(auto_now_add=True) fax = models.CharField(max_length=100) avatar = models.CharField(max_length=100, null=True, blank=True) tagline = models.CharField(max_length=140) class Meta: abstract = True class AdminOrganisations(HattiUser): title = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def __unicode__(self):
class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return unicode(self.user)
return self.title
identifier_body
models.py
from django.db import models from django.contrib.auth.models import User class OrganisationType(models.Model): type_desc = models.CharField(max_length=200) def __unicode__(self): return self.type_desc class Address(models.Model): street_address = models.CharField(max_length=100) city = models.CharField(max_length=100) pin = models.CharField(max_length=10) province = models.CharField(max_length=100) nationality = models.CharField(max_length=100) def __unicode__(self): return self.street_address + ',' + self.city class HattiUser(models.Model): user = models.OneToOneField(User) address = models.ForeignKey(Address) telephone = models.CharField(max_length=500) date_joined = models.DateTimeField(auto_now_add=True) fax = models.CharField(max_length=100) avatar = models.CharField(max_length=100, null=True, blank=True) tagline = models.CharField(max_length=140) class Meta: abstract = True
class AdminOrganisations(HattiUser): title = models.CharField(max_length=200) organisation_type = models.ForeignKey(OrganisationType) def __unicode__(self): return self.title class Customer(HattiUser): title = models.CharField(max_length=200, blank=True, null=True) is_org = models.BooleanField(); org_type = models.ForeignKey(OrganisationType) company = models.CharField(max_length = 200) def __unicode__(self, arg): return unicode(self.user)
random_line_split
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum
{ /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35 .. 0] we always have [0 .. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } } // If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum != _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum != _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum != _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else { buf[i as usize] = value2ascii(0); i -= 1; } } } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if !exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if !exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
SignFormat
identifier_name
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum SignFormat { /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35 .. 0] we always have [0 .. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } } // If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum != _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum != _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum != _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else
} } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if !exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if !exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
{ buf[i as usize] = value2ascii(0); i -= 1; }
conditional_block
float.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(missing_docs)] pub use self::ExponentFormat::*; pub use self::SignificantDigits::*; pub use self::SignFormat::*; use char; use char::CharExt; use fmt; use iter::Iterator; use num::{cast, Float, ToPrimitive}; use num::FpCategory as Fp; use ops::FnOnce; use result::Result::Ok; use slice::{self, SliceExt}; use str::{self, StrExt}; /// A flag that specifies whether to use exponential (scientific) notation. pub enum ExponentFormat { /// Do not use exponential notation. ExpNone, /// Use exponential notation with the exponent having a base of 10 and the /// exponent sign being `e` or `E`. For example, 1000 would be printed /// 1e3. ExpDec } /// The number of digits used for emitting the fractional part of a number, if /// any. pub enum SignificantDigits { /// At most the given number of digits will be printed, truncating any /// trailing zeroes. DigMax(usize), /// Precisely the given number of digits will be printed. DigExact(usize) } /// How to emit the sign of a number. pub enum SignFormat { /// `-` will be printed for negative values, but no sign will be emitted /// for positive numbers. SignNeg } const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11; /// Converts a number to its string representation as a byte vector. /// This is meant to be a common base implementation for all numeric string /// conversion functions like `to_string()` or `to_str_radix()`. /// /// # Arguments /// /// - `num` - The number to convert. Accepts any number that /// implements the numeric traits. /// - `radix` - Base to use. Accepts only the values 2-36. If the exponential notation /// is used, then this base is only used for the significand. The exponent /// itself always printed using a base of 10. /// - `negative_zero` - Whether to treat the special value `-0` as /// `-0` or as `+0`. /// - `sign` - How to emit the sign. See `SignFormat`. /// - `digits` - The amount of digits to use for emitting the fractional /// part, if any. See `SignificantDigits`. /// - `exp_format` - Whether or not to use the exponential (scientific) notation. /// See `ExponentFormat`. /// - `exp_capital` - Whether or not to use a capital letter for the exponent sign, if /// exponential notation is desired. /// - `f` - A closure to invoke with the bytes representing the /// float. /// /// # Panics /// /// - Panics if `radix` < 2 or `radix` > 36. /// - Panics if `radix` > 14 and `exp_format` is `ExpDec` due to conflict /// between digit and exponent sign `'e'`. /// - Panics if `radix` > 25 and `exp_format` is `ExpBin` due to conflict /// between digit and exponent sign `'p'`. pub fn float_to_str_bytes_common<T: Float, U, F>( num: T, radix: u32, negative_zero: bool, sign: SignFormat, digits: SignificantDigits, exp_format: ExponentFormat, exp_upper: bool, f: F ) -> U where F: FnOnce(&str) -> U, { assert!(2 <= radix && radix <= 36); match exp_format { ExpDec if radix >= DIGIT_E_RADIX // decimal exponent 'e' => panic!("float_to_str_bytes_common: radix {} incompatible with \ use of 'e' as decimal exponent", radix), _ => () } let _0: T = Float::zero(); let _1: T = Float::one(); match num.classify() { Fp::Nan => return f("NaN"), Fp::Infinite if num > _0 => { return f("inf"); } Fp::Infinite if num < _0 => { return f("-inf"); } _ => {} } let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity()); // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so // we may have up to that many digits. Give ourselves some extra wiggle room // otherwise as well. let mut buf = [0; 1536]; let mut end = 0; let radix_gen: T = cast(radix as isize).unwrap(); let (num, exp) = match exp_format { ExpNone => (num, 0), ExpDec if num == _0 => (num, 0), ExpDec => { let (exp, exp_base) = match exp_format { ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()), ExpNone => panic!("unreachable"), }; (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap()) } }; // First emit the non-fractional part, looping at least once to make // sure at least a `0` gets emitted. let mut deccum = num.trunc(); loop { // Calculate the absolute value of each digit instead of only // doing it once for the whole number because a // representable negative number doesn't necessary have an // representable additive inverse of the same type // (See twos complement). But we assume that for the // numbers [-35 .. 0] we always have [0 .. 35]. let current_digit = (deccum % radix_gen).abs(); // Decrease the deccumulator one digit at a time deccum = deccum / radix_gen; deccum = deccum.trunc(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // No more digits to calculate for the non-fractional part -> break if deccum == _0 { break; } }
// If limited digits, calculate one digit more for rounding. let (limit_digits, digit_count, exact) = match digits { DigMax(count) => (true, count + 1, false), DigExact(count) => (true, count + 1, true) }; // Decide what sign to put in front match sign { SignNeg if neg => { buf[end] = b'-'; end += 1; } _ => () } buf[..end].reverse(); // Remember start of the fractional digits. // Points one beyond end of buf if none get generated, // or at the '.' otherwise. let start_fractional_digits = end; // Now emit the fractional part, if any deccum = num.fract(); if deccum != _0 || (limit_digits && exact && digit_count > 0) { buf[end] = b'.'; end += 1; let mut dig = 0; // calculate new digits while // - there is no limit and there are digits left // - or there is a limit, it's not reached yet and // - it's exact // - or it's a maximum, and there are still digits left while (!limit_digits && deccum != _0) || (limit_digits && dig < digit_count && ( exact || (!exact && deccum != _0) ) ) { // Shift first fractional digit into the integer part deccum = deccum * radix_gen; // Calculate the absolute value of each digit. // See note in first loop. let current_digit = deccum.trunc().abs(); let c = char::from_digit(current_digit.to_isize().unwrap() as u32, radix); buf[end] = c.unwrap() as u8; end += 1; // Decrease the deccumulator one fractional digit at a time deccum = deccum.fract(); dig += 1; } // If digits are limited, and that limit has been reached, // cut off the one extra digit, and depending on its value // round the remaining ones. if limit_digits && dig == digit_count { let ascii2value = |chr: u8| { (chr as char).to_digit(radix).unwrap() }; let value2ascii = |val: u32| { char::from_digit(val, radix).unwrap() as u8 }; let extra_digit = ascii2value(buf[end - 1]); end -= 1; if extra_digit >= radix / 2 { // -> need to round let mut i: isize = end as isize - 1; loop { // If reached left end of number, have to // insert additional digit: if i < 0 || buf[i as usize] == b'-' || buf[i as usize] == b'+' { for j in ((i + 1) as usize..end).rev() { buf[j + 1] = buf[j]; } buf[(i + 1) as usize] = value2ascii(1); end += 1; break; } // Skip the '.' if buf[i as usize] == b'.' { i -= 1; continue; } // Either increment the digit, // or set to 0 if max and carry the 1. let current_digit = ascii2value(buf[i as usize]); if current_digit < (radix - 1) { buf[i as usize] = value2ascii(current_digit+1); break; } else { buf[i as usize] = value2ascii(0); i -= 1; } } } } } // if number of digits is not exact, remove all trailing '0's up to // and including the '.' if !exact { let buf_max_i = end - 1; // index to truncate from let mut i = buf_max_i; // discover trailing zeros of fractional part while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { end = i + 1; } } } // If exact and trailing '.', just cut that else { let max_i = end - 1; if buf[max_i] == b'.' { end = max_i; } } match exp_format { ExpNone => {}, _ => { buf[end] = match exp_format { ExpDec if exp_upper => 'E', ExpDec if !exp_upper => 'e', _ => panic!("unreachable"), } as u8; end += 1; struct Filler<'a> { buf: &'a mut [u8], end: &'a mut usize, } impl<'a> fmt::Write for Filler<'a> { fn write_str(&mut self, s: &str) -> fmt::Result { slice::bytes::copy_memory(s.as_bytes(), &mut self.buf[(*self.end)..]); *self.end += s.len(); Ok(()) } } let mut filler = Filler { buf: &mut buf, end: &mut end }; match sign { SignNeg => { let _ = fmt::write(&mut filler, format_args!("{:-}", exp)); } } } } f(unsafe { str::from_utf8_unchecked(&buf[..end]) }) }
random_line_split
pyunit_wide_dataset_largeGLM.py
import sys sys.path.insert(1, "../../../") import h2o import numpy as np def wide_dataset_large(ip,port): print("Reading in Arcene training data for binomial modeling.") trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ') trainDataResponse = np.where(trainDataResponse == -1, 0, 1) trainDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train.data"), delimiter=' ') trainData = h2o.H2OFrame(np.column_stack((trainDataResponse, trainDataFeatures)).tolist()) print("Run model on 3250 columns of Arcene with strong rules off.") model = h2o.glm(x=trainData[1:3250], y=trainData[0].asfactor(), family="binomial", lambda_search=False, alpha=[1]) print("Test model on validation set.") validDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid_labels.labels"), delimiter=' ') validDataResponse = np.where(validDataResponse == -1, 0, 1) validDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid.data"), delimiter=' ') validData = h2o.H2OFrame(np.column_stack((validDataResponse, validDataFeatures)).tolist()) prediction = model.predict(validData) print("Check performance of predictions.") performance = model.model_performance(validData)
print("Check that prediction AUC better than guessing (0.5).") assert performance.auc() > 0.5, "predictions should be better then pure chance" if __name__ == "__main__": h2o.run_test(sys.argv, wide_dataset_large)
random_line_split
pyunit_wide_dataset_largeGLM.py
import sys sys.path.insert(1, "../../../") import h2o import numpy as np def wide_dataset_large(ip,port): print("Reading in Arcene training data for binomial modeling.") trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ') trainDataResponse = np.where(trainDataResponse == -1, 0, 1) trainDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train.data"), delimiter=' ') trainData = h2o.H2OFrame(np.column_stack((trainDataResponse, trainDataFeatures)).tolist()) print("Run model on 3250 columns of Arcene with strong rules off.") model = h2o.glm(x=trainData[1:3250], y=trainData[0].asfactor(), family="binomial", lambda_search=False, alpha=[1]) print("Test model on validation set.") validDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid_labels.labels"), delimiter=' ') validDataResponse = np.where(validDataResponse == -1, 0, 1) validDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid.data"), delimiter=' ') validData = h2o.H2OFrame(np.column_stack((validDataResponse, validDataFeatures)).tolist()) prediction = model.predict(validData) print("Check performance of predictions.") performance = model.model_performance(validData) print("Check that prediction AUC better than guessing (0.5).") assert performance.auc() > 0.5, "predictions should be better then pure chance" if __name__ == "__main__":
h2o.run_test(sys.argv, wide_dataset_large)
conditional_block
pyunit_wide_dataset_largeGLM.py
import sys sys.path.insert(1, "../../../") import h2o import numpy as np def wide_dataset_large(ip,port):
if __name__ == "__main__": h2o.run_test(sys.argv, wide_dataset_large)
print("Reading in Arcene training data for binomial modeling.") trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ') trainDataResponse = np.where(trainDataResponse == -1, 0, 1) trainDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train.data"), delimiter=' ') trainData = h2o.H2OFrame(np.column_stack((trainDataResponse, trainDataFeatures)).tolist()) print("Run model on 3250 columns of Arcene with strong rules off.") model = h2o.glm(x=trainData[1:3250], y=trainData[0].asfactor(), family="binomial", lambda_search=False, alpha=[1]) print("Test model on validation set.") validDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid_labels.labels"), delimiter=' ') validDataResponse = np.where(validDataResponse == -1, 0, 1) validDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid.data"), delimiter=' ') validData = h2o.H2OFrame(np.column_stack((validDataResponse, validDataFeatures)).tolist()) prediction = model.predict(validData) print("Check performance of predictions.") performance = model.model_performance(validData) print("Check that prediction AUC better than guessing (0.5).") assert performance.auc() > 0.5, "predictions should be better then pure chance"
identifier_body
pyunit_wide_dataset_largeGLM.py
import sys sys.path.insert(1, "../../../") import h2o import numpy as np def
(ip,port): print("Reading in Arcene training data for binomial modeling.") trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ') trainDataResponse = np.where(trainDataResponse == -1, 0, 1) trainDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train.data"), delimiter=' ') trainData = h2o.H2OFrame(np.column_stack((trainDataResponse, trainDataFeatures)).tolist()) print("Run model on 3250 columns of Arcene with strong rules off.") model = h2o.glm(x=trainData[1:3250], y=trainData[0].asfactor(), family="binomial", lambda_search=False, alpha=[1]) print("Test model on validation set.") validDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid_labels.labels"), delimiter=' ') validDataResponse = np.where(validDataResponse == -1, 0, 1) validDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_valid.data"), delimiter=' ') validData = h2o.H2OFrame(np.column_stack((validDataResponse, validDataFeatures)).tolist()) prediction = model.predict(validData) print("Check performance of predictions.") performance = model.model_performance(validData) print("Check that prediction AUC better than guessing (0.5).") assert performance.auc() > 0.5, "predictions should be better then pure chance" if __name__ == "__main__": h2o.run_test(sys.argv, wide_dataset_large)
wide_dataset_large
identifier_name
other.py
""" pygments.lexers.other ~~~~~~~~~~~~~~~~~~~~~ Just export lexer classes previously contained in this module.
from pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \ TcshLexer from pygments.lexers.robotframework import RobotFrameworkLexer from pygments.lexers.testing import GherkinLexer from pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexer from pygments.lexers.prolog import LogtalkLexer from pygments.lexers.snobol import SnobolLexer from pygments.lexers.rebol import RebolLexer from pygments.lexers.configs import KconfigLexer, Cfengine3Lexer from pygments.lexers.modeling import ModelicaLexer from pygments.lexers.scripting import AppleScriptLexer, MOOCodeLexer, \ HybrisLexer from pygments.lexers.graphics import PostScriptLexer, GnuplotLexer, \ AsymptoteLexer, PovrayLexer from pygments.lexers.business import ABAPLexer, OpenEdgeLexer, \ GoodDataCLLexer, MaqlLexer from pygments.lexers.automation import AutoItLexer, AutohotkeyLexer from pygments.lexers.dsls import ProtoBufLexer, BroLexer, PuppetLexer, \ MscgenLexer, VGLLexer from pygments.lexers.basic import CbmBasicV2Lexer from pygments.lexers.pawn import SourcePawnLexer, PawnLexer from pygments.lexers.ecl import ECLLexer from pygments.lexers.urbi import UrbiscriptLexer from pygments.lexers.smalltalk import SmalltalkLexer, NewspeakLexer from pygments.lexers.installers import NSISLexer, RPMSpecLexer from pygments.lexers.textedit import AwkLexer from pygments.lexers.smv import NuSMVLexer __all__ = []
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexer
random_line_split
main.py
from prompt_toolkit import Application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import create_eventloop from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys from prompt_toolkit.buffer import Buffer, AcceptAction from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.layout.containers import VSplit, Window, HSplit from prompt_toolkit.layout.controls import BufferControl, FillControl, TokenListControl from prompt_toolkit.layout.dimension import LayoutDimension as D from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from pygments.token import Token def get_titlebar_tokens(cli): return [ (Token.Title, ' Hello world '), (Token.Title, ' (Press [Ctrl-Q] to quit.)'), ] def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. buffer.delete_before_cursor(len(text)) cli.focus(DEFAULT_BUFFER) # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. # self.leave_command_mode(append_to_history=True) # Execute command. buffers[DEFAULT_BUFFER].insert_text(text) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'PROMPT': Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory()), 'RESULT': Buffer(is_multiline=True), } def default_buffer_changed(cli): """ When the buffer on the left (DEFAULT_BUFFER) changes, update the buffer on the right. We just reverse the text. """
buffers[DEFAULT_BUFFER].on_text_changed += default_buffer_changed def get_bottom_toolbar_tokens(cli): return [(Token.Toolbar, ' This is a toolbar. ')] layout = VSplit([ Window(content=BufferControl( buffer_name=DEFAULT_BUFFER, focus_on_click=True)), Window(width=D.exact(1), content=FillControl('|', token=Token.Line)), Window(content=BufferControl(buffer_name='RESULT')) ]) layout = HSplit([ Window(height=D.exact(1), content=TokenListControl( get_titlebar_tokens, align_center=True )), Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), layout, Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), Window(height=D.exact(2), content=BufferControl( buffer_name='PROMPT', focus_on_click=True)), ]) loop = create_eventloop() manager = KeyBindingManager() registry = manager.registry @registry.add_binding(Keys.ControlQ, eager=True) def exit_(event): event.cli.set_return_value(None) application = Application(key_bindings_registry=registry, layout=layout, buffers=buffers, mouse_support=True, use_alternate_screen=True, editing_mode=EditingMode.VI ) cli = CommandLineInterface(application=application, eventloop=loop) cli.run() print("Exiting")
buffers['RESULT'].text = buffers[DEFAULT_BUFFER].text[::-1]
random_line_split
main.py
from prompt_toolkit import Application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import create_eventloop from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys from prompt_toolkit.buffer import Buffer, AcceptAction from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.layout.containers import VSplit, Window, HSplit from prompt_toolkit.layout.controls import BufferControl, FillControl, TokenListControl from prompt_toolkit.layout.dimension import LayoutDimension as D from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from pygments.token import Token def get_titlebar_tokens(cli): return [ (Token.Title, ' Hello world '), (Token.Title, ' (Press [Ctrl-Q] to quit.)'), ] def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. buffer.delete_before_cursor(len(text)) cli.focus(DEFAULT_BUFFER) # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. # self.leave_command_mode(append_to_history=True) # Execute command. buffers[DEFAULT_BUFFER].insert_text(text) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'PROMPT': Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory()), 'RESULT': Buffer(is_multiline=True), } def default_buffer_changed(cli): """ When the buffer on the left (DEFAULT_BUFFER) changes, update the buffer on the right. We just reverse the text. """ buffers['RESULT'].text = buffers[DEFAULT_BUFFER].text[::-1] buffers[DEFAULT_BUFFER].on_text_changed += default_buffer_changed def
(cli): return [(Token.Toolbar, ' This is a toolbar. ')] layout = VSplit([ Window(content=BufferControl( buffer_name=DEFAULT_BUFFER, focus_on_click=True)), Window(width=D.exact(1), content=FillControl('|', token=Token.Line)), Window(content=BufferControl(buffer_name='RESULT')) ]) layout = HSplit([ Window(height=D.exact(1), content=TokenListControl( get_titlebar_tokens, align_center=True )), Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), layout, Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), Window(height=D.exact(2), content=BufferControl( buffer_name='PROMPT', focus_on_click=True)), ]) loop = create_eventloop() manager = KeyBindingManager() registry = manager.registry @registry.add_binding(Keys.ControlQ, eager=True) def exit_(event): event.cli.set_return_value(None) application = Application(key_bindings_registry=registry, layout=layout, buffers=buffers, mouse_support=True, use_alternate_screen=True, editing_mode=EditingMode.VI ) cli = CommandLineInterface(application=application, eventloop=loop) cli.run() print("Exiting")
get_bottom_toolbar_tokens
identifier_name
main.py
from prompt_toolkit import Application from prompt_toolkit.interface import CommandLineInterface from prompt_toolkit.shortcuts import create_eventloop from prompt_toolkit.key_binding.manager import KeyBindingManager from prompt_toolkit.keys import Keys from prompt_toolkit.buffer import Buffer, AcceptAction from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode from prompt_toolkit.layout.containers import VSplit, Window, HSplit from prompt_toolkit.layout.controls import BufferControl, FillControl, TokenListControl from prompt_toolkit.layout.dimension import LayoutDimension as D from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from pygments.token import Token def get_titlebar_tokens(cli): return [ (Token.Title, ' Hello world '), (Token.Title, ' (Press [Ctrl-Q] to quit.)'), ] def handle_action(cli, buffer):
buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'PROMPT': Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory()), 'RESULT': Buffer(is_multiline=True), } def default_buffer_changed(cli): """ When the buffer on the left (DEFAULT_BUFFER) changes, update the buffer on the right. We just reverse the text. """ buffers['RESULT'].text = buffers[DEFAULT_BUFFER].text[::-1] buffers[DEFAULT_BUFFER].on_text_changed += default_buffer_changed def get_bottom_toolbar_tokens(cli): return [(Token.Toolbar, ' This is a toolbar. ')] layout = VSplit([ Window(content=BufferControl( buffer_name=DEFAULT_BUFFER, focus_on_click=True)), Window(width=D.exact(1), content=FillControl('|', token=Token.Line)), Window(content=BufferControl(buffer_name='RESULT')) ]) layout = HSplit([ Window(height=D.exact(1), content=TokenListControl( get_titlebar_tokens, align_center=True )), Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), layout, Window(height=D.exact(1), content=FillControl('-', token=Token.Line)), Window(height=D.exact(2), content=BufferControl( buffer_name='PROMPT', focus_on_click=True)), ]) loop = create_eventloop() manager = KeyBindingManager() registry = manager.registry @registry.add_binding(Keys.ControlQ, eager=True) def exit_(event): event.cli.set_return_value(None) application = Application(key_bindings_registry=registry, layout=layout, buffers=buffers, mouse_support=True, use_alternate_screen=True, editing_mode=EditingMode.VI ) cli = CommandLineInterface(application=application, eventloop=loop) cli.run() print("Exiting")
' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. buffer.delete_before_cursor(len(text)) cli.focus(DEFAULT_BUFFER) # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. # self.leave_command_mode(append_to_history=True) # Execute command. buffers[DEFAULT_BUFFER].insert_text(text)
identifier_body
db.py
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 2.1 of the License, or (at your option) any # later version. # # logilab-common is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. """Wrappers to get actually replaceable DBAPI2 compliant modules and database connection whatever the database and client lib used. Currently support: - postgresql (pgdb, psycopg, psycopg2, pyPgSQL) - mysql (MySQLdb) - sqlite (pysqlite2, sqlite, sqlite3) just use the `get_connection` function from this module to get a wrapped connection. If multiple drivers for a database are available, you can control which one you want to use using the `set_prefered_driver` function. Additional helpers are also provided for advanced functionalities such as listing existing users or databases, creating database... Get the helper for your database using the `get_adv_func_helper` function. """ __docformat__ = "restructuredtext en" from warnings import warn warn('this module is deprecated, use logilab.database instead', DeprecationWarning, stacklevel=1) from logilab.database import (get_connection, set_prefered_driver, get_dbapi_compliant_module as _gdcm, get_db_helper as _gdh) def
(driver, *args, **kwargs): module = _gdcm(driver, *args, **kwargs) module.adv_func_helper = _gdh(driver) return module
get_dbapi_compliant_module
identifier_name
db.py
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 2.1 of the License, or (at your option) any # later version. # # logilab-common is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. """Wrappers to get actually replaceable DBAPI2 compliant modules and database connection whatever the database and client lib used. Currently support: - postgresql (pgdb, psycopg, psycopg2, pyPgSQL) - mysql (MySQLdb) - sqlite (pysqlite2, sqlite, sqlite3) just use the `get_connection` function from this module to get a wrapped connection. If multiple drivers for a database are available, you can control which one you want to use using the `set_prefered_driver` function. Additional helpers are also provided for advanced functionalities such as listing existing users or databases, creating database... Get the helper for your database using the `get_adv_func_helper` function. """
from logilab.database import (get_connection, set_prefered_driver, get_dbapi_compliant_module as _gdcm, get_db_helper as _gdh) def get_dbapi_compliant_module(driver, *args, **kwargs): module = _gdcm(driver, *args, **kwargs) module.adv_func_helper = _gdh(driver) return module
__docformat__ = "restructuredtext en" from warnings import warn warn('this module is deprecated, use logilab.database instead', DeprecationWarning, stacklevel=1)
random_line_split
db.py
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 2.1 of the License, or (at your option) any # later version. # # logilab-common is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License along # with logilab-common. If not, see <http://www.gnu.org/licenses/>. """Wrappers to get actually replaceable DBAPI2 compliant modules and database connection whatever the database and client lib used. Currently support: - postgresql (pgdb, psycopg, psycopg2, pyPgSQL) - mysql (MySQLdb) - sqlite (pysqlite2, sqlite, sqlite3) just use the `get_connection` function from this module to get a wrapped connection. If multiple drivers for a database are available, you can control which one you want to use using the `set_prefered_driver` function. Additional helpers are also provided for advanced functionalities such as listing existing users or databases, creating database... Get the helper for your database using the `get_adv_func_helper` function. """ __docformat__ = "restructuredtext en" from warnings import warn warn('this module is deprecated, use logilab.database instead', DeprecationWarning, stacklevel=1) from logilab.database import (get_connection, set_prefered_driver, get_dbapi_compliant_module as _gdcm, get_db_helper as _gdh) def get_dbapi_compliant_module(driver, *args, **kwargs):
module = _gdcm(driver, *args, **kwargs) module.adv_func_helper = _gdh(driver) return module
identifier_body
ping.node.js
/* eslint-env mocha */ 'use strict' const chai = require('chai') chai.use(require('dirty-chai')) const expect = chai.expect const parallel = require('async/parallel') const createNode = require('./utils/create-node.js') const echo = require('./utils/echo') describe('ping', () => { let nodeA let nodeB before((done) => { parallel([ (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeA = node node.handle('/echo/1.0.0', echo) node.start(cb) }),
nodeB = node node.handle('/echo/1.0.0', echo) node.start(cb) }) ], done) }) after((done) => { parallel([ (cb) => nodeA.stop(cb), (cb) => nodeB.stop(cb) ], done) }) it('should be able to ping another node', (done) => { nodeA.ping(nodeB.peerInfo, (err, ping) => { expect(err).to.not.exist() ping.once('ping', (time) => { expect(time).to.exist() ping.stop() done() }) ping.start() }) }) it('should be not be able to ping when stopped', (done) => { nodeA.stop(() => { nodeA.ping(nodeB.peerInfo, (err) => { expect(err).to.exist() done() }) }) }) })
(cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist()
random_line_split
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn { .. } => write!(f, "[function]"), &Value::BuiltInFn { ref name, .. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display()
}
{ assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); }
identifier_body
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn { .. } => write!(f, "[function]"), &Value::BuiltInFn { ref name, .. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn
(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
eq
identifier_name
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) => { let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }, &Value::Fn { .. } => write!(f, "[function]"), &Value::BuiltInFn { ref name, .. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b),
pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
&Hashable::String(ref s) => Value::String(s.clone()), }) } }
random_line_split
value.rs
use std::collections::HashMap; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use common::util::unescape; use parser::ast::*; use evaluator::types::*; #[derive(Eq, Debug)] pub enum Value { Int(i64), Bool(bool), String(String), Array(Vec<Rc<Value>>), Hash(HashMap<Hashable, Rc<Value>>), Fn { params: Vec<Ident>, body: BlockStmt, env: Rc<RefCell<Env>>, }, BuiltInFn { name: String, num_params: usize, func: BuiltInFn, }, Return(Rc<Value>), Null, } impl fmt::Display for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Value::Int(i) => write!(f, "{}", i), &Value::Bool(b) => write!(f, "{}", b), &Value::String(ref s) => write!(f, "{}", unescape(s)), &Value::Array(ref a) => { let mapped: Vec<String> = a.iter().map(|v| format!("{}", v)).collect(); write!(f, "[{}]", mapped.join(", ")) }, &Value::Hash(ref m) =>
, &Value::Fn { .. } => write!(f, "[function]"), &Value::BuiltInFn { ref name, .. } => write!(f, "[built-in function: {}]", name), &Value::Return(ref o) => o.fmt(f), &Value::Null => write!(f, "null"), } } } impl PartialEq for Value { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Value::Int(i1), &Value::Int(i2)) => i1 == i2, (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2, (&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2, (&Value::Array(ref v1), &Value::Array(ref v2)) => v1 == v2, (&Value::Hash(ref h1), &Value::Hash(ref h2)) => h1 == h2, (&Value::Fn { params: ref p1, body: ref b1, env: ref e1, }, &Value::Fn { params: ref p2, body: ref b2, env: ref e2, }) => p1 == p2 && b1 == b2 && e1 == e2, (&Value::BuiltInFn { name: ref n1, num_params: ref p1, .. }, &Value::BuiltInFn { name: ref n2, num_params: ref p2, .. }) => n1 == n2 && p1 == p2, (&Value::Return(ref o1), &Value::Return(ref o2)) => o1 == o2, (&Value::Null, &Value::Null) => true, _ => false, } } } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Hashable { Int(i64), Bool(bool), String(String), } impl Hashable { pub fn from_lit(lit: &Literal) -> Self { match lit { &Literal::Int(i, _) => Hashable::Int(i), &Literal::Bool(b, _) => Hashable::Bool(b), &Literal::String(ref s, _) => Hashable::String(s.clone()), } } } impl fmt::Display for Hashable { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match self { &Hashable::Int(i) => Value::Int(i), &Hashable::Bool(b) => Value::Bool(b), &Hashable::String(ref s) => Value::String(s.clone()), }) } } pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>; #[cfg(test)] mod tests { use super::*; use std::iter::FromIterator; fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> { unreachable!() } #[test] fn value_display() { assert_eq!(format!("{}", Value::Int(35)), "35"); assert_eq!(format!("{}", Value::Bool(true)), "true"); assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))), "\"hello\\nworld\""); assert_eq!(format!("{}", Value::Array(vec![])), "[]"); assert_eq!(format!("{}", Value::Array(vec![Rc::new(Value::Int(1)), Rc::new(Value::Int(2)), Rc::new(Value::Int(3))])), "[1, 2, 3]"); assert_eq!(format!("{}", Value::Hash(HashMap::new())), "{}"); assert_eq!(format!("{}", Value::Hash(HashMap::from_iter(vec![(Hashable::Int(1), Rc::new(Value::String(String::from("one")))), (Hashable::Int(2), Rc::new(Value::String(String::from("two")))), (Hashable::Int(3), Rc::new(Value::String(String::from("three"))))] ))), "{1: \"one\", 2: \"two\", 3: \"three\"}"); assert_eq!(format!("{}", Value::Fn { params: vec![], body: vec![], env: Rc::new(RefCell::new(Env::new())), }), "[function]"); assert_eq!(format!("{}", Value::BuiltInFn { name: String::from("hi"), num_params: 0, func: dummy, }), "[built-in function: hi]"); assert_eq!(format!("{}", Value::Return(Rc::from(Value::Int(35)))), "35"); assert_eq!(format!("{}", Value::Null), "null"); } }
{ let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect(); mapped.sort(); write!(f, "{{{}}}", mapped.join(", ")) }
conditional_block
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin') var TARGET = process.env.TARGET; var config = { devtool: 'eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/index' ],
plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; if (TARGET === 'prod') { var config = { devtool: 'source-map', entry: [ './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/ui/' }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false }, sourceMap: false }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; } module.exports = config;
output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', },
random_line_split
webpack.config.js
var path = require('path'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin') var TARGET = process.env.TARGET; var config = { devtool: 'eval-source-map', entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; if (TARGET === 'prod')
module.exports = config;
{ var config = { devtool: 'source-map', entry: [ './app/index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/ui/' }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false }, sourceMap: false }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new HtmlWebpackPlugin({ filename: 'index.html', template: 'App/Views/template.html' }) ], module: { loaders: [{ test: /\.js$/, loaders: ['react-hot', 'babel'], include: path.join(__dirname, 'app') }] }, resolve: { root: [ path.resolve(__dirname) ] } }; }
conditional_block
shared.ts
/** * A found external editor on the user's machine */ export type FoundEditor = { /** * The friendly name of the editor, to be used in labels */ editor: string /** * The executable associated with the editor to launch */ path: string /** * the editor requires a shell spawn to launch */ usesShell?: boolean } interface IErrorMetadata { /** The error dialog should link off to the default editor's website */ suggestDefaultEditor?: boolean /** The error dialog should direct the user to open Preferences */ openPreferences?: boolean } export class
extends Error { /** The error's metadata. */ public readonly metadata: IErrorMetadata public constructor(message: string, metadata: IErrorMetadata = {}) { super(message) this.metadata = metadata } } export const suggestedExternalEditor = { name: 'Visual Studio Code', url: 'https://code.visualstudio.com', }
ExternalEditorError
identifier_name
shared.ts
/** * A found external editor on the user's machine */ export type FoundEditor = { /** * The friendly name of the editor, to be used in labels */ editor: string /** * The executable associated with the editor to launch */
/** * the editor requires a shell spawn to launch */ usesShell?: boolean } interface IErrorMetadata { /** The error dialog should link off to the default editor's website */ suggestDefaultEditor?: boolean /** The error dialog should direct the user to open Preferences */ openPreferences?: boolean } export class ExternalEditorError extends Error { /** The error's metadata. */ public readonly metadata: IErrorMetadata public constructor(message: string, metadata: IErrorMetadata = {}) { super(message) this.metadata = metadata } } export const suggestedExternalEditor = { name: 'Visual Studio Code', url: 'https://code.visualstudio.com', }
path: string
random_line_split
issues.py
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import codecs import datetime import itertools import operator import os import re import sys try: from lxml import etree except ImportError: etree = None from . import colorize, config, source, utils ISSUE_KIND_ERROR = 'ERROR' ISSUE_KIND_WARNING = 'WARNING' ISSUE_KIND_INFO = 'INFO' ISSUE_KIND_ADVICE = 'ADVICE' # field names in rows of json reports JSON_INDEX_DOTTY = 'dotty' JSON_INDEX_FILENAME = 'file' JSON_INDEX_HASH = 'hash' JSON_INDEX_INFER_SOURCE_LOC = 'infer_source_loc' JSON_INDEX_ISL_FILE = 'file' JSON_INDEX_ISL_LNUM = 'lnum' JSON_INDEX_ISL_CNUM = 'cnum' JSON_INDEX_ISL_ENUM = 'enum' JSON_INDEX_KIND = 'kind' JSON_INDEX_LINE = 'line' JSON_INDEX_PROCEDURE = 'procedure' JSON_INDEX_PROCEDURE_ID = 'procedure_id' JSON_INDEX_QUALIFIER = 'qualifier' JSON_INDEX_QUALIFIER_TAGS = 'qualifier_tags' JSON_INDEX_TYPE = 'bug_type' JSON_INDEX_TRACE = 'bug_trace' JSON_INDEX_TRACE_LEVEL = 'level' JSON_INDEX_TRACE_FILENAME = 'filename' JSON_INDEX_TRACE_LINE = 'line_number' JSON_INDEX_TRACE_DESCRIPTION = 'description' JSON_INDEX_VISIBILITY = 'visibility' ISSUE_TYPES_URL = 'http://fbinfer.com/docs/infer-issue-types.html#' def _text_of_infer_loc(loc): return ' ({}:{}:{}-{}:)'.format( loc[JSON_INDEX_ISL_FILE], loc[JSON_INDEX_ISL_LNUM], loc[JSON_INDEX_ISL_CNUM], loc[JSON_INDEX_ISL_ENUM], ) def text_of_report(report): filename = report[JSON_INDEX_FILENAME] kind = report[JSON_INDEX_KIND] line = report[JSON_INDEX_LINE] error_type = report[JSON_INDEX_TYPE] msg = report[JSON_INDEX_QUALIFIER] infer_loc = '' if JSON_INDEX_INFER_SOURCE_LOC in report: infer_loc = _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) return '%s:%d: %s: %s%s\n %s' % ( filename, line, kind.lower(), error_type, infer_loc, msg, ) def _text_of_report_list(project_root, reports, bugs_txt_path, limit=None, formatter=colorize.TERMINAL_FORMATTER): n_issues = len(reports) if n_issues == 0: if formatter == colorize.TERMINAL_FORMATTER: out = colorize.color(' No issues found ', colorize.SUCCESS, formatter) return out + '\n' else: return 'No issues found' text_errors_list = [] for report in reports[:limit]: filename = report[JSON_INDEX_FILENAME] line = report[JSON_INDEX_LINE] source_context = '' source_context = source.build_source_context( os.path.join(project_root, filename), formatter, line, ) indenter = source.Indenter() \ .indent_push() \ .add(source_context) source_context = '\n' + unicode(indenter) msg = text_of_report(report) if report[JSON_INDEX_KIND] == ISSUE_KIND_ERROR: msg = colorize.color(msg, colorize.ERROR, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_WARNING: msg = colorize.color(msg, colorize.WARNING, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_ADVICE: msg = colorize.color(msg, colorize.ADVICE, formatter) text = '%s%s' % (msg, source_context) text_errors_list.append(text) error_types_count = {} for report in reports: t = report[JSON_INDEX_TYPE] # assert failures are not very informative without knowing # which assertion failed if t == 'Assert_failure' and JSON_INDEX_INFER_SOURCE_LOC in report: t += _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) if t not in error_types_count: error_types_count[t] = 1 else: error_types_count[t] += 1 max_type_length = max(map(len, error_types_count.keys())) + 2 sorted_error_types = error_types_count.items() sorted_error_types.sort(key=operator.itemgetter(1), reverse=True) types_text_list = map(lambda (t, count): '%s: %d' % ( t.rjust(max_type_length), count, ), sorted_error_types) text_errors = '\n\n'.join(text_errors_list) if limit >= 0 and n_issues > limit: text_errors += colorize.color( ('\n\n...too many issues to display (limit=%d exceeded), please ' + 'see %s or run `inferTraceBugs` for the remaining issues.') % (limit, bugs_txt_path), colorize.HEADER, formatter) issues_found = 'Found {n_issues}'.format( n_issues=utils.get_plural('issue', n_issues), ) msg = '{issues_found}\n\n{issues}\n\n{header}\n\n{summary}'.format( issues_found=colorize.color(issues_found, colorize.HEADER, formatter), issues=text_errors, header=colorize.color('Summary of the reports', colorize.HEADER, formatter), summary='\n'.join(types_text_list), ) return msg def _is_user_visible(project_root, report): kind = report[JSON_INDEX_KIND] return kind in [ISSUE_KIND_ERROR, ISSUE_KIND_WARNING, ISSUE_KIND_ADVICE] def print_and_save_errors(infer_out, project_root, json_report, bugs_out, pmd_xml): errors = utils.load_json_from_path(json_report) errors = [e for e in errors if _is_user_visible(project_root, e)] console_out = _text_of_report_list(project_root, errors, bugs_out, limit=10) utils.stdout('\n' + console_out) plain_out = _text_of_report_list(project_root, errors, bugs_out, formatter=colorize.PLAIN_FORMATTER) with codecs.open(bugs_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(plain_out) if pmd_xml: xml_out = os.path.join(infer_out, config.PMD_XML_FILENAME) with codecs.open(xml_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(_pmd_xml_of_issues(errors)) def
(report_paths): json_data = [] for json_path in report_paths: json_data.extend(utils.load_json_from_path(json_path)) return _sort_and_uniq_rows(json_data) def _pmd_xml_of_issues(issues): if etree is None: print('ERROR: "etree" Python package not found.') print('ERROR: You need to install it to use Infer with --pmd-xml') sys.exit(1) root = etree.Element('pmd') root.attrib['version'] = '5.4.1' root.attrib['date'] = datetime.datetime.now().isoformat() for issue in issues: fully_qualifed_method_name = re.search('(.*)\(.*', issue[JSON_INDEX_PROCEDURE_ID]) class_name = '' package = '' if fully_qualifed_method_name is not None: # probably Java info = fully_qualifed_method_name.groups()[0].split('.') class_name = info[-2:-1][0] method = info[-1] package = '.'.join(info[0:-2]) else: method = issue[JSON_INDEX_PROCEDURE] file_node = etree.Element('file') file_node.attrib['name'] = issue[JSON_INDEX_FILENAME] violation = etree.Element('violation') violation.attrib['begincolumn'] = '0' violation.attrib['beginline'] = str(issue[JSON_INDEX_LINE]) violation.attrib['endcolumn'] = '0' violation.attrib['endline'] = str(issue[JSON_INDEX_LINE] + 1) violation.attrib['class'] = class_name violation.attrib['method'] = method violation.attrib['package'] = package violation.attrib['priority'] = '1' violation.attrib['rule'] = issue[JSON_INDEX_TYPE] violation.attrib['ruleset'] = 'Infer Rules' violation.attrib['externalinfourl'] = ( ISSUE_TYPES_URL + issue[JSON_INDEX_TYPE]) violation.text = issue[JSON_INDEX_QUALIFIER] file_node.append(violation) root.append(file_node) return etree.tostring(root, pretty_print=True, encoding=config.CODESET) def _sort_and_uniq_rows(l): key = operator.itemgetter(JSON_INDEX_FILENAME, JSON_INDEX_LINE, JSON_INDEX_HASH, JSON_INDEX_QUALIFIER) l.sort(key=key) groups = itertools.groupby(l, key) # guaranteed to be at least one element in each group return map(lambda (keys, dups): dups.next(), groups)
merge_reports_from_paths
identifier_name
issues.py
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import codecs import datetime import itertools import operator import os import re import sys try: from lxml import etree except ImportError: etree = None from . import colorize, config, source, utils ISSUE_KIND_ERROR = 'ERROR' ISSUE_KIND_WARNING = 'WARNING' ISSUE_KIND_INFO = 'INFO' ISSUE_KIND_ADVICE = 'ADVICE' # field names in rows of json reports JSON_INDEX_DOTTY = 'dotty' JSON_INDEX_FILENAME = 'file' JSON_INDEX_HASH = 'hash' JSON_INDEX_INFER_SOURCE_LOC = 'infer_source_loc' JSON_INDEX_ISL_FILE = 'file' JSON_INDEX_ISL_LNUM = 'lnum' JSON_INDEX_ISL_CNUM = 'cnum' JSON_INDEX_ISL_ENUM = 'enum' JSON_INDEX_KIND = 'kind' JSON_INDEX_LINE = 'line' JSON_INDEX_PROCEDURE = 'procedure' JSON_INDEX_PROCEDURE_ID = 'procedure_id' JSON_INDEX_QUALIFIER = 'qualifier' JSON_INDEX_QUALIFIER_TAGS = 'qualifier_tags' JSON_INDEX_TYPE = 'bug_type' JSON_INDEX_TRACE = 'bug_trace' JSON_INDEX_TRACE_LEVEL = 'level' JSON_INDEX_TRACE_FILENAME = 'filename' JSON_INDEX_TRACE_LINE = 'line_number' JSON_INDEX_TRACE_DESCRIPTION = 'description' JSON_INDEX_VISIBILITY = 'visibility' ISSUE_TYPES_URL = 'http://fbinfer.com/docs/infer-issue-types.html#' def _text_of_infer_loc(loc): return ' ({}:{}:{}-{}:)'.format( loc[JSON_INDEX_ISL_FILE], loc[JSON_INDEX_ISL_LNUM], loc[JSON_INDEX_ISL_CNUM], loc[JSON_INDEX_ISL_ENUM], ) def text_of_report(report): filename = report[JSON_INDEX_FILENAME] kind = report[JSON_INDEX_KIND] line = report[JSON_INDEX_LINE] error_type = report[JSON_INDEX_TYPE] msg = report[JSON_INDEX_QUALIFIER] infer_loc = '' if JSON_INDEX_INFER_SOURCE_LOC in report: infer_loc = _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) return '%s:%d: %s: %s%s\n %s' % ( filename, line, kind.lower(), error_type, infer_loc, msg, ) def _text_of_report_list(project_root, reports, bugs_txt_path, limit=None, formatter=colorize.TERMINAL_FORMATTER): n_issues = len(reports) if n_issues == 0: if formatter == colorize.TERMINAL_FORMATTER:
else: return 'No issues found' text_errors_list = [] for report in reports[:limit]: filename = report[JSON_INDEX_FILENAME] line = report[JSON_INDEX_LINE] source_context = '' source_context = source.build_source_context( os.path.join(project_root, filename), formatter, line, ) indenter = source.Indenter() \ .indent_push() \ .add(source_context) source_context = '\n' + unicode(indenter) msg = text_of_report(report) if report[JSON_INDEX_KIND] == ISSUE_KIND_ERROR: msg = colorize.color(msg, colorize.ERROR, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_WARNING: msg = colorize.color(msg, colorize.WARNING, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_ADVICE: msg = colorize.color(msg, colorize.ADVICE, formatter) text = '%s%s' % (msg, source_context) text_errors_list.append(text) error_types_count = {} for report in reports: t = report[JSON_INDEX_TYPE] # assert failures are not very informative without knowing # which assertion failed if t == 'Assert_failure' and JSON_INDEX_INFER_SOURCE_LOC in report: t += _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) if t not in error_types_count: error_types_count[t] = 1 else: error_types_count[t] += 1 max_type_length = max(map(len, error_types_count.keys())) + 2 sorted_error_types = error_types_count.items() sorted_error_types.sort(key=operator.itemgetter(1), reverse=True) types_text_list = map(lambda (t, count): '%s: %d' % ( t.rjust(max_type_length), count, ), sorted_error_types) text_errors = '\n\n'.join(text_errors_list) if limit >= 0 and n_issues > limit: text_errors += colorize.color( ('\n\n...too many issues to display (limit=%d exceeded), please ' + 'see %s or run `inferTraceBugs` for the remaining issues.') % (limit, bugs_txt_path), colorize.HEADER, formatter) issues_found = 'Found {n_issues}'.format( n_issues=utils.get_plural('issue', n_issues), ) msg = '{issues_found}\n\n{issues}\n\n{header}\n\n{summary}'.format( issues_found=colorize.color(issues_found, colorize.HEADER, formatter), issues=text_errors, header=colorize.color('Summary of the reports', colorize.HEADER, formatter), summary='\n'.join(types_text_list), ) return msg def _is_user_visible(project_root, report): kind = report[JSON_INDEX_KIND] return kind in [ISSUE_KIND_ERROR, ISSUE_KIND_WARNING, ISSUE_KIND_ADVICE] def print_and_save_errors(infer_out, project_root, json_report, bugs_out, pmd_xml): errors = utils.load_json_from_path(json_report) errors = [e for e in errors if _is_user_visible(project_root, e)] console_out = _text_of_report_list(project_root, errors, bugs_out, limit=10) utils.stdout('\n' + console_out) plain_out = _text_of_report_list(project_root, errors, bugs_out, formatter=colorize.PLAIN_FORMATTER) with codecs.open(bugs_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(plain_out) if pmd_xml: xml_out = os.path.join(infer_out, config.PMD_XML_FILENAME) with codecs.open(xml_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(_pmd_xml_of_issues(errors)) def merge_reports_from_paths(report_paths): json_data = [] for json_path in report_paths: json_data.extend(utils.load_json_from_path(json_path)) return _sort_and_uniq_rows(json_data) def _pmd_xml_of_issues(issues): if etree is None: print('ERROR: "etree" Python package not found.') print('ERROR: You need to install it to use Infer with --pmd-xml') sys.exit(1) root = etree.Element('pmd') root.attrib['version'] = '5.4.1' root.attrib['date'] = datetime.datetime.now().isoformat() for issue in issues: fully_qualifed_method_name = re.search('(.*)\(.*', issue[JSON_INDEX_PROCEDURE_ID]) class_name = '' package = '' if fully_qualifed_method_name is not None: # probably Java info = fully_qualifed_method_name.groups()[0].split('.') class_name = info[-2:-1][0] method = info[-1] package = '.'.join(info[0:-2]) else: method = issue[JSON_INDEX_PROCEDURE] file_node = etree.Element('file') file_node.attrib['name'] = issue[JSON_INDEX_FILENAME] violation = etree.Element('violation') violation.attrib['begincolumn'] = '0' violation.attrib['beginline'] = str(issue[JSON_INDEX_LINE]) violation.attrib['endcolumn'] = '0' violation.attrib['endline'] = str(issue[JSON_INDEX_LINE] + 1) violation.attrib['class'] = class_name violation.attrib['method'] = method violation.attrib['package'] = package violation.attrib['priority'] = '1' violation.attrib['rule'] = issue[JSON_INDEX_TYPE] violation.attrib['ruleset'] = 'Infer Rules' violation.attrib['externalinfourl'] = ( ISSUE_TYPES_URL + issue[JSON_INDEX_TYPE]) violation.text = issue[JSON_INDEX_QUALIFIER] file_node.append(violation) root.append(file_node) return etree.tostring(root, pretty_print=True, encoding=config.CODESET) def _sort_and_uniq_rows(l): key = operator.itemgetter(JSON_INDEX_FILENAME, JSON_INDEX_LINE, JSON_INDEX_HASH, JSON_INDEX_QUALIFIER) l.sort(key=key) groups = itertools.groupby(l, key) # guaranteed to be at least one element in each group return map(lambda (keys, dups): dups.next(), groups)
out = colorize.color(' No issues found ', colorize.SUCCESS, formatter) return out + '\n'
conditional_block
issues.py
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import codecs import datetime import itertools import operator import os import re import sys try: from lxml import etree except ImportError: etree = None from . import colorize, config, source, utils ISSUE_KIND_ERROR = 'ERROR' ISSUE_KIND_WARNING = 'WARNING' ISSUE_KIND_INFO = 'INFO' ISSUE_KIND_ADVICE = 'ADVICE' # field names in rows of json reports JSON_INDEX_DOTTY = 'dotty' JSON_INDEX_FILENAME = 'file' JSON_INDEX_HASH = 'hash' JSON_INDEX_INFER_SOURCE_LOC = 'infer_source_loc' JSON_INDEX_ISL_FILE = 'file' JSON_INDEX_ISL_LNUM = 'lnum' JSON_INDEX_ISL_CNUM = 'cnum' JSON_INDEX_ISL_ENUM = 'enum' JSON_INDEX_KIND = 'kind' JSON_INDEX_LINE = 'line' JSON_INDEX_PROCEDURE = 'procedure' JSON_INDEX_PROCEDURE_ID = 'procedure_id' JSON_INDEX_QUALIFIER = 'qualifier' JSON_INDEX_QUALIFIER_TAGS = 'qualifier_tags' JSON_INDEX_TYPE = 'bug_type' JSON_INDEX_TRACE = 'bug_trace' JSON_INDEX_TRACE_LEVEL = 'level' JSON_INDEX_TRACE_FILENAME = 'filename' JSON_INDEX_TRACE_LINE = 'line_number' JSON_INDEX_TRACE_DESCRIPTION = 'description' JSON_INDEX_VISIBILITY = 'visibility' ISSUE_TYPES_URL = 'http://fbinfer.com/docs/infer-issue-types.html#' def _text_of_infer_loc(loc): return ' ({}:{}:{}-{}:)'.format( loc[JSON_INDEX_ISL_FILE], loc[JSON_INDEX_ISL_LNUM], loc[JSON_INDEX_ISL_CNUM], loc[JSON_INDEX_ISL_ENUM], ) def text_of_report(report): filename = report[JSON_INDEX_FILENAME] kind = report[JSON_INDEX_KIND] line = report[JSON_INDEX_LINE] error_type = report[JSON_INDEX_TYPE] msg = report[JSON_INDEX_QUALIFIER] infer_loc = '' if JSON_INDEX_INFER_SOURCE_LOC in report: infer_loc = _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) return '%s:%d: %s: %s%s\n %s' % ( filename, line, kind.lower(), error_type, infer_loc, msg, ) def _text_of_report_list(project_root, reports, bugs_txt_path, limit=None, formatter=colorize.TERMINAL_FORMATTER): n_issues = len(reports) if n_issues == 0: if formatter == colorize.TERMINAL_FORMATTER: out = colorize.color(' No issues found ', colorize.SUCCESS, formatter) return out + '\n' else: return 'No issues found' text_errors_list = [] for report in reports[:limit]: filename = report[JSON_INDEX_FILENAME] line = report[JSON_INDEX_LINE] source_context = '' source_context = source.build_source_context( os.path.join(project_root, filename), formatter, line, ) indenter = source.Indenter() \ .indent_push() \ .add(source_context) source_context = '\n' + unicode(indenter) msg = text_of_report(report) if report[JSON_INDEX_KIND] == ISSUE_KIND_ERROR: msg = colorize.color(msg, colorize.ERROR, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_WARNING: msg = colorize.color(msg, colorize.WARNING, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_ADVICE: msg = colorize.color(msg, colorize.ADVICE, formatter) text = '%s%s' % (msg, source_context) text_errors_list.append(text) error_types_count = {} for report in reports: t = report[JSON_INDEX_TYPE] # assert failures are not very informative without knowing # which assertion failed if t == 'Assert_failure' and JSON_INDEX_INFER_SOURCE_LOC in report: t += _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) if t not in error_types_count: error_types_count[t] = 1 else: error_types_count[t] += 1 max_type_length = max(map(len, error_types_count.keys())) + 2 sorted_error_types = error_types_count.items() sorted_error_types.sort(key=operator.itemgetter(1), reverse=True) types_text_list = map(lambda (t, count): '%s: %d' % ( t.rjust(max_type_length), count, ), sorted_error_types) text_errors = '\n\n'.join(text_errors_list) if limit >= 0 and n_issues > limit: text_errors += colorize.color( ('\n\n...too many issues to display (limit=%d exceeded), please ' + 'see %s or run `inferTraceBugs` for the remaining issues.') % (limit, bugs_txt_path), colorize.HEADER, formatter) issues_found = 'Found {n_issues}'.format( n_issues=utils.get_plural('issue', n_issues), ) msg = '{issues_found}\n\n{issues}\n\n{header}\n\n{summary}'.format( issues_found=colorize.color(issues_found, colorize.HEADER, formatter), issues=text_errors, header=colorize.color('Summary of the reports', colorize.HEADER, formatter), summary='\n'.join(types_text_list), ) return msg def _is_user_visible(project_root, report): kind = report[JSON_INDEX_KIND] return kind in [ISSUE_KIND_ERROR, ISSUE_KIND_WARNING, ISSUE_KIND_ADVICE] def print_and_save_errors(infer_out, project_root, json_report, bugs_out, pmd_xml):
def merge_reports_from_paths(report_paths): json_data = [] for json_path in report_paths: json_data.extend(utils.load_json_from_path(json_path)) return _sort_and_uniq_rows(json_data) def _pmd_xml_of_issues(issues): if etree is None: print('ERROR: "etree" Python package not found.') print('ERROR: You need to install it to use Infer with --pmd-xml') sys.exit(1) root = etree.Element('pmd') root.attrib['version'] = '5.4.1' root.attrib['date'] = datetime.datetime.now().isoformat() for issue in issues: fully_qualifed_method_name = re.search('(.*)\(.*', issue[JSON_INDEX_PROCEDURE_ID]) class_name = '' package = '' if fully_qualifed_method_name is not None: # probably Java info = fully_qualifed_method_name.groups()[0].split('.') class_name = info[-2:-1][0] method = info[-1] package = '.'.join(info[0:-2]) else: method = issue[JSON_INDEX_PROCEDURE] file_node = etree.Element('file') file_node.attrib['name'] = issue[JSON_INDEX_FILENAME] violation = etree.Element('violation') violation.attrib['begincolumn'] = '0' violation.attrib['beginline'] = str(issue[JSON_INDEX_LINE]) violation.attrib['endcolumn'] = '0' violation.attrib['endline'] = str(issue[JSON_INDEX_LINE] + 1) violation.attrib['class'] = class_name violation.attrib['method'] = method violation.attrib['package'] = package violation.attrib['priority'] = '1' violation.attrib['rule'] = issue[JSON_INDEX_TYPE] violation.attrib['ruleset'] = 'Infer Rules' violation.attrib['externalinfourl'] = ( ISSUE_TYPES_URL + issue[JSON_INDEX_TYPE]) violation.text = issue[JSON_INDEX_QUALIFIER] file_node.append(violation) root.append(file_node) return etree.tostring(root, pretty_print=True, encoding=config.CODESET) def _sort_and_uniq_rows(l): key = operator.itemgetter(JSON_INDEX_FILENAME, JSON_INDEX_LINE, JSON_INDEX_HASH, JSON_INDEX_QUALIFIER) l.sort(key=key) groups = itertools.groupby(l, key) # guaranteed to be at least one element in each group return map(lambda (keys, dups): dups.next(), groups)
errors = utils.load_json_from_path(json_report) errors = [e for e in errors if _is_user_visible(project_root, e)] console_out = _text_of_report_list(project_root, errors, bugs_out, limit=10) utils.stdout('\n' + console_out) plain_out = _text_of_report_list(project_root, errors, bugs_out, formatter=colorize.PLAIN_FORMATTER) with codecs.open(bugs_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(plain_out) if pmd_xml: xml_out = os.path.join(infer_out, config.PMD_XML_FILENAME) with codecs.open(xml_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(_pmd_xml_of_issues(errors))
identifier_body
issues.py
# Copyright (c) 2015 - present Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import codecs import datetime import itertools import operator import os import re import sys try: from lxml import etree except ImportError: etree = None from . import colorize, config, source, utils ISSUE_KIND_ERROR = 'ERROR' ISSUE_KIND_WARNING = 'WARNING' ISSUE_KIND_INFO = 'INFO' ISSUE_KIND_ADVICE = 'ADVICE' # field names in rows of json reports JSON_INDEX_DOTTY = 'dotty' JSON_INDEX_FILENAME = 'file' JSON_INDEX_HASH = 'hash' JSON_INDEX_INFER_SOURCE_LOC = 'infer_source_loc' JSON_INDEX_ISL_FILE = 'file' JSON_INDEX_ISL_LNUM = 'lnum' JSON_INDEX_ISL_CNUM = 'cnum' JSON_INDEX_ISL_ENUM = 'enum' JSON_INDEX_KIND = 'kind' JSON_INDEX_LINE = 'line' JSON_INDEX_PROCEDURE = 'procedure' JSON_INDEX_PROCEDURE_ID = 'procedure_id' JSON_INDEX_QUALIFIER = 'qualifier' JSON_INDEX_QUALIFIER_TAGS = 'qualifier_tags' JSON_INDEX_TYPE = 'bug_type' JSON_INDEX_TRACE = 'bug_trace' JSON_INDEX_TRACE_LEVEL = 'level' JSON_INDEX_TRACE_FILENAME = 'filename' JSON_INDEX_TRACE_LINE = 'line_number' JSON_INDEX_TRACE_DESCRIPTION = 'description' JSON_INDEX_VISIBILITY = 'visibility' ISSUE_TYPES_URL = 'http://fbinfer.com/docs/infer-issue-types.html#' def _text_of_infer_loc(loc): return ' ({}:{}:{}-{}:)'.format( loc[JSON_INDEX_ISL_FILE], loc[JSON_INDEX_ISL_LNUM], loc[JSON_INDEX_ISL_CNUM], loc[JSON_INDEX_ISL_ENUM], ) def text_of_report(report): filename = report[JSON_INDEX_FILENAME] kind = report[JSON_INDEX_KIND] line = report[JSON_INDEX_LINE] error_type = report[JSON_INDEX_TYPE] msg = report[JSON_INDEX_QUALIFIER] infer_loc = '' if JSON_INDEX_INFER_SOURCE_LOC in report: infer_loc = _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) return '%s:%d: %s: %s%s\n %s' % ( filename, line, kind.lower(), error_type, infer_loc, msg, ) def _text_of_report_list(project_root, reports, bugs_txt_path, limit=None, formatter=colorize.TERMINAL_FORMATTER): n_issues = len(reports) if n_issues == 0: if formatter == colorize.TERMINAL_FORMATTER: out = colorize.color(' No issues found ', colorize.SUCCESS, formatter) return out + '\n' else: return 'No issues found' text_errors_list = [] for report in reports[:limit]: filename = report[JSON_INDEX_FILENAME] line = report[JSON_INDEX_LINE] source_context = '' source_context = source.build_source_context( os.path.join(project_root, filename), formatter, line, ) indenter = source.Indenter() \ .indent_push() \ .add(source_context) source_context = '\n' + unicode(indenter) msg = text_of_report(report) if report[JSON_INDEX_KIND] == ISSUE_KIND_ERROR: msg = colorize.color(msg, colorize.ERROR, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_WARNING: msg = colorize.color(msg, colorize.WARNING, formatter) elif report[JSON_INDEX_KIND] == ISSUE_KIND_ADVICE: msg = colorize.color(msg, colorize.ADVICE, formatter) text = '%s%s' % (msg, source_context) text_errors_list.append(text) error_types_count = {} for report in reports: t = report[JSON_INDEX_TYPE] # assert failures are not very informative without knowing # which assertion failed if t == 'Assert_failure' and JSON_INDEX_INFER_SOURCE_LOC in report: t += _text_of_infer_loc(report[JSON_INDEX_INFER_SOURCE_LOC]) if t not in error_types_count: error_types_count[t] = 1 else: error_types_count[t] += 1 max_type_length = max(map(len, error_types_count.keys())) + 2 sorted_error_types = error_types_count.items()
), sorted_error_types) text_errors = '\n\n'.join(text_errors_list) if limit >= 0 and n_issues > limit: text_errors += colorize.color( ('\n\n...too many issues to display (limit=%d exceeded), please ' + 'see %s or run `inferTraceBugs` for the remaining issues.') % (limit, bugs_txt_path), colorize.HEADER, formatter) issues_found = 'Found {n_issues}'.format( n_issues=utils.get_plural('issue', n_issues), ) msg = '{issues_found}\n\n{issues}\n\n{header}\n\n{summary}'.format( issues_found=colorize.color(issues_found, colorize.HEADER, formatter), issues=text_errors, header=colorize.color('Summary of the reports', colorize.HEADER, formatter), summary='\n'.join(types_text_list), ) return msg def _is_user_visible(project_root, report): kind = report[JSON_INDEX_KIND] return kind in [ISSUE_KIND_ERROR, ISSUE_KIND_WARNING, ISSUE_KIND_ADVICE] def print_and_save_errors(infer_out, project_root, json_report, bugs_out, pmd_xml): errors = utils.load_json_from_path(json_report) errors = [e for e in errors if _is_user_visible(project_root, e)] console_out = _text_of_report_list(project_root, errors, bugs_out, limit=10) utils.stdout('\n' + console_out) plain_out = _text_of_report_list(project_root, errors, bugs_out, formatter=colorize.PLAIN_FORMATTER) with codecs.open(bugs_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(plain_out) if pmd_xml: xml_out = os.path.join(infer_out, config.PMD_XML_FILENAME) with codecs.open(xml_out, 'w', encoding=config.CODESET, errors='replace') as file_out: file_out.write(_pmd_xml_of_issues(errors)) def merge_reports_from_paths(report_paths): json_data = [] for json_path in report_paths: json_data.extend(utils.load_json_from_path(json_path)) return _sort_and_uniq_rows(json_data) def _pmd_xml_of_issues(issues): if etree is None: print('ERROR: "etree" Python package not found.') print('ERROR: You need to install it to use Infer with --pmd-xml') sys.exit(1) root = etree.Element('pmd') root.attrib['version'] = '5.4.1' root.attrib['date'] = datetime.datetime.now().isoformat() for issue in issues: fully_qualifed_method_name = re.search('(.*)\(.*', issue[JSON_INDEX_PROCEDURE_ID]) class_name = '' package = '' if fully_qualifed_method_name is not None: # probably Java info = fully_qualifed_method_name.groups()[0].split('.') class_name = info[-2:-1][0] method = info[-1] package = '.'.join(info[0:-2]) else: method = issue[JSON_INDEX_PROCEDURE] file_node = etree.Element('file') file_node.attrib['name'] = issue[JSON_INDEX_FILENAME] violation = etree.Element('violation') violation.attrib['begincolumn'] = '0' violation.attrib['beginline'] = str(issue[JSON_INDEX_LINE]) violation.attrib['endcolumn'] = '0' violation.attrib['endline'] = str(issue[JSON_INDEX_LINE] + 1) violation.attrib['class'] = class_name violation.attrib['method'] = method violation.attrib['package'] = package violation.attrib['priority'] = '1' violation.attrib['rule'] = issue[JSON_INDEX_TYPE] violation.attrib['ruleset'] = 'Infer Rules' violation.attrib['externalinfourl'] = ( ISSUE_TYPES_URL + issue[JSON_INDEX_TYPE]) violation.text = issue[JSON_INDEX_QUALIFIER] file_node.append(violation) root.append(file_node) return etree.tostring(root, pretty_print=True, encoding=config.CODESET) def _sort_and_uniq_rows(l): key = operator.itemgetter(JSON_INDEX_FILENAME, JSON_INDEX_LINE, JSON_INDEX_HASH, JSON_INDEX_QUALIFIER) l.sort(key=key) groups = itertools.groupby(l, key) # guaranteed to be at least one element in each group return map(lambda (keys, dups): dups.next(), groups)
sorted_error_types.sort(key=operator.itemgetter(1), reverse=True) types_text_list = map(lambda (t, count): '%s: %d' % ( t.rjust(max_type_length), count,
random_line_split
hourly.js
* * Copyright (C) 2015 Cam Moore. * * The MIT License (MIT) * * 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, deistribute, sublicense, and/or sell * copies of the Software, and to permit person to whom the Software is * furnished to do so, subject to the following condtions: * * 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 * AUTHOERS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETER IN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISIGN FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE */ //Meteor.subscribe("hourly");
/** * This file is a part of hale_aloha_dashboard. * * Created by Cam Moore on 11/12/15.
random_line_split
slick.media.js
/** * @file */ (function ($) { "use strict"; Drupal.behaviors.slickMedia = { attach: function (context, settings) { var $slider = $('.slick', context), player = '.media--switch--player'; $(player, context).once('slick-media', function () { var t = $(this); // Remove SRC attributes to avoid direct autoplay, if mistakenly enabled. t.find('iframe').attr('src', ''); t.on('click.media-play', '.media-icon--play', function (e) { e.preventDefault(); var p = $(this), iframe = p.closest(player).find('iframe'), url = iframe.data('lazy'), media = iframe.data('media'); // Soundcloud needs internet, fails on disconnected local. if (url === '') { return false; } // Force autoplay, if not provided, which should not.
if (media.scheme === 'soundcloud') { if (url.indexOf('auto_play') < 0 || url.indexOf('auto_play') === false) { url = url.indexOf('?') < 0 ? url + '?auto_play=true' : url + '&amp;auto_play=true'; } } else if (url.indexOf('autoplay') < 0 || url.indexOf('autoplay') === 0) { url = url.indexOf('?') < 0 ? url + '?autoplay=1' : url + '&amp;autoplay=1'; } // First, reset any video to avoid multiple videos from playing. $(player).removeClass('is-playing').find('iframe').attr('src', ''); // Clean up any pause marker. $('.is-paused').removeClass('is-paused'); // Last, pause the slide, for just in case autoplay is on and // pauseOnHover is disabled, and then trigger autoplay. t.closest('.slick').addClass('is-paused').slickPause(); t.closest(player).addClass('is-playing').find('iframe').attr('src', url); }) // Closes the video. .on('click.media-close', '.media-icon--close', function (e) { e.preventDefault(); $(this).closest(player).removeClass('is-playing').find('iframe').attr('src', ''); $('.is-paused').removeClass('is-paused'); }) // Turns off video if any button clicked. .on('click.media-close-other', '.slick__arrow button, > button', function (e) { e.preventDefault(); t.find('.media-icon--close').trigger('click.media-close'); }); }); } }; // Turn off current video if the slide changes, e.g. by dragging the slide. Drupal.slick.callbacks.onAfterChange = function (slider, index) { $('.media-icon--close', '#' + slider.$slider.attr('id')).trigger('click.media-close'); }; })(jQuery);
random_line_split
slick.media.js
/** * @file */ (function ($) { "use strict"; Drupal.behaviors.slickMedia = { attach: function (context, settings) { var $slider = $('.slick', context), player = '.media--switch--player'; $(player, context).once('slick-media', function () { var t = $(this); // Remove SRC attributes to avoid direct autoplay, if mistakenly enabled. t.find('iframe').attr('src', ''); t.on('click.media-play', '.media-icon--play', function (e) { e.preventDefault(); var p = $(this), iframe = p.closest(player).find('iframe'), url = iframe.data('lazy'), media = iframe.data('media'); // Soundcloud needs internet, fails on disconnected local. if (url === '') { return false; } // Force autoplay, if not provided, which should not. if (media.scheme === 'soundcloud') { if (url.indexOf('auto_play') < 0 || url.indexOf('auto_play') === false) { url = url.indexOf('?') < 0 ? url + '?auto_play=true' : url + '&amp;auto_play=true'; } } else if (url.indexOf('autoplay') < 0 || url.indexOf('autoplay') === 0)
// First, reset any video to avoid multiple videos from playing. $(player).removeClass('is-playing').find('iframe').attr('src', ''); // Clean up any pause marker. $('.is-paused').removeClass('is-paused'); // Last, pause the slide, for just in case autoplay is on and // pauseOnHover is disabled, and then trigger autoplay. t.closest('.slick').addClass('is-paused').slickPause(); t.closest(player).addClass('is-playing').find('iframe').attr('src', url); }) // Closes the video. .on('click.media-close', '.media-icon--close', function (e) { e.preventDefault(); $(this).closest(player).removeClass('is-playing').find('iframe').attr('src', ''); $('.is-paused').removeClass('is-paused'); }) // Turns off video if any button clicked. .on('click.media-close-other', '.slick__arrow button, > button', function (e) { e.preventDefault(); t.find('.media-icon--close').trigger('click.media-close'); }); }); } }; // Turn off current video if the slide changes, e.g. by dragging the slide. Drupal.slick.callbacks.onAfterChange = function (slider, index) { $('.media-icon--close', '#' + slider.$slider.attr('id')).trigger('click.media-close'); }; })(jQuery);
{ url = url.indexOf('?') < 0 ? url + '?autoplay=1' : url + '&amp;autoplay=1'; }
conditional_block
jsclass_async.js
/********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ function
(o){var resp=YAHOO.lang.JSON.parse(o.responseText),request_id=o.tId,result=resp.result;if(result==null){return;} reqid=global_request_registry[request_id];if(typeof(reqid)!='undefined'){widget=global_request_registry[request_id][0];method_name=global_request_registry[request_id][1];widget[method_name](result);}} SugarClass.inherit("SugarVCalClient","SugarClass");function SugarVCalClient(){this.init();} SugarVCalClient.prototype.init=function(){} SugarVCalClient.prototype.load=function(user_id,request_id){this.user_id=user_id;YAHOO.util.Connect.asyncRequest('GET','./vcal_server.php?type=vfb&source=outlook&noAuth=noAuth&user_id='+user_id,{success:function(result){if(typeof GLOBAL_REGISTRY.freebusy=='undefined'){GLOBAL_REGISTRY.freebusy=new Object();} if(typeof GLOBAL_REGISTRY.freebusy_adjusted=='undefined'){GLOBAL_REGISTRY.freebusy_adjusted=new Object();} GLOBAL_REGISTRY.freebusy[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,false);GLOBAL_REGISTRY.freebusy_adjusted[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,true);global_request_registry[request_id][0].display();},failure:function(result){this.success(result);},argument:{result:result}});} SugarVCalClient.prototype.parseResults=function(textResult,adjusted){var match=/FREEBUSY.*?\:([\w]+)\/([\w]+)/g;var result;var timehash=new Object();var dst_start;var dst_end;if(GLOBAL_REGISTRY.current_user.fields.dst_start==null) dst_start='19700101T000000Z';else dst_start=GLOBAL_REGISTRY.current_user.fields.dst_start.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';if(GLOBAL_REGISTRY.current_user.fields.dst_end==null) dst_end='19700101T000000Z';else dst_end=GLOBAL_REGISTRY.current_user.fields.dst_end.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';gmt_offset_secs=GLOBAL_REGISTRY.current_user.fields.gmt_offset*60;while(((result=match.exec(textResult)))!=null){var startdate;var enddate;if(adjusted){startdate=SugarDateTime.parseAdjustedDate(result[1],dst_start,dst_end,gmt_offset_secs);enddate=SugarDateTime.parseAdjustedDate(result[2],dst_start,dst_end,gmt_offset_secs);} else{startdate=SugarDateTime.parseUTCDate(result[1]);enddate=SugarDateTime.parseUTCDate(result[2]);} var startmins=startdate.getUTCMinutes();if(startmins>=0&&startmins<15){startdate.setUTCMinutes(0);} else if(startmins>=15&&startmins<30){startdate.setUTCMinutes(15);} else if(startmins>=30&&startmins<45){startdate.setUTCMinutes(30);} else{startdate.setUTCMinutes(45);} while(startdate.valueOf()<enddate.valueOf()){var hash=SugarDateTime.getUTCHash(startdate);if(typeof(timehash[hash])=='undefined'){timehash[hash]=0;} timehash[hash]+=1;startdate=new Date(startdate.valueOf()+(15*60*1000));}} return timehash;} SugarVCalClient.parseResults=SugarVCalClient.prototype.parseResults;SugarRPCClient.allowed_methods=['retrieve','query','save','set_accept_status','get_objects_from_module','email','get_user_array','get_full_list'];SugarClass.inherit("SugarRPCClient","SugarClass");function SugarRPCClient(){this.init();} SugarRPCClient.prototype.allowed_methods=['retrieve','query','get_objects_from_module'];SugarRPCClient.prototype.init=function(){this._showError=function(e){alert("ERROR CONNECTING to: ./index.php?entryPoint=json_server, ERROR:"+e);} this.serviceURL='./index.php?entryPoint=json_server';} SugarRPCClient.prototype.call_method=function(method,args,synchronous){var result,transaction,post_data=YAHOO.lang.JSON.stringify({method:method,id:1,params:[args]});synchronous=synchronous||false;try{if(synchronous){result=http_fetch_sync(this.serviceURL,post_data);result=YAHOO.lang.JSON.parse(result.responseText).result;return result;}else{transaction=YAHOO.util.Connect.asyncRequest('POST',this.serviceURL,{success:method_callback,failure:method_callback},post_data);return transaction.tId;}}catch(e){this._showError(e);}} var global_rpcClient=new SugarRPCClient();
method_callback
identifier_name
jsclass_async.js
/********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ function method_callback(o)
SugarClass.inherit("SugarVCalClient","SugarClass");function SugarVCalClient(){this.init();} SugarVCalClient.prototype.init=function(){} SugarVCalClient.prototype.load=function(user_id,request_id){this.user_id=user_id;YAHOO.util.Connect.asyncRequest('GET','./vcal_server.php?type=vfb&source=outlook&noAuth=noAuth&user_id='+user_id,{success:function(result){if(typeof GLOBAL_REGISTRY.freebusy=='undefined'){GLOBAL_REGISTRY.freebusy=new Object();} if(typeof GLOBAL_REGISTRY.freebusy_adjusted=='undefined'){GLOBAL_REGISTRY.freebusy_adjusted=new Object();} GLOBAL_REGISTRY.freebusy[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,false);GLOBAL_REGISTRY.freebusy_adjusted[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,true);global_request_registry[request_id][0].display();},failure:function(result){this.success(result);},argument:{result:result}});} SugarVCalClient.prototype.parseResults=function(textResult,adjusted){var match=/FREEBUSY.*?\:([\w]+)\/([\w]+)/g;var result;var timehash=new Object();var dst_start;var dst_end;if(GLOBAL_REGISTRY.current_user.fields.dst_start==null) dst_start='19700101T000000Z';else dst_start=GLOBAL_REGISTRY.current_user.fields.dst_start.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';if(GLOBAL_REGISTRY.current_user.fields.dst_end==null) dst_end='19700101T000000Z';else dst_end=GLOBAL_REGISTRY.current_user.fields.dst_end.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';gmt_offset_secs=GLOBAL_REGISTRY.current_user.fields.gmt_offset*60;while(((result=match.exec(textResult)))!=null){var startdate;var enddate;if(adjusted){startdate=SugarDateTime.parseAdjustedDate(result[1],dst_start,dst_end,gmt_offset_secs);enddate=SugarDateTime.parseAdjustedDate(result[2],dst_start,dst_end,gmt_offset_secs);} else{startdate=SugarDateTime.parseUTCDate(result[1]);enddate=SugarDateTime.parseUTCDate(result[2]);} var startmins=startdate.getUTCMinutes();if(startmins>=0&&startmins<15){startdate.setUTCMinutes(0);} else if(startmins>=15&&startmins<30){startdate.setUTCMinutes(15);} else if(startmins>=30&&startmins<45){startdate.setUTCMinutes(30);} else{startdate.setUTCMinutes(45);} while(startdate.valueOf()<enddate.valueOf()){var hash=SugarDateTime.getUTCHash(startdate);if(typeof(timehash[hash])=='undefined'){timehash[hash]=0;} timehash[hash]+=1;startdate=new Date(startdate.valueOf()+(15*60*1000));}} return timehash;} SugarVCalClient.parseResults=SugarVCalClient.prototype.parseResults;SugarRPCClient.allowed_methods=['retrieve','query','save','set_accept_status','get_objects_from_module','email','get_user_array','get_full_list'];SugarClass.inherit("SugarRPCClient","SugarClass");function SugarRPCClient(){this.init();} SugarRPCClient.prototype.allowed_methods=['retrieve','query','get_objects_from_module'];SugarRPCClient.prototype.init=function(){this._showError=function(e){alert("ERROR CONNECTING to: ./index.php?entryPoint=json_server, ERROR:"+e);} this.serviceURL='./index.php?entryPoint=json_server';} SugarRPCClient.prototype.call_method=function(method,args,synchronous){var result,transaction,post_data=YAHOO.lang.JSON.stringify({method:method,id:1,params:[args]});synchronous=synchronous||false;try{if(synchronous){result=http_fetch_sync(this.serviceURL,post_data);result=YAHOO.lang.JSON.parse(result.responseText).result;return result;}else{transaction=YAHOO.util.Connect.asyncRequest('POST',this.serviceURL,{success:method_callback,failure:method_callback},post_data);return transaction.tId;}}catch(e){this._showError(e);}} var global_rpcClient=new SugarRPCClient();
{var resp=YAHOO.lang.JSON.parse(o.responseText),request_id=o.tId,result=resp.result;if(result==null){return;} reqid=global_request_registry[request_id];if(typeof(reqid)!='undefined'){widget=global_request_registry[request_id][0];method_name=global_request_registry[request_id][1];widget[method_name](result);}}
identifier_body
jsclass_async.js
/*********************************************************************************
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ function method_callback(o){var resp=YAHOO.lang.JSON.parse(o.responseText),request_id=o.tId,result=resp.result;if(result==null){return;} reqid=global_request_registry[request_id];if(typeof(reqid)!='undefined'){widget=global_request_registry[request_id][0];method_name=global_request_registry[request_id][1];widget[method_name](result);}} SugarClass.inherit("SugarVCalClient","SugarClass");function SugarVCalClient(){this.init();} SugarVCalClient.prototype.init=function(){} SugarVCalClient.prototype.load=function(user_id,request_id){this.user_id=user_id;YAHOO.util.Connect.asyncRequest('GET','./vcal_server.php?type=vfb&source=outlook&noAuth=noAuth&user_id='+user_id,{success:function(result){if(typeof GLOBAL_REGISTRY.freebusy=='undefined'){GLOBAL_REGISTRY.freebusy=new Object();} if(typeof GLOBAL_REGISTRY.freebusy_adjusted=='undefined'){GLOBAL_REGISTRY.freebusy_adjusted=new Object();} GLOBAL_REGISTRY.freebusy[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,false);GLOBAL_REGISTRY.freebusy_adjusted[user_id]=SugarVCalClient.prototype.parseResults(result.responseText,true);global_request_registry[request_id][0].display();},failure:function(result){this.success(result);},argument:{result:result}});} SugarVCalClient.prototype.parseResults=function(textResult,adjusted){var match=/FREEBUSY.*?\:([\w]+)\/([\w]+)/g;var result;var timehash=new Object();var dst_start;var dst_end;if(GLOBAL_REGISTRY.current_user.fields.dst_start==null) dst_start='19700101T000000Z';else dst_start=GLOBAL_REGISTRY.current_user.fields.dst_start.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';if(GLOBAL_REGISTRY.current_user.fields.dst_end==null) dst_end='19700101T000000Z';else dst_end=GLOBAL_REGISTRY.current_user.fields.dst_end.replace(/ /gi,'T').replace(/:/gi,'').replace(/-/gi,'')+'Z';gmt_offset_secs=GLOBAL_REGISTRY.current_user.fields.gmt_offset*60;while(((result=match.exec(textResult)))!=null){var startdate;var enddate;if(adjusted){startdate=SugarDateTime.parseAdjustedDate(result[1],dst_start,dst_end,gmt_offset_secs);enddate=SugarDateTime.parseAdjustedDate(result[2],dst_start,dst_end,gmt_offset_secs);} else{startdate=SugarDateTime.parseUTCDate(result[1]);enddate=SugarDateTime.parseUTCDate(result[2]);} var startmins=startdate.getUTCMinutes();if(startmins>=0&&startmins<15){startdate.setUTCMinutes(0);} else if(startmins>=15&&startmins<30){startdate.setUTCMinutes(15);} else if(startmins>=30&&startmins<45){startdate.setUTCMinutes(30);} else{startdate.setUTCMinutes(45);} while(startdate.valueOf()<enddate.valueOf()){var hash=SugarDateTime.getUTCHash(startdate);if(typeof(timehash[hash])=='undefined'){timehash[hash]=0;} timehash[hash]+=1;startdate=new Date(startdate.valueOf()+(15*60*1000));}} return timehash;} SugarVCalClient.parseResults=SugarVCalClient.prototype.parseResults;SugarRPCClient.allowed_methods=['retrieve','query','save','set_accept_status','get_objects_from_module','email','get_user_array','get_full_list'];SugarClass.inherit("SugarRPCClient","SugarClass");function SugarRPCClient(){this.init();} SugarRPCClient.prototype.allowed_methods=['retrieve','query','get_objects_from_module'];SugarRPCClient.prototype.init=function(){this._showError=function(e){alert("ERROR CONNECTING to: ./index.php?entryPoint=json_server, ERROR:"+e);} this.serviceURL='./index.php?entryPoint=json_server';} SugarRPCClient.prototype.call_method=function(method,args,synchronous){var result,transaction,post_data=YAHOO.lang.JSON.stringify({method:method,id:1,params:[args]});synchronous=synchronous||false;try{if(synchronous){result=http_fetch_sync(this.serviceURL,post_data);result=YAHOO.lang.JSON.parse(result.responseText).result;return result;}else{transaction=YAHOO.util.Connect.asyncRequest('POST',this.serviceURL,{success:method_callback,failure:method_callback},post_data);return transaction.tId;}}catch(e){this._showError(e);}} var global_rpcClient=new SugarRPCClient();
* SugarCRM Community Edition is a customer relationship management program developed by
random_line_split
OfferManager.py
import re from gi.repository import GObject from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \ PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \ WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \ ACTION_ERROR_CLOCK_NOT_PAUSED, ACTION_ERROR_NONE_TO_ACCEPT, ACTION_ERROR_NONE_TO_WITHDRAW, \ ACTION_ERROR_NONE_TO_DECLINE, ACTION_ERROR_TOO_LARGE_UNDO, ACTION_ERROR_NOT_OUT_OF_TIME from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.ic import GAME_TYPES, VariantGameType from pychess.ic.FICSObjects import FICSChallenge names = "\w+(?:\([A-Z\*]+\))*" rated = "(rated|unrated)" colors = "(?:\[(white|black)\])?" ratings = "\(([0-9\ \-\+]{1,4}[E P]?)\)" loaded_from = "(?: Loaded from (wild[/\w]*))?" adjourned = "(?: (\(adjourned\)))?" matchreUntimed = re.compile("(\w+) %s %s ?(\w+) %s %s (untimed)\s*" % (ratings, colors, ratings, rated)) matchre = re.compile( "(\w+) %s %s ?(\w+) %s %s (\w+) (\d+) (\d+)%s%s" % (ratings, colors, ratings, rated, loaded_from, adjourned)) # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) [black] GuestNXMP (----) unrated blitz 2 12 # <pf> 16 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated wild 2 12 Loaded from wild/fr # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated blitz 2 12 (adjourned) # <pf> 45 w=GuestGYXR t=match p=GuestGYXR (----) Lobais (----) unrated losers 2 12 # <pf> 45 w=GuestYDDR t=match p=GuestYDDR (----) mgatto (1358) unrated untimed # <pf> 71 w=joseph t=match p=joseph (1632) mgatto (1742) rated wild 5 1 Loaded from wild/fr (adjourned) # <pf> 59 w=antiseptic t=match p=antiseptic (1945) mgatto (1729) rated wild 6 1 Loaded from wild/4 (adjourned) # # Known offers: abort accept adjourn draw match pause unpause switch takeback # strToOfferType = { "draw": DRAW_OFFER, "abort": ABORT_OFFER, "adjourn": ADJOURN_OFFER, "takeback": TAKEBACK_OFFER, "pause": PAUSE_OFFER, "unpause": RESUME_OFFER, "switch": SWITCH_OFFER, "resign": RESIGNATION, "flag": FLAG_CALL, "match": MATCH_OFFER } offerTypeToStr = {} for k, v in strToOfferType.items(): offerTypeToStr[v] = k class OfferManager(GObject.GObject): __gsignals__ = { 'onOfferAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferRemove': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferDeclined': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeRemove': (GObject.SignalFlags.RUN_FIRST, None, (int, )), 'onActionError': (GObject.SignalFlags.RUN_FIRST, None, (object, int)), } def __init__(self, connection): GObject.GObject.__init__(self) self.connection = connection self.connection.expect_line( self.onOfferAdd, "<p(t|f)> (\d+) w=%s t=(\w+) p=(.+)" % names) self.connection.expect_line(self.onOfferRemove, "<pr> (\d+)") for ficsstring, offer, error in ( ("You cannot switch sides once a game is underway.", Offer(SWITCH_OFFER), ACTION_ERROR_SWITCH_UNDERWAY), ("Opponent is not out of time.", Offer(FLAG_CALL), ACTION_ERROR_NOT_OUT_OF_TIME), ("The clock is not ticking yet.", Offer(PAUSE_OFFER), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not ticking.", Offer(FLAG_CALL), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not paused.", Offer(RESUME_OFFER), ACTION_ERROR_CLOCK_NOT_PAUSED)): self.connection.expect_line( lambda match: self.emit("onActionError", offer, error), ficsstring) self.connection.expect_line( self.notEnoughMovesToUndo, "There are (?:(no)|only (\d+) half) moves in your game\.") self.connection.expect_line(self.noOffersToAccept, "There are no ([^ ]+) offers to (accept).") self.connection.expect_line( self.onOfferDeclined, "\w+ declines the (draw|takeback|pause|unpause|abort|adjourn) request\.") self.lastPly = 0 self.offers = {} self.connection.client.run_command("iset pendinfo 1") def onOfferDeclined(self, match): log.debug("OfferManager.onOfferDeclined: match.string=%s" % match.string) type = match.groups()[0] offer = Offer(strToOfferType[type]) self.emit("onOfferDeclined", offer) def noOffersToAccept(self, match): offertype, request = match.groups() if request == "accept": error = ACTION_ERROR_NONE_TO_ACCEPT elif request == "withdraw": error = ACTION_ERROR_NONE_TO_WITHDRAW elif request == "decline": error = ACTION_ERROR_NONE_TO_DECLINE offer = Offer(strToOfferType[offertype]) self.emit("onActionError", offer, error) def notEnoughMovesToUndo(self, match): ply = match.groups()[0] or match.groups()[1] if ply == "no": ply = 0 else: ply = int(ply) offer = Offer(TAKEBACK_OFFER, param=self.lastPly - ply) self.emit("onActionError", offer, ACTION_ERROR_TOO_LARGE_UNDO) def onOfferAdd(self, match): log.debug("OfferManager.onOfferAdd: match.string=%s" % match.string) tofrom, index, offertype, parameters = match.groups() index = int(index) if tofrom == "t": # ICGameModel keeps track of the offers we've sent ourselves, so we # don't need this return if offertype not in strToOfferType: log.warning("OfferManager.onOfferAdd: Declining unknown offer type: " + "offertype=%s parameters=%s index=%d" % (offertype, parameters, index)) self.connection.client.run_command("decline %d" % index) return offertype = strToOfferType[offertype] if offertype == TAKEBACK_OFFER: offer = Offer(offertype, param=int(parameters), index=index) else: offer = Offer(offertype, index=index) self.offers[offer.index] = offer if offer.type == MATCH_OFFER: is_adjourned = False if matchreUntimed.match(parameters) is not None: fname, frating, col, tname, trating, rated, type = \ matchreUntimed.match(parameters).groups() mins = 0 incr = 0 gametype = GAME_TYPES["untimed"] else: fname, frating, col, tname, trating, rated, gametype, mins, \ incr, wildtype, adjourned = matchre.match(parameters).groups() if (wildtype and "adjourned" in wildtype) or \ (adjourned and "adjourned" in adjourned): is_adjourned = True if wildtype and "wild" in wildtype: gametype = wildtype try: gametype = GAME_TYPES[gametype] except KeyError: log.warning("OfferManager.onOfferAdd: auto-declining " + "unknown offer type: '%s'\n" % gametype) self.decline(offer) del self.offers[offer.index] return player = self.connection.players.get(fname) rating = frating.strip() rating = int(rating) if rating.isdigit() else 0 if gametype.rating_type in player.ratings and \ player.ratings[gametype.rating_type] != rating: player.ratings[gametype.rating_type] = rating player.emit("ratings_changed", gametype.rating_type, player) rated = rated != "unrated" challenge = FICSChallenge(index, player, int(mins), int(incr), rated, col, gametype, adjourned=is_adjourned)
self.emit("onOfferAdd", offer) def onOfferRemove(self, match): log.debug("OfferManager.onOfferRemove: match.string=%s" % match.string) index = int(match.groups()[0]) if index not in self.offers: return if self.offers[index].type == MATCH_OFFER: self.emit("onChallengeRemove", index) else: self.emit("onOfferRemove", self.offers[index]) del self.offers[index] ### def challenge(self, player_name, game_type, startmin, incsec, rated, color=None): log.debug("OfferManager.challenge: %s %s %s %s %s %s" % (player_name, game_type, startmin, incsec, rated, color)) rchar = rated and "r" or "u" if color is not None: cchar = color == WHITE and "w" or "b" else: cchar = "" s = "match %s %d %d %s %s" % \ (player_name, startmin, incsec, rchar, cchar) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text self.connection.client.run_command(s) def offer(self, offer, curply): log.debug("OfferManager.offer: curply=%s %s" % (curply, offer)) self.lastPly = curply s = offerTypeToStr[offer.type] if offer.type == TAKEBACK_OFFER: s += " " + str(curply - offer.param) self.connection.client.run_command(s) ### def withdraw(self, offer): log.debug("OfferManager.withdraw: %s" % offer) self.connection.client.run_command("withdraw t %s" % offerTypeToStr[offer.type]) def accept(self, offer): log.debug("OfferManager.accept: %s" % offer) if offer.index is not None: self.acceptIndex(offer.index) else: self.connection.client.run_command("accept t %s" % offerTypeToStr[offer.type]) def decline(self, offer): log.debug("OfferManager.decline: %s" % offer) if offer.index is not None: self.declineIndex(offer.index) else: self.connection.client.run_command("decline t %s" % offerTypeToStr[offer.type]) def acceptIndex(self, index): log.debug("OfferManager.acceptIndex: index=%s" % index) self.connection.client.run_command("accept %s" % index) def declineIndex(self, index): log.debug("OfferManager.declineIndex: index=%s" % index) self.connection.client.run_command("decline %s" % index) def playIndex(self, index): log.debug("OfferManager.playIndex: index=%s" % index) self.connection.client.run_command("play %s" % index)
self.emit("onChallengeAdd", challenge) else: log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" % offer)
random_line_split
OfferManager.py
import re from gi.repository import GObject from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \ PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \ WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \ ACTION_ERROR_CLOCK_NOT_PAUSED, ACTION_ERROR_NONE_TO_ACCEPT, ACTION_ERROR_NONE_TO_WITHDRAW, \ ACTION_ERROR_NONE_TO_DECLINE, ACTION_ERROR_TOO_LARGE_UNDO, ACTION_ERROR_NOT_OUT_OF_TIME from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.ic import GAME_TYPES, VariantGameType from pychess.ic.FICSObjects import FICSChallenge names = "\w+(?:\([A-Z\*]+\))*" rated = "(rated|unrated)" colors = "(?:\[(white|black)\])?" ratings = "\(([0-9\ \-\+]{1,4}[E P]?)\)" loaded_from = "(?: Loaded from (wild[/\w]*))?" adjourned = "(?: (\(adjourned\)))?" matchreUntimed = re.compile("(\w+) %s %s ?(\w+) %s %s (untimed)\s*" % (ratings, colors, ratings, rated)) matchre = re.compile( "(\w+) %s %s ?(\w+) %s %s (\w+) (\d+) (\d+)%s%s" % (ratings, colors, ratings, rated, loaded_from, adjourned)) # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) [black] GuestNXMP (----) unrated blitz 2 12 # <pf> 16 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated wild 2 12 Loaded from wild/fr # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated blitz 2 12 (adjourned) # <pf> 45 w=GuestGYXR t=match p=GuestGYXR (----) Lobais (----) unrated losers 2 12 # <pf> 45 w=GuestYDDR t=match p=GuestYDDR (----) mgatto (1358) unrated untimed # <pf> 71 w=joseph t=match p=joseph (1632) mgatto (1742) rated wild 5 1 Loaded from wild/fr (adjourned) # <pf> 59 w=antiseptic t=match p=antiseptic (1945) mgatto (1729) rated wild 6 1 Loaded from wild/4 (adjourned) # # Known offers: abort accept adjourn draw match pause unpause switch takeback # strToOfferType = { "draw": DRAW_OFFER, "abort": ABORT_OFFER, "adjourn": ADJOURN_OFFER, "takeback": TAKEBACK_OFFER, "pause": PAUSE_OFFER, "unpause": RESUME_OFFER, "switch": SWITCH_OFFER, "resign": RESIGNATION, "flag": FLAG_CALL, "match": MATCH_OFFER } offerTypeToStr = {} for k, v in strToOfferType.items(): offerTypeToStr[v] = k class OfferManager(GObject.GObject): __gsignals__ = { 'onOfferAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferRemove': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferDeclined': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeRemove': (GObject.SignalFlags.RUN_FIRST, None, (int, )), 'onActionError': (GObject.SignalFlags.RUN_FIRST, None, (object, int)), } def __init__(self, connection): GObject.GObject.__init__(self) self.connection = connection self.connection.expect_line( self.onOfferAdd, "<p(t|f)> (\d+) w=%s t=(\w+) p=(.+)" % names) self.connection.expect_line(self.onOfferRemove, "<pr> (\d+)") for ficsstring, offer, error in ( ("You cannot switch sides once a game is underway.", Offer(SWITCH_OFFER), ACTION_ERROR_SWITCH_UNDERWAY), ("Opponent is not out of time.", Offer(FLAG_CALL), ACTION_ERROR_NOT_OUT_OF_TIME), ("The clock is not ticking yet.", Offer(PAUSE_OFFER), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not ticking.", Offer(FLAG_CALL), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not paused.", Offer(RESUME_OFFER), ACTION_ERROR_CLOCK_NOT_PAUSED)): self.connection.expect_line( lambda match: self.emit("onActionError", offer, error), ficsstring) self.connection.expect_line( self.notEnoughMovesToUndo, "There are (?:(no)|only (\d+) half) moves in your game\.") self.connection.expect_line(self.noOffersToAccept, "There are no ([^ ]+) offers to (accept).") self.connection.expect_line( self.onOfferDeclined, "\w+ declines the (draw|takeback|pause|unpause|abort|adjourn) request\.") self.lastPly = 0 self.offers = {} self.connection.client.run_command("iset pendinfo 1") def onOfferDeclined(self, match): log.debug("OfferManager.onOfferDeclined: match.string=%s" % match.string) type = match.groups()[0] offer = Offer(strToOfferType[type]) self.emit("onOfferDeclined", offer) def noOffersToAccept(self, match): offertype, request = match.groups() if request == "accept": error = ACTION_ERROR_NONE_TO_ACCEPT elif request == "withdraw": error = ACTION_ERROR_NONE_TO_WITHDRAW elif request == "decline": error = ACTION_ERROR_NONE_TO_DECLINE offer = Offer(strToOfferType[offertype]) self.emit("onActionError", offer, error) def notEnoughMovesToUndo(self, match): ply = match.groups()[0] or match.groups()[1] if ply == "no": ply = 0 else: ply = int(ply) offer = Offer(TAKEBACK_OFFER, param=self.lastPly - ply) self.emit("onActionError", offer, ACTION_ERROR_TOO_LARGE_UNDO) def onOfferAdd(self, match): log.debug("OfferManager.onOfferAdd: match.string=%s" % match.string) tofrom, index, offertype, parameters = match.groups() index = int(index) if tofrom == "t": # ICGameModel keeps track of the offers we've sent ourselves, so we # don't need this return if offertype not in strToOfferType: log.warning("OfferManager.onOfferAdd: Declining unknown offer type: " + "offertype=%s parameters=%s index=%d" % (offertype, parameters, index)) self.connection.client.run_command("decline %d" % index) return offertype = strToOfferType[offertype] if offertype == TAKEBACK_OFFER: offer = Offer(offertype, param=int(parameters), index=index) else: offer = Offer(offertype, index=index) self.offers[offer.index] = offer if offer.type == MATCH_OFFER: is_adjourned = False if matchreUntimed.match(parameters) is not None: fname, frating, col, tname, trating, rated, type = \ matchreUntimed.match(parameters).groups() mins = 0 incr = 0 gametype = GAME_TYPES["untimed"] else: fname, frating, col, tname, trating, rated, gametype, mins, \ incr, wildtype, adjourned = matchre.match(parameters).groups() if (wildtype and "adjourned" in wildtype) or \ (adjourned and "adjourned" in adjourned): is_adjourned = True if wildtype and "wild" in wildtype: gametype = wildtype try: gametype = GAME_TYPES[gametype] except KeyError: log.warning("OfferManager.onOfferAdd: auto-declining " + "unknown offer type: '%s'\n" % gametype) self.decline(offer) del self.offers[offer.index] return player = self.connection.players.get(fname) rating = frating.strip() rating = int(rating) if rating.isdigit() else 0 if gametype.rating_type in player.ratings and \ player.ratings[gametype.rating_type] != rating: player.ratings[gametype.rating_type] = rating player.emit("ratings_changed", gametype.rating_type, player) rated = rated != "unrated" challenge = FICSChallenge(index, player, int(mins), int(incr), rated, col, gametype, adjourned=is_adjourned) self.emit("onChallengeAdd", challenge) else: log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" % offer) self.emit("onOfferAdd", offer) def onOfferRemove(self, match): log.debug("OfferManager.onOfferRemove: match.string=%s" % match.string) index = int(match.groups()[0]) if index not in self.offers: return if self.offers[index].type == MATCH_OFFER: self.emit("onChallengeRemove", index) else: self.emit("onOfferRemove", self.offers[index]) del self.offers[index] ### def challenge(self, player_name, game_type, startmin, incsec, rated, color=None): log.debug("OfferManager.challenge: %s %s %s %s %s %s" % (player_name, game_type, startmin, incsec, rated, color)) rchar = rated and "r" or "u" if color is not None: cchar = color == WHITE and "w" or "b" else: cchar = "" s = "match %s %d %d %s %s" % \ (player_name, startmin, incsec, rchar, cchar) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text self.connection.client.run_command(s) def offer(self, offer, curply): log.debug("OfferManager.offer: curply=%s %s" % (curply, offer)) self.lastPly = curply s = offerTypeToStr[offer.type] if offer.type == TAKEBACK_OFFER: s += " " + str(curply - offer.param) self.connection.client.run_command(s) ### def withdraw(self, offer): log.debug("OfferManager.withdraw: %s" % offer) self.connection.client.run_command("withdraw t %s" % offerTypeToStr[offer.type]) def accept(self, offer): log.debug("OfferManager.accept: %s" % offer) if offer.index is not None: self.acceptIndex(offer.index) else: self.connection.client.run_command("accept t %s" % offerTypeToStr[offer.type]) def decline(self, offer): log.debug("OfferManager.decline: %s" % offer) if offer.index is not None: self.declineIndex(offer.index) else: self.connection.client.run_command("decline t %s" % offerTypeToStr[offer.type]) def acceptIndex(self, index): log.debug("OfferManager.acceptIndex: index=%s" % index) self.connection.client.run_command("accept %s" % index) def declineIndex(self, index): log.debug("OfferManager.declineIndex: index=%s" % index) self.connection.client.run_command("decline %s" % index) def playIndex(self, index):
log.debug("OfferManager.playIndex: index=%s" % index) self.connection.client.run_command("play %s" % index)
identifier_body
OfferManager.py
import re from gi.repository import GObject from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \ PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \ WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \ ACTION_ERROR_CLOCK_NOT_PAUSED, ACTION_ERROR_NONE_TO_ACCEPT, ACTION_ERROR_NONE_TO_WITHDRAW, \ ACTION_ERROR_NONE_TO_DECLINE, ACTION_ERROR_TOO_LARGE_UNDO, ACTION_ERROR_NOT_OUT_OF_TIME from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.ic import GAME_TYPES, VariantGameType from pychess.ic.FICSObjects import FICSChallenge names = "\w+(?:\([A-Z\*]+\))*" rated = "(rated|unrated)" colors = "(?:\[(white|black)\])?" ratings = "\(([0-9\ \-\+]{1,4}[E P]?)\)" loaded_from = "(?: Loaded from (wild[/\w]*))?" adjourned = "(?: (\(adjourned\)))?" matchreUntimed = re.compile("(\w+) %s %s ?(\w+) %s %s (untimed)\s*" % (ratings, colors, ratings, rated)) matchre = re.compile( "(\w+) %s %s ?(\w+) %s %s (\w+) (\d+) (\d+)%s%s" % (ratings, colors, ratings, rated, loaded_from, adjourned)) # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) [black] GuestNXMP (----) unrated blitz 2 12 # <pf> 16 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated wild 2 12 Loaded from wild/fr # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated blitz 2 12 (adjourned) # <pf> 45 w=GuestGYXR t=match p=GuestGYXR (----) Lobais (----) unrated losers 2 12 # <pf> 45 w=GuestYDDR t=match p=GuestYDDR (----) mgatto (1358) unrated untimed # <pf> 71 w=joseph t=match p=joseph (1632) mgatto (1742) rated wild 5 1 Loaded from wild/fr (adjourned) # <pf> 59 w=antiseptic t=match p=antiseptic (1945) mgatto (1729) rated wild 6 1 Loaded from wild/4 (adjourned) # # Known offers: abort accept adjourn draw match pause unpause switch takeback # strToOfferType = { "draw": DRAW_OFFER, "abort": ABORT_OFFER, "adjourn": ADJOURN_OFFER, "takeback": TAKEBACK_OFFER, "pause": PAUSE_OFFER, "unpause": RESUME_OFFER, "switch": SWITCH_OFFER, "resign": RESIGNATION, "flag": FLAG_CALL, "match": MATCH_OFFER } offerTypeToStr = {} for k, v in strToOfferType.items(): offerTypeToStr[v] = k class OfferManager(GObject.GObject): __gsignals__ = { 'onOfferAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferRemove': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferDeclined': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeRemove': (GObject.SignalFlags.RUN_FIRST, None, (int, )), 'onActionError': (GObject.SignalFlags.RUN_FIRST, None, (object, int)), } def __init__(self, connection): GObject.GObject.__init__(self) self.connection = connection self.connection.expect_line( self.onOfferAdd, "<p(t|f)> (\d+) w=%s t=(\w+) p=(.+)" % names) self.connection.expect_line(self.onOfferRemove, "<pr> (\d+)") for ficsstring, offer, error in ( ("You cannot switch sides once a game is underway.", Offer(SWITCH_OFFER), ACTION_ERROR_SWITCH_UNDERWAY), ("Opponent is not out of time.", Offer(FLAG_CALL), ACTION_ERROR_NOT_OUT_OF_TIME), ("The clock is not ticking yet.", Offer(PAUSE_OFFER), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not ticking.", Offer(FLAG_CALL), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not paused.", Offer(RESUME_OFFER), ACTION_ERROR_CLOCK_NOT_PAUSED)): self.connection.expect_line( lambda match: self.emit("onActionError", offer, error), ficsstring) self.connection.expect_line( self.notEnoughMovesToUndo, "There are (?:(no)|only (\d+) half) moves in your game\.") self.connection.expect_line(self.noOffersToAccept, "There are no ([^ ]+) offers to (accept).") self.connection.expect_line( self.onOfferDeclined, "\w+ declines the (draw|takeback|pause|unpause|abort|adjourn) request\.") self.lastPly = 0 self.offers = {} self.connection.client.run_command("iset pendinfo 1") def onOfferDeclined(self, match): log.debug("OfferManager.onOfferDeclined: match.string=%s" % match.string) type = match.groups()[0] offer = Offer(strToOfferType[type]) self.emit("onOfferDeclined", offer) def noOffersToAccept(self, match): offertype, request = match.groups() if request == "accept": error = ACTION_ERROR_NONE_TO_ACCEPT elif request == "withdraw": error = ACTION_ERROR_NONE_TO_WITHDRAW elif request == "decline": error = ACTION_ERROR_NONE_TO_DECLINE offer = Offer(strToOfferType[offertype]) self.emit("onActionError", offer, error) def notEnoughMovesToUndo(self, match): ply = match.groups()[0] or match.groups()[1] if ply == "no": ply = 0 else: ply = int(ply) offer = Offer(TAKEBACK_OFFER, param=self.lastPly - ply) self.emit("onActionError", offer, ACTION_ERROR_TOO_LARGE_UNDO) def onOfferAdd(self, match): log.debug("OfferManager.onOfferAdd: match.string=%s" % match.string) tofrom, index, offertype, parameters = match.groups() index = int(index) if tofrom == "t": # ICGameModel keeps track of the offers we've sent ourselves, so we # don't need this return if offertype not in strToOfferType: log.warning("OfferManager.onOfferAdd: Declining unknown offer type: " + "offertype=%s parameters=%s index=%d" % (offertype, parameters, index)) self.connection.client.run_command("decline %d" % index) return offertype = strToOfferType[offertype] if offertype == TAKEBACK_OFFER: offer = Offer(offertype, param=int(parameters), index=index) else: offer = Offer(offertype, index=index) self.offers[offer.index] = offer if offer.type == MATCH_OFFER: is_adjourned = False if matchreUntimed.match(parameters) is not None: fname, frating, col, tname, trating, rated, type = \ matchreUntimed.match(parameters).groups() mins = 0 incr = 0 gametype = GAME_TYPES["untimed"] else: fname, frating, col, tname, trating, rated, gametype, mins, \ incr, wildtype, adjourned = matchre.match(parameters).groups() if (wildtype and "adjourned" in wildtype) or \ (adjourned and "adjourned" in adjourned): is_adjourned = True if wildtype and "wild" in wildtype: gametype = wildtype try: gametype = GAME_TYPES[gametype] except KeyError: log.warning("OfferManager.onOfferAdd: auto-declining " + "unknown offer type: '%s'\n" % gametype) self.decline(offer) del self.offers[offer.index] return player = self.connection.players.get(fname) rating = frating.strip() rating = int(rating) if rating.isdigit() else 0 if gametype.rating_type in player.ratings and \ player.ratings[gametype.rating_type] != rating: player.ratings[gametype.rating_type] = rating player.emit("ratings_changed", gametype.rating_type, player) rated = rated != "unrated" challenge = FICSChallenge(index, player, int(mins), int(incr), rated, col, gametype, adjourned=is_adjourned) self.emit("onChallengeAdd", challenge) else: log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" % offer) self.emit("onOfferAdd", offer) def onOfferRemove(self, match): log.debug("OfferManager.onOfferRemove: match.string=%s" % match.string) index = int(match.groups()[0]) if index not in self.offers: return if self.offers[index].type == MATCH_OFFER: self.emit("onChallengeRemove", index) else: self.emit("onOfferRemove", self.offers[index]) del self.offers[index] ### def challenge(self, player_name, game_type, startmin, incsec, rated, color=None): log.debug("OfferManager.challenge: %s %s %s %s %s %s" % (player_name, game_type, startmin, incsec, rated, color)) rchar = rated and "r" or "u" if color is not None: cchar = color == WHITE and "w" or "b" else: cchar = "" s = "match %s %d %d %s %s" % \ (player_name, startmin, incsec, rchar, cchar) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text self.connection.client.run_command(s) def offer(self, offer, curply): log.debug("OfferManager.offer: curply=%s %s" % (curply, offer)) self.lastPly = curply s = offerTypeToStr[offer.type] if offer.type == TAKEBACK_OFFER: s += " " + str(curply - offer.param) self.connection.client.run_command(s) ### def
(self, offer): log.debug("OfferManager.withdraw: %s" % offer) self.connection.client.run_command("withdraw t %s" % offerTypeToStr[offer.type]) def accept(self, offer): log.debug("OfferManager.accept: %s" % offer) if offer.index is not None: self.acceptIndex(offer.index) else: self.connection.client.run_command("accept t %s" % offerTypeToStr[offer.type]) def decline(self, offer): log.debug("OfferManager.decline: %s" % offer) if offer.index is not None: self.declineIndex(offer.index) else: self.connection.client.run_command("decline t %s" % offerTypeToStr[offer.type]) def acceptIndex(self, index): log.debug("OfferManager.acceptIndex: index=%s" % index) self.connection.client.run_command("accept %s" % index) def declineIndex(self, index): log.debug("OfferManager.declineIndex: index=%s" % index) self.connection.client.run_command("decline %s" % index) def playIndex(self, index): log.debug("OfferManager.playIndex: index=%s" % index) self.connection.client.run_command("play %s" % index)
withdraw
identifier_name
OfferManager.py
import re from gi.repository import GObject from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \ PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \ WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \ ACTION_ERROR_CLOCK_NOT_PAUSED, ACTION_ERROR_NONE_TO_ACCEPT, ACTION_ERROR_NONE_TO_WITHDRAW, \ ACTION_ERROR_NONE_TO_DECLINE, ACTION_ERROR_TOO_LARGE_UNDO, ACTION_ERROR_NOT_OUT_OF_TIME from pychess.Utils.Offer import Offer from pychess.System.Log import log from pychess.ic import GAME_TYPES, VariantGameType from pychess.ic.FICSObjects import FICSChallenge names = "\w+(?:\([A-Z\*]+\))*" rated = "(rated|unrated)" colors = "(?:\[(white|black)\])?" ratings = "\(([0-9\ \-\+]{1,4}[E P]?)\)" loaded_from = "(?: Loaded from (wild[/\w]*))?" adjourned = "(?: (\(adjourned\)))?" matchreUntimed = re.compile("(\w+) %s %s ?(\w+) %s %s (untimed)\s*" % (ratings, colors, ratings, rated)) matchre = re.compile( "(\w+) %s %s ?(\w+) %s %s (\w+) (\d+) (\d+)%s%s" % (ratings, colors, ratings, rated, loaded_from, adjourned)) # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) [black] GuestNXMP (----) unrated blitz 2 12 # <pf> 16 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated wild 2 12 Loaded from wild/fr # <pf> 39 w=GuestDVXV t=match p=GuestDVXV (----) GuestNXMP (----) unrated blitz 2 12 (adjourned) # <pf> 45 w=GuestGYXR t=match p=GuestGYXR (----) Lobais (----) unrated losers 2 12 # <pf> 45 w=GuestYDDR t=match p=GuestYDDR (----) mgatto (1358) unrated untimed # <pf> 71 w=joseph t=match p=joseph (1632) mgatto (1742) rated wild 5 1 Loaded from wild/fr (adjourned) # <pf> 59 w=antiseptic t=match p=antiseptic (1945) mgatto (1729) rated wild 6 1 Loaded from wild/4 (adjourned) # # Known offers: abort accept adjourn draw match pause unpause switch takeback # strToOfferType = { "draw": DRAW_OFFER, "abort": ABORT_OFFER, "adjourn": ADJOURN_OFFER, "takeback": TAKEBACK_OFFER, "pause": PAUSE_OFFER, "unpause": RESUME_OFFER, "switch": SWITCH_OFFER, "resign": RESIGNATION, "flag": FLAG_CALL, "match": MATCH_OFFER } offerTypeToStr = {} for k, v in strToOfferType.items(): offerTypeToStr[v] = k class OfferManager(GObject.GObject): __gsignals__ = { 'onOfferAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferRemove': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onOfferDeclined': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeAdd': (GObject.SignalFlags.RUN_FIRST, None, (object, )), 'onChallengeRemove': (GObject.SignalFlags.RUN_FIRST, None, (int, )), 'onActionError': (GObject.SignalFlags.RUN_FIRST, None, (object, int)), } def __init__(self, connection): GObject.GObject.__init__(self) self.connection = connection self.connection.expect_line( self.onOfferAdd, "<p(t|f)> (\d+) w=%s t=(\w+) p=(.+)" % names) self.connection.expect_line(self.onOfferRemove, "<pr> (\d+)") for ficsstring, offer, error in ( ("You cannot switch sides once a game is underway.", Offer(SWITCH_OFFER), ACTION_ERROR_SWITCH_UNDERWAY), ("Opponent is not out of time.", Offer(FLAG_CALL), ACTION_ERROR_NOT_OUT_OF_TIME), ("The clock is not ticking yet.", Offer(PAUSE_OFFER), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not ticking.", Offer(FLAG_CALL), ACTION_ERROR_CLOCK_NOT_STARTED), ("The clock is not paused.", Offer(RESUME_OFFER), ACTION_ERROR_CLOCK_NOT_PAUSED)): self.connection.expect_line( lambda match: self.emit("onActionError", offer, error), ficsstring) self.connection.expect_line( self.notEnoughMovesToUndo, "There are (?:(no)|only (\d+) half) moves in your game\.") self.connection.expect_line(self.noOffersToAccept, "There are no ([^ ]+) offers to (accept).") self.connection.expect_line( self.onOfferDeclined, "\w+ declines the (draw|takeback|pause|unpause|abort|adjourn) request\.") self.lastPly = 0 self.offers = {} self.connection.client.run_command("iset pendinfo 1") def onOfferDeclined(self, match): log.debug("OfferManager.onOfferDeclined: match.string=%s" % match.string) type = match.groups()[0] offer = Offer(strToOfferType[type]) self.emit("onOfferDeclined", offer) def noOffersToAccept(self, match): offertype, request = match.groups() if request == "accept": error = ACTION_ERROR_NONE_TO_ACCEPT elif request == "withdraw": error = ACTION_ERROR_NONE_TO_WITHDRAW elif request == "decline": error = ACTION_ERROR_NONE_TO_DECLINE offer = Offer(strToOfferType[offertype]) self.emit("onActionError", offer, error) def notEnoughMovesToUndo(self, match): ply = match.groups()[0] or match.groups()[1] if ply == "no": ply = 0 else: ply = int(ply) offer = Offer(TAKEBACK_OFFER, param=self.lastPly - ply) self.emit("onActionError", offer, ACTION_ERROR_TOO_LARGE_UNDO) def onOfferAdd(self, match): log.debug("OfferManager.onOfferAdd: match.string=%s" % match.string) tofrom, index, offertype, parameters = match.groups() index = int(index) if tofrom == "t": # ICGameModel keeps track of the offers we've sent ourselves, so we # don't need this return if offertype not in strToOfferType: log.warning("OfferManager.onOfferAdd: Declining unknown offer type: " + "offertype=%s parameters=%s index=%d" % (offertype, parameters, index)) self.connection.client.run_command("decline %d" % index) return offertype = strToOfferType[offertype] if offertype == TAKEBACK_OFFER: offer = Offer(offertype, param=int(parameters), index=index) else: offer = Offer(offertype, index=index) self.offers[offer.index] = offer if offer.type == MATCH_OFFER: is_adjourned = False if matchreUntimed.match(parameters) is not None: fname, frating, col, tname, trating, rated, type = \ matchreUntimed.match(parameters).groups() mins = 0 incr = 0 gametype = GAME_TYPES["untimed"] else: fname, frating, col, tname, trating, rated, gametype, mins, \ incr, wildtype, adjourned = matchre.match(parameters).groups() if (wildtype and "adjourned" in wildtype) or \ (adjourned and "adjourned" in adjourned): is_adjourned = True if wildtype and "wild" in wildtype: gametype = wildtype try: gametype = GAME_TYPES[gametype] except KeyError: log.warning("OfferManager.onOfferAdd: auto-declining " + "unknown offer type: '%s'\n" % gametype) self.decline(offer) del self.offers[offer.index] return player = self.connection.players.get(fname) rating = frating.strip() rating = int(rating) if rating.isdigit() else 0 if gametype.rating_type in player.ratings and \ player.ratings[gametype.rating_type] != rating: player.ratings[gametype.rating_type] = rating player.emit("ratings_changed", gametype.rating_type, player) rated = rated != "unrated" challenge = FICSChallenge(index, player, int(mins), int(incr), rated, col, gametype, adjourned=is_adjourned) self.emit("onChallengeAdd", challenge) else: log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" % offer) self.emit("onOfferAdd", offer) def onOfferRemove(self, match): log.debug("OfferManager.onOfferRemove: match.string=%s" % match.string) index = int(match.groups()[0]) if index not in self.offers: return if self.offers[index].type == MATCH_OFFER: self.emit("onChallengeRemove", index) else: self.emit("onOfferRemove", self.offers[index]) del self.offers[index] ### def challenge(self, player_name, game_type, startmin, incsec, rated, color=None): log.debug("OfferManager.challenge: %s %s %s %s %s %s" % (player_name, game_type, startmin, incsec, rated, color)) rchar = rated and "r" or "u" if color is not None: cchar = color == WHITE and "w" or "b" else: cchar = "" s = "match %s %d %d %s %s" % \ (player_name, startmin, incsec, rchar, cchar) if isinstance(game_type, VariantGameType): s += " " + game_type.seek_text self.connection.client.run_command(s) def offer(self, offer, curply): log.debug("OfferManager.offer: curply=%s %s" % (curply, offer)) self.lastPly = curply s = offerTypeToStr[offer.type] if offer.type == TAKEBACK_OFFER: s += " " + str(curply - offer.param) self.connection.client.run_command(s) ### def withdraw(self, offer): log.debug("OfferManager.withdraw: %s" % offer) self.connection.client.run_command("withdraw t %s" % offerTypeToStr[offer.type]) def accept(self, offer): log.debug("OfferManager.accept: %s" % offer) if offer.index is not None:
else: self.connection.client.run_command("accept t %s" % offerTypeToStr[offer.type]) def decline(self, offer): log.debug("OfferManager.decline: %s" % offer) if offer.index is not None: self.declineIndex(offer.index) else: self.connection.client.run_command("decline t %s" % offerTypeToStr[offer.type]) def acceptIndex(self, index): log.debug("OfferManager.acceptIndex: index=%s" % index) self.connection.client.run_command("accept %s" % index) def declineIndex(self, index): log.debug("OfferManager.declineIndex: index=%s" % index) self.connection.client.run_command("decline %s" % index) def playIndex(self, index): log.debug("OfferManager.playIndex: index=%s" % index) self.connection.client.run_command("play %s" % index)
self.acceptIndex(offer.index)
conditional_block
MessageConnection.js
var util = require('util'); var EventEmitter = require('events').EventEmitter; var MessageCodec = require('./MessageCodec'); exports = module.exports = MessageConnection; function MessageConnection(socket, options)
util.inherits(MessageConnection, EventEmitter); MessageConnection.prototype.send = function(message) { try { this._socket.write(this._messageCodec.encode(message)); } catch (err) { this._onError(err); } }; MessageConnection.prototype._onSockData = function(data) { try { var self = this; this._messageCodec.decode(data, function(message) { self._onMessage(message); }); } catch (err) { this._onError(err); } }; MessageConnection.prototype.close = function() { if(this._socket) { this._socket.destroy(); this._socket = undefined; if(this.onclose) this.onclose(); this.emit('close'); } }; MessageConnection.prototype.destroy = MessageConnection.prototype.close; MessageConnection.prototype._onMessage = function(message) { var event = { data: message }; if(this.onmessage) this.onmessage(event); this.emit('message', event); }; MessageConnection.prototype._onError = function(err) { if(!err.stack) err = new Error(err); if(!this.silent) console.error(err.stack); if(this.onerror) this.onerror(err); this.emit('error', err); this.close(); };
{ EventEmitter.call(this); this._socket = socket; this._messageCodec = new MessageCodec(options); socket.on('data', MessageConnection.prototype._onSockData.bind(this)); socket.on('close', MessageConnection.prototype.close .bind(this)); socket.on('error', MessageConnection.prototype._onError .bind(this)); }
identifier_body
MessageConnection.js
var util = require('util'); var EventEmitter = require('events').EventEmitter; var MessageCodec = require('./MessageCodec'); exports = module.exports = MessageConnection; function
(socket, options) { EventEmitter.call(this); this._socket = socket; this._messageCodec = new MessageCodec(options); socket.on('data', MessageConnection.prototype._onSockData.bind(this)); socket.on('close', MessageConnection.prototype.close .bind(this)); socket.on('error', MessageConnection.prototype._onError .bind(this)); } util.inherits(MessageConnection, EventEmitter); MessageConnection.prototype.send = function(message) { try { this._socket.write(this._messageCodec.encode(message)); } catch (err) { this._onError(err); } }; MessageConnection.prototype._onSockData = function(data) { try { var self = this; this._messageCodec.decode(data, function(message) { self._onMessage(message); }); } catch (err) { this._onError(err); } }; MessageConnection.prototype.close = function() { if(this._socket) { this._socket.destroy(); this._socket = undefined; if(this.onclose) this.onclose(); this.emit('close'); } }; MessageConnection.prototype.destroy = MessageConnection.prototype.close; MessageConnection.prototype._onMessage = function(message) { var event = { data: message }; if(this.onmessage) this.onmessage(event); this.emit('message', event); }; MessageConnection.prototype._onError = function(err) { if(!err.stack) err = new Error(err); if(!this.silent) console.error(err.stack); if(this.onerror) this.onerror(err); this.emit('error', err); this.close(); };
MessageConnection
identifier_name
MessageConnection.js
var util = require('util'); var EventEmitter = require('events').EventEmitter; var MessageCodec = require('./MessageCodec'); exports = module.exports = MessageConnection; function MessageConnection(socket, options) { EventEmitter.call(this); this._socket = socket; this._messageCodec = new MessageCodec(options); socket.on('data', MessageConnection.prototype._onSockData.bind(this)); socket.on('close', MessageConnection.prototype.close .bind(this)); socket.on('error', MessageConnection.prototype._onError .bind(this)); } util.inherits(MessageConnection, EventEmitter); MessageConnection.prototype.send = function(message) { try { this._socket.write(this._messageCodec.encode(message)); } catch (err) { this._onError(err); } }; MessageConnection.prototype._onSockData = function(data) { try { var self = this; this._messageCodec.decode(data, function(message) { self._onMessage(message); }); } catch (err) {
} }; MessageConnection.prototype.close = function() { if(this._socket) { this._socket.destroy(); this._socket = undefined; if(this.onclose) this.onclose(); this.emit('close'); } }; MessageConnection.prototype.destroy = MessageConnection.prototype.close; MessageConnection.prototype._onMessage = function(message) { var event = { data: message }; if(this.onmessage) this.onmessage(event); this.emit('message', event); }; MessageConnection.prototype._onError = function(err) { if(!err.stack) err = new Error(err); if(!this.silent) console.error(err.stack); if(this.onerror) this.onerror(err); this.emit('error', err); this.close(); };
this._onError(err);
random_line_split
login.ts
import Controller from '@ember/controller'; import { get, setProperties, getProperties } from '@ember/object'; import Session from 'ember-simple-auth/services/session'; import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications'; import BannerService from 'wherehows-web/services/banners'; import { alias } from '@ember-decorators/object/computed'; import { service } from '@ember-decorators/service'; import { action } from '@ember-decorators/object'; export default class
extends Controller { /** * References the application session service * @type {Session} * @memberof Login */ @service session: Session; /** * Banner alert service * @type {BannerService} * @memberof Login */ @service banners: BannerService; /** * Aliases the name property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('name') username: string; /** * Aliases the password computed property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('pass') password: string; /** * On instantiation, error message reference is an empty string value * @type {string} * @memberof Login */ errorMessage = ''; @action authenticateUser(this: Login): void { const { username, password, banners } = getProperties(this, ['username', 'password', 'banners']); get(this, 'session') .authenticate('authenticator:custom-ldap', username, password) .then(results => { // Once user has chosen to authenticate, then we remove the login banner (if it exists) since it will // no longer be relevant banners.removeBanner(twoFABannerMessage, twoFABannerType); return results; }) .catch(({ responseText = 'Bad Credentials' }) => setProperties(this, { errorMessage: responseText })); } }
Login
identifier_name
login.ts
import Controller from '@ember/controller'; import { get, setProperties, getProperties } from '@ember/object'; import Session from 'ember-simple-auth/services/session'; import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications'; import BannerService from 'wherehows-web/services/banners'; import { alias } from '@ember-decorators/object/computed'; import { service } from '@ember-decorators/service'; import { action } from '@ember-decorators/object'; export default class Login extends Controller { /** * References the application session service * @type {Session} * @memberof Login */ @service session: Session; /** * Banner alert service * @type {BannerService} * @memberof Login */ @service banners: BannerService; /** * Aliases the name property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('name') username: string; /** * Aliases the password computed property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('pass') password: string; /** * On instantiation, error message reference is an empty string value * @type {string} * @memberof Login */ errorMessage = '';
authenticateUser(this: Login): void { const { username, password, banners } = getProperties(this, ['username', 'password', 'banners']); get(this, 'session') .authenticate('authenticator:custom-ldap', username, password) .then(results => { // Once user has chosen to authenticate, then we remove the login banner (if it exists) since it will // no longer be relevant banners.removeBanner(twoFABannerMessage, twoFABannerType); return results; }) .catch(({ responseText = 'Bad Credentials' }) => setProperties(this, { errorMessage: responseText })); } }
@action
random_line_split
login.ts
import Controller from '@ember/controller'; import { get, setProperties, getProperties } from '@ember/object'; import Session from 'ember-simple-auth/services/session'; import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications'; import BannerService from 'wherehows-web/services/banners'; import { alias } from '@ember-decorators/object/computed'; import { service } from '@ember-decorators/service'; import { action } from '@ember-decorators/object'; export default class Login extends Controller { /** * References the application session service * @type {Session} * @memberof Login */ @service session: Session; /** * Banner alert service * @type {BannerService} * @memberof Login */ @service banners: BannerService; /** * Aliases the name property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('name') username: string; /** * Aliases the password computed property on the component * @type {ComputedProperty<string>} * @memberof Login */ @alias('pass') password: string; /** * On instantiation, error message reference is an empty string value * @type {string} * @memberof Login */ errorMessage = ''; @action authenticateUser(this: Login): void
}
{ const { username, password, banners } = getProperties(this, ['username', 'password', 'banners']); get(this, 'session') .authenticate('authenticator:custom-ldap', username, password) .then(results => { // Once user has chosen to authenticate, then we remove the login banner (if it exists) since it will // no longer be relevant banners.removeBanner(twoFABannerMessage, twoFABannerType); return results; }) .catch(({ responseText = 'Bad Credentials' }) => setProperties(this, { errorMessage: responseText })); }
identifier_body
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone + 'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter() .map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main()
{ let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration != 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
identifier_body
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone + 'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter() .map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len()); for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn
() { let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration != 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
main
identifier_name
main.rs
#![feature(box_syntax)] #![feature(asm)] extern crate e2d2; extern crate fnv; extern crate getopts; extern crate rand; extern crate time; use self::nf::*; use e2d2::config::{basic_opts, read_matches}; use e2d2::interface::*; use e2d2::operators::*; use e2d2::scheduler::*; use std::env; use std::fmt::Display; use std::process; use std::sync::Arc; use std::thread; use std::time::Duration; mod nf; fn test<T, S>(ports: Vec<T>, sched: &mut S) where T: PacketRx + PacketTx + Display + Clone + 'static, S: Scheduler + Sized, { for port in &ports { println!("Receiving port {}", port); } let pipelines: Vec<_> = ports .iter()
for pipeline in pipelines { sched.add_task(pipeline).unwrap(); } } fn main() { let mut opts = basic_opts(); opts.optopt( "", "dur", "Test duration", "If this option is set to a nonzero value, then the \ test will exit after X seconds.", ); let args: Vec<String> = env::args().collect(); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => panic!(f.to_string()), }; let mut configuration = read_matches(&matches, &opts); configuration.pool_size = 255; let test_duration: u64 = matches .opt_str("dur") .unwrap_or_else(|| String::from("0")) .parse() .expect("Could not parse test duration"); match initialize_system(&configuration) { Ok(mut context) => { context.start_schedulers(); context.add_pipeline_to_run(Arc::new(move |p, s: &mut StandaloneScheduler| test(p, s))); context.execute(); if test_duration != 0 { thread::sleep(Duration::from_secs(test_duration)); } else { loop { thread::sleep(Duration::from_secs(1)); } } } Err(ref e) => { println!("Error: {}", e); if let Some(backtrace) = e.backtrace() { println!("Backtrace: {:?}", backtrace); } process::exit(1); } } }
.map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone())) .collect(); println!("Running {} pipelines", pipelines.len());
random_line_split
gumby.fixed.js
/** * Gumby Fixed */ !function() { 'use strict'; function
($el) { this.$el = $el; this.fixedPoint = ''; this.pinPoint = false; this.offset = 0; this.pinOffset = 0; this.top = 0; this.constrainEl = true; this.state = false; this.measurements = { left: 0, width: 0 }; // set up module based on attributes this.setup(); var scope = this; // monitor scroll and update fixed elements accordingly $(window).on('scroll load', function() { scope.monitorScroll(); }); // reinitialize event listener this.$el.on('gumby.initialize', function() { scope.setup(); }); } // set up module based on attributes Fixed.prototype.setup = function() { var scope = this; this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed'])); // pin point is optional this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false; // offset from fixed point this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0; // offset from pin point this.pinOffset = Number(Gumby.selectAttr.apply(this.$el, ['pinoffset'])) || 0; // top position when fixed this.top = Number(Gumby.selectAttr.apply(this.$el, ['top'])) || 0; // constrain can be turned off this.constrainEl = Gumby.selectAttr.apply(this.$el, ['constrain']) || true; if(this.constrainEl === 'false') { this.constrainEl = false; } // reference to the parent, row/column this.$parent = this.$el.parents('.columns, .column, .row'); this.$parent = this.$parent.length ? this.$parent.first() : false; this.parentRow = this.$parent ? !!this.$parent.hasClass('row') : false; // if optional pin point set then parse now if(this.pinPoint) { this.pinPoint = this.parseAttrValue(this.pinPoint); } // if we have a parent constrain dimenions if(this.$parent && this.constrainEl) { // measure up this.measure(); // and on resize reset measurement $(window).resize(function() { if(scope.state) { scope.measure(); scope.constrain(); } }); } }; // monitor scroll and trigger changes based on position Fixed.prototype.monitorScroll = function() { var scrollAmount = $(window).scrollTop(), // recalculate selector attributes as position may have changed fixedPoint = this.fixedPoint instanceof jQuery ? this.fixedPoint.offset().top : this.fixedPoint, pinPoint = false; // if a pin point is set recalculate if(this.pinPoint) { pinPoint = this.pinPoint instanceof jQuery ? this.pinPoint.offset().top : this.pinPoint; } // apply offsets if(this.offset) { fixedPoint -= this.offset; } if(this.pinOffset) { pinPoint -= this.pinOffset; } // fix it if((scrollAmount >= fixedPoint) && this.state !== 'fixed') { if(!pinPoint || scrollAmount < pinPoint) { this.fix(); } // unfix it } else if(scrollAmount < fixedPoint && this.state === 'fixed') { this.unfix(); // pin it } else if(pinPoint && scrollAmount >= pinPoint && this.state !== 'pinned') { this.pin(); } }; // fix the element and update state Fixed.prototype.fix = function() { this.state = 'fixed'; this.$el.css({ 'top' : 0 + this.top }).addClass('fixed').removeClass('unfixed pinned').trigger('gumby.onFixed'); // if we have a parent constrain dimenions if(this.$parent) { this.constrain(); } }; // unfix the element and update state Fixed.prototype.unfix = function() { this.state = 'unfixed'; this.$el.addClass('unfixed').removeClass('fixed pinned').trigger('gumby.onUnfixed'); }; // pin the element in position Fixed.prototype.pin = function() { this.state = 'pinned'; this.$el.css({ 'top' : this.$el.offset().top }).addClass('pinned fixed').removeClass('unfixed').trigger('gumby.onPinned'); }; // constrain elements dimensions to match width/height Fixed.prototype.constrain = function() { this.$el.css({ left: this.measurements.left, width: this.measurements.width }); }; // measure up the parent for constraining Fixed.prototype.measure = function() { var offsets = this.$parent.offset(), parentPadding; this.measurements.left = offsets.left; this.measurements.width = this.$parent.width(); // if element has a parent row then need to consider padding if(this.parentRow) { parentPadding = Number(this.$parent.css('paddingLeft').replace(/px/, '')); if(parentPadding) { this.measurements.left += parentPadding; } } }; // parse attribute values, could be px, top, selector Fixed.prototype.parseAttrValue = function(attr) { // px value fixed point if($.isNumeric(attr)) { return Number(attr); // 'top' string fixed point } else if(attr === 'top') { return this.$el.offset().top; // selector specified } else { var $el = $(attr); return $el; } }; // add initialisation Gumby.addInitalisation('fixed', function() { $('[data-fixed],[gumby-fixed],[fixed]').each(function() { var $this = $(this); // this element has already been initialized if($this.data('isFixed')) { return true; } // mark element as initialized $this.data('isFixed', true); new Fixed($this); }); }); // register UI module Gumby.UIModule({ module: 'fixed', events: ['onFixed', 'onUnfixed'], init: function() { Gumby.initialize('fixed'); } }); }();
Fixed
identifier_name
gumby.fixed.js
/** * Gumby Fixed */ !function() { 'use strict'; function Fixed($el) { this.$el = $el; this.fixedPoint = ''; this.pinPoint = false; this.offset = 0; this.pinOffset = 0; this.top = 0; this.constrainEl = true; this.state = false; this.measurements = { left: 0, width: 0 }; // set up module based on attributes this.setup(); var scope = this; // monitor scroll and update fixed elements accordingly $(window).on('scroll load', function() { scope.monitorScroll(); }); // reinitialize event listener this.$el.on('gumby.initialize', function() { scope.setup(); }); } // set up module based on attributes Fixed.prototype.setup = function() { var scope = this; this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed'])); // pin point is optional this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false; // offset from fixed point this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0; // offset from pin point this.pinOffset = Number(Gumby.selectAttr.apply(this.$el, ['pinoffset'])) || 0; // top position when fixed this.top = Number(Gumby.selectAttr.apply(this.$el, ['top'])) || 0; // constrain can be turned off this.constrainEl = Gumby.selectAttr.apply(this.$el, ['constrain']) || true; if(this.constrainEl === 'false') { this.constrainEl = false; } // reference to the parent, row/column this.$parent = this.$el.parents('.columns, .column, .row'); this.$parent = this.$parent.length ? this.$parent.first() : false; this.parentRow = this.$parent ? !!this.$parent.hasClass('row') : false; // if optional pin point set then parse now if(this.pinPoint) { this.pinPoint = this.parseAttrValue(this.pinPoint); } // if we have a parent constrain dimenions if(this.$parent && this.constrainEl) { // measure up this.measure(); // and on resize reset measurement $(window).resize(function() { if(scope.state) { scope.measure(); scope.constrain(); } }); } }; // monitor scroll and trigger changes based on position Fixed.prototype.monitorScroll = function() { var scrollAmount = $(window).scrollTop(), // recalculate selector attributes as position may have changed fixedPoint = this.fixedPoint instanceof jQuery ? this.fixedPoint.offset().top : this.fixedPoint, pinPoint = false; // if a pin point is set recalculate if(this.pinPoint) { pinPoint = this.pinPoint instanceof jQuery ? this.pinPoint.offset().top : this.pinPoint; } // apply offsets if(this.offset) { fixedPoint -= this.offset; } if(this.pinOffset)
// fix it if((scrollAmount >= fixedPoint) && this.state !== 'fixed') { if(!pinPoint || scrollAmount < pinPoint) { this.fix(); } // unfix it } else if(scrollAmount < fixedPoint && this.state === 'fixed') { this.unfix(); // pin it } else if(pinPoint && scrollAmount >= pinPoint && this.state !== 'pinned') { this.pin(); } }; // fix the element and update state Fixed.prototype.fix = function() { this.state = 'fixed'; this.$el.css({ 'top' : 0 + this.top }).addClass('fixed').removeClass('unfixed pinned').trigger('gumby.onFixed'); // if we have a parent constrain dimenions if(this.$parent) { this.constrain(); } }; // unfix the element and update state Fixed.prototype.unfix = function() { this.state = 'unfixed'; this.$el.addClass('unfixed').removeClass('fixed pinned').trigger('gumby.onUnfixed'); }; // pin the element in position Fixed.prototype.pin = function() { this.state = 'pinned'; this.$el.css({ 'top' : this.$el.offset().top }).addClass('pinned fixed').removeClass('unfixed').trigger('gumby.onPinned'); }; // constrain elements dimensions to match width/height Fixed.prototype.constrain = function() { this.$el.css({ left: this.measurements.left, width: this.measurements.width }); }; // measure up the parent for constraining Fixed.prototype.measure = function() { var offsets = this.$parent.offset(), parentPadding; this.measurements.left = offsets.left; this.measurements.width = this.$parent.width(); // if element has a parent row then need to consider padding if(this.parentRow) { parentPadding = Number(this.$parent.css('paddingLeft').replace(/px/, '')); if(parentPadding) { this.measurements.left += parentPadding; } } }; // parse attribute values, could be px, top, selector Fixed.prototype.parseAttrValue = function(attr) { // px value fixed point if($.isNumeric(attr)) { return Number(attr); // 'top' string fixed point } else if(attr === 'top') { return this.$el.offset().top; // selector specified } else { var $el = $(attr); return $el; } }; // add initialisation Gumby.addInitalisation('fixed', function() { $('[data-fixed],[gumby-fixed],[fixed]').each(function() { var $this = $(this); // this element has already been initialized if($this.data('isFixed')) { return true; } // mark element as initialized $this.data('isFixed', true); new Fixed($this); }); }); // register UI module Gumby.UIModule({ module: 'fixed', events: ['onFixed', 'onUnfixed'], init: function() { Gumby.initialize('fixed'); } }); }();
{ pinPoint -= this.pinOffset; }
conditional_block
gumby.fixed.js
/** * Gumby Fixed */ !function() { 'use strict'; function Fixed($el)
// set up module based on attributes Fixed.prototype.setup = function() { var scope = this; this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed'])); // pin point is optional this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false; // offset from fixed point this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0; // offset from pin point this.pinOffset = Number(Gumby.selectAttr.apply(this.$el, ['pinoffset'])) || 0; // top position when fixed this.top = Number(Gumby.selectAttr.apply(this.$el, ['top'])) || 0; // constrain can be turned off this.constrainEl = Gumby.selectAttr.apply(this.$el, ['constrain']) || true; if(this.constrainEl === 'false') { this.constrainEl = false; } // reference to the parent, row/column this.$parent = this.$el.parents('.columns, .column, .row'); this.$parent = this.$parent.length ? this.$parent.first() : false; this.parentRow = this.$parent ? !!this.$parent.hasClass('row') : false; // if optional pin point set then parse now if(this.pinPoint) { this.pinPoint = this.parseAttrValue(this.pinPoint); } // if we have a parent constrain dimenions if(this.$parent && this.constrainEl) { // measure up this.measure(); // and on resize reset measurement $(window).resize(function() { if(scope.state) { scope.measure(); scope.constrain(); } }); } }; // monitor scroll and trigger changes based on position Fixed.prototype.monitorScroll = function() { var scrollAmount = $(window).scrollTop(), // recalculate selector attributes as position may have changed fixedPoint = this.fixedPoint instanceof jQuery ? this.fixedPoint.offset().top : this.fixedPoint, pinPoint = false; // if a pin point is set recalculate if(this.pinPoint) { pinPoint = this.pinPoint instanceof jQuery ? this.pinPoint.offset().top : this.pinPoint; } // apply offsets if(this.offset) { fixedPoint -= this.offset; } if(this.pinOffset) { pinPoint -= this.pinOffset; } // fix it if((scrollAmount >= fixedPoint) && this.state !== 'fixed') { if(!pinPoint || scrollAmount < pinPoint) { this.fix(); } // unfix it } else if(scrollAmount < fixedPoint && this.state === 'fixed') { this.unfix(); // pin it } else if(pinPoint && scrollAmount >= pinPoint && this.state !== 'pinned') { this.pin(); } }; // fix the element and update state Fixed.prototype.fix = function() { this.state = 'fixed'; this.$el.css({ 'top' : 0 + this.top }).addClass('fixed').removeClass('unfixed pinned').trigger('gumby.onFixed'); // if we have a parent constrain dimenions if(this.$parent) { this.constrain(); } }; // unfix the element and update state Fixed.prototype.unfix = function() { this.state = 'unfixed'; this.$el.addClass('unfixed').removeClass('fixed pinned').trigger('gumby.onUnfixed'); }; // pin the element in position Fixed.prototype.pin = function() { this.state = 'pinned'; this.$el.css({ 'top' : this.$el.offset().top }).addClass('pinned fixed').removeClass('unfixed').trigger('gumby.onPinned'); }; // constrain elements dimensions to match width/height Fixed.prototype.constrain = function() { this.$el.css({ left: this.measurements.left, width: this.measurements.width }); }; // measure up the parent for constraining Fixed.prototype.measure = function() { var offsets = this.$parent.offset(), parentPadding; this.measurements.left = offsets.left; this.measurements.width = this.$parent.width(); // if element has a parent row then need to consider padding if(this.parentRow) { parentPadding = Number(this.$parent.css('paddingLeft').replace(/px/, '')); if(parentPadding) { this.measurements.left += parentPadding; } } }; // parse attribute values, could be px, top, selector Fixed.prototype.parseAttrValue = function(attr) { // px value fixed point if($.isNumeric(attr)) { return Number(attr); // 'top' string fixed point } else if(attr === 'top') { return this.$el.offset().top; // selector specified } else { var $el = $(attr); return $el; } }; // add initialisation Gumby.addInitalisation('fixed', function() { $('[data-fixed],[gumby-fixed],[fixed]').each(function() { var $this = $(this); // this element has already been initialized if($this.data('isFixed')) { return true; } // mark element as initialized $this.data('isFixed', true); new Fixed($this); }); }); // register UI module Gumby.UIModule({ module: 'fixed', events: ['onFixed', 'onUnfixed'], init: function() { Gumby.initialize('fixed'); } }); }();
{ this.$el = $el; this.fixedPoint = ''; this.pinPoint = false; this.offset = 0; this.pinOffset = 0; this.top = 0; this.constrainEl = true; this.state = false; this.measurements = { left: 0, width: 0 }; // set up module based on attributes this.setup(); var scope = this; // monitor scroll and update fixed elements accordingly $(window).on('scroll load', function() { scope.monitorScroll(); }); // reinitialize event listener this.$el.on('gumby.initialize', function() { scope.setup(); }); }
identifier_body
gumby.fixed.js
/** * Gumby Fixed */ !function() { 'use strict'; function Fixed($el) { this.$el = $el; this.fixedPoint = ''; this.pinPoint = false; this.offset = 0; this.pinOffset = 0; this.top = 0; this.constrainEl = true; this.state = false; this.measurements = { left: 0, width: 0 }; // set up module based on attributes this.setup(); var scope = this; // monitor scroll and update fixed elements accordingly $(window).on('scroll load', function() { scope.monitorScroll(); }); // reinitialize event listener this.$el.on('gumby.initialize', function() { scope.setup(); }); } // set up module based on attributes Fixed.prototype.setup = function() { var scope = this; this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed'])); // pin point is optional this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false; // offset from fixed point this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0; // offset from pin point this.pinOffset = Number(Gumby.selectAttr.apply(this.$el, ['pinoffset'])) || 0; // top position when fixed this.top = Number(Gumby.selectAttr.apply(this.$el, ['top'])) || 0; // constrain can be turned off this.constrainEl = Gumby.selectAttr.apply(this.$el, ['constrain']) || true; if(this.constrainEl === 'false') { this.constrainEl = false; } // reference to the parent, row/column this.$parent = this.$el.parents('.columns, .column, .row'); this.$parent = this.$parent.length ? this.$parent.first() : false; this.parentRow = this.$parent ? !!this.$parent.hasClass('row') : false; // if optional pin point set then parse now if(this.pinPoint) { this.pinPoint = this.parseAttrValue(this.pinPoint); } // if we have a parent constrain dimenions if(this.$parent && this.constrainEl) { // measure up this.measure(); // and on resize reset measurement $(window).resize(function() { if(scope.state) { scope.measure(); scope.constrain(); } }); } }; // monitor scroll and trigger changes based on position Fixed.prototype.monitorScroll = function() { var scrollAmount = $(window).scrollTop(), // recalculate selector attributes as position may have changed fixedPoint = this.fixedPoint instanceof jQuery ? this.fixedPoint.offset().top : this.fixedPoint, pinPoint = false; // if a pin point is set recalculate if(this.pinPoint) { pinPoint = this.pinPoint instanceof jQuery ? this.pinPoint.offset().top : this.pinPoint; } // apply offsets if(this.offset) { fixedPoint -= this.offset; } if(this.pinOffset) { pinPoint -= this.pinOffset; } // fix it if((scrollAmount >= fixedPoint) && this.state !== 'fixed') { if(!pinPoint || scrollAmount < pinPoint) { this.fix(); } // unfix it } else if(scrollAmount < fixedPoint && this.state === 'fixed') { this.unfix(); // pin it } else if(pinPoint && scrollAmount >= pinPoint && this.state !== 'pinned') { this.pin(); } }; // fix the element and update state Fixed.prototype.fix = function() { this.state = 'fixed'; this.$el.css({ 'top' : 0 + this.top }).addClass('fixed').removeClass('unfixed pinned').trigger('gumby.onFixed'); // if we have a parent constrain dimenions if(this.$parent) { this.constrain(); } }; // unfix the element and update state Fixed.prototype.unfix = function() { this.state = 'unfixed'; this.$el.addClass('unfixed').removeClass('fixed pinned').trigger('gumby.onUnfixed'); }; // pin the element in position Fixed.prototype.pin = function() { this.state = 'pinned'; this.$el.css({ 'top' : this.$el.offset().top }).addClass('pinned fixed').removeClass('unfixed').trigger('gumby.onPinned'); }; // constrain elements dimensions to match width/height Fixed.prototype.constrain = function() { this.$el.css({ left: this.measurements.left, width: this.measurements.width }); }; // measure up the parent for constraining Fixed.prototype.measure = function() { var offsets = this.$parent.offset(), parentPadding; this.measurements.left = offsets.left; this.measurements.width = this.$parent.width(); // if element has a parent row then need to consider padding if(this.parentRow) { parentPadding = Number(this.$parent.css('paddingLeft').replace(/px/, '')); if(parentPadding) { this.measurements.left += parentPadding; } } }; // parse attribute values, could be px, top, selector Fixed.prototype.parseAttrValue = function(attr) { // px value fixed point if($.isNumeric(attr)) { return Number(attr); // 'top' string fixed point } else if(attr === 'top') { return this.$el.offset().top; // selector specified } else { var $el = $(attr); return $el; } }; // add initialisation Gumby.addInitalisation('fixed', function() { $('[data-fixed],[gumby-fixed],[fixed]').each(function() { var $this = $(this); // this element has already been initialized if($this.data('isFixed')) { return true; } // mark element as initialized $this.data('isFixed', true); new Fixed($this); }); }); // register UI module Gumby.UIModule({ module: 'fixed', events: ['onFixed', 'onUnfixed'], init: function() { Gumby.initialize('fixed'); }
}();
});
random_line_split
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn
() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
main
identifier_name
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&`
if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||`
random_line_split
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main()
{ use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
identifier_body
syntax-ambiguity-2018.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // edition:2018 // Enabling `ireffutable_let_patterns` isn't necessary for what this tests, but it makes coming up // with examples easier. #![feature(irrefutable_let_patterns)] #[allow(irrefutable_let_patterns)] fn main() { use std::ops::Range; if let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` if let Range { start: _, end: _ } = true..true || false
//~^ ERROR ambiguous use of `||` while let Range { start: _, end: _ } = true..true && false { } //~^ ERROR ambiguous use of `&&` while let Range { start: _, end: _ } = true..true || false { } //~^ ERROR ambiguous use of `||` if let true = false && false { } //~^ ERROR ambiguous use of `&&` while let true = (1 == 2) && false { } //~^ ERROR ambiguous use of `&&` // The following cases are not an error as parenthesis are used to // clarify intent: if let Range { start: _, end: _ } = true..(true || false) { } if let Range { start: _, end: _ } = true..(true && false) { } while let Range { start: _, end: _ } = true..(true || false) { } while let Range { start: _, end: _ } = true..(true && false) { } }
{ }
conditional_block
expander.module.d.ts
/// <reference path="../../ts/default.module.d.ts" /> export declare class MPCExpanderElement extends HTMLElement { constructor(); readonly ownerExpander: MPCExpanderElement; readonly isOwnerExpander: boolean; private _selected; selected: MPCExpanderElement;
expand(): boolean; collapse(): boolean; toggle(force?: boolean): void; readonly label: HTMLElement; labelText: string; expandable: boolean; expanded: boolean; static readonly observedAttributes: string[]; attributeChangedCallback(name: string, oldValue: string, newValue: string): void; connectedCallback(): void; disconnectedCallback(): void; adoptedCallback(): void; private _onexpand; onexpand: (this: this, event: Event) => any; private _onexpanded; onexpanded: (this: this, event: Event) => any; private _oncollapse; oncollapse: (this: this, event: Event) => any; private _oncollapsed; oncollapsed: (this: this, event: Event) => any; } //# sourceMappingURL=expander.module.d.ts.map
random_line_split
expander.module.d.ts
/// <reference path="../../ts/default.module.d.ts" /> export declare class
extends HTMLElement { constructor(); readonly ownerExpander: MPCExpanderElement; readonly isOwnerExpander: boolean; private _selected; selected: MPCExpanderElement; expand(): boolean; collapse(): boolean; toggle(force?: boolean): void; readonly label: HTMLElement; labelText: string; expandable: boolean; expanded: boolean; static readonly observedAttributes: string[]; attributeChangedCallback(name: string, oldValue: string, newValue: string): void; connectedCallback(): void; disconnectedCallback(): void; adoptedCallback(): void; private _onexpand; onexpand: (this: this, event: Event) => any; private _onexpanded; onexpanded: (this: this, event: Event) => any; private _oncollapse; oncollapse: (this: this, event: Event) => any; private _oncollapsed; oncollapsed: (this: this, event: Event) => any; } //# sourceMappingURL=expander.module.d.ts.map
MPCExpanderElement
identifier_name
long.py
# http://rosalind.info/problems/long/ def superstring(arr, accumulator=''): # We now have all strings if len(arr) == 0:
accumulator = arr.pop(0) return superstring(arr, accumulator) # Recursive call else: for i in range(len(arr)): sample = arr[i] l = len(sample) for p in range(l / 2): q = l - p if accumulator.startswith(sample[p:]): arr.pop(i) return superstring(arr, sample[:p] + accumulator) if accumulator.endswith(sample[:q]): arr.pop(i) return superstring(arr, accumulator + sample[q:]) f = open("rosalind_long.txt", "r") dnas = {} currentKey = '' for content in f: # Beginning of a new sample if '>' in content: key = content.rstrip().replace('>', '') currentKey = key dnas[currentKey] = '' else: dnas[currentKey] += content.rstrip() print superstring(dnas.values())
return accumulator # Initial call elif len(accumulator) == 0:
random_line_split
long.py
# http://rosalind.info/problems/long/ def
(arr, accumulator=''): # We now have all strings if len(arr) == 0: return accumulator # Initial call elif len(accumulator) == 0: accumulator = arr.pop(0) return superstring(arr, accumulator) # Recursive call else: for i in range(len(arr)): sample = arr[i] l = len(sample) for p in range(l / 2): q = l - p if accumulator.startswith(sample[p:]): arr.pop(i) return superstring(arr, sample[:p] + accumulator) if accumulator.endswith(sample[:q]): arr.pop(i) return superstring(arr, accumulator + sample[q:]) f = open("rosalind_long.txt", "r") dnas = {} currentKey = '' for content in f: # Beginning of a new sample if '>' in content: key = content.rstrip().replace('>', '') currentKey = key dnas[currentKey] = '' else: dnas[currentKey] += content.rstrip() print superstring(dnas.values())
superstring
identifier_name
long.py
# http://rosalind.info/problems/long/ def superstring(arr, accumulator=''): # We now have all strings
f = open("rosalind_long.txt", "r") dnas = {} currentKey = '' for content in f: # Beginning of a new sample if '>' in content: key = content.rstrip().replace('>', '') currentKey = key dnas[currentKey] = '' else: dnas[currentKey] += content.rstrip() print superstring(dnas.values())
if len(arr) == 0: return accumulator # Initial call elif len(accumulator) == 0: accumulator = arr.pop(0) return superstring(arr, accumulator) # Recursive call else: for i in range(len(arr)): sample = arr[i] l = len(sample) for p in range(l / 2): q = l - p if accumulator.startswith(sample[p:]): arr.pop(i) return superstring(arr, sample[:p] + accumulator) if accumulator.endswith(sample[:q]): arr.pop(i) return superstring(arr, accumulator + sample[q:])
identifier_body
long.py
# http://rosalind.info/problems/long/ def superstring(arr, accumulator=''): # We now have all strings if len(arr) == 0: return accumulator # Initial call elif len(accumulator) == 0: accumulator = arr.pop(0) return superstring(arr, accumulator) # Recursive call else: for i in range(len(arr)): sample = arr[i] l = len(sample) for p in range(l / 2):
f = open("rosalind_long.txt", "r") dnas = {} currentKey = '' for content in f: # Beginning of a new sample if '>' in content: key = content.rstrip().replace('>', '') currentKey = key dnas[currentKey] = '' else: dnas[currentKey] += content.rstrip() print superstring(dnas.values())
q = l - p if accumulator.startswith(sample[p:]): arr.pop(i) return superstring(arr, sample[:p] + accumulator) if accumulator.endswith(sample[:q]): arr.pop(i) return superstring(arr, accumulator + sample[q:])
conditional_block
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [ ! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if ! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()>
fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
{ let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) }
identifier_body
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [ ! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if ! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 ";
hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
pub struct Bootstrap {
random_line_split
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [ ! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if ! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn new(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password
else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
{ sess.userauth_password(u, p).unwrap(); }
conditional_block
bootstrap.rs
// Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the // top-level directory of this distribution and at // https://intecture.io/COPYRIGHT. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. use auth::Auth; use error::{Error, Result}; use inapi::ProjectConfig; use project; use read_conf; use ssh2::Session; use std::env; use std::fs::File; use std::io::prelude::*; use std::net::TcpStream; use std::path::Path; const BOOTSTRAP_SOURCE: &'static str = "#!/bin/sh set -u main() { # Run any user-defined preinstall scripts {{PREINSTALL}} need_cmd curl local _tmpdir=\"$(mktemp -d 2>/dev/null || mktemp -d -t intecture)\" cd $_tmpdir # Install agent curl -sSf https://get.intecture.io | sh -s -- -y -d $_tmpdir agent || exit 1 # Create agent cert cat << \"EOF\" > agent.crt {{AGENTCERT}} EOF # Create auth cert cat << \"EOF\" > auth.crt {{AUTHCERT}} EOF {{SUDO}} $_tmpdir/agent/installer.sh install_certs agent.crt auth.crt {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_server \"{{AUTHHOST}}\" {{SUDO}} $_tmpdir/agent/installer.sh amend_conf auth_update_port {{AUTHPORT}} {{SUDO}} $_tmpdir/agent/installer.sh start_daemon # Check that inagent is up and running sleep 1 local _pid=$(pgrep -x inagent) if [ ! -n $_pid ]; then echo \"Failed to start inagent daemon\" >&2 exit 1 fi # Run any user-defined postinstall scripts {{POSTINSTALL}} } need_cmd() { if ! command -v \"$1\" > /dev/null 2>&1; then echo \"need '$1' (command not found)\" >&2 exit 1 fi } main || exit 1 "; pub struct Bootstrap { hostname: String, _stream: TcpStream, session: Session, is_root: bool, } impl Bootstrap { pub fn
(hostname: &str, port: Option<u32>, username: Option<&str>, password: Option<&str>, identity_file: Option<&str>) -> Result<Bootstrap> { let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?; let mut sess = Session::new().unwrap(); sess.handshake(&tcp)?; let u = username.unwrap_or("root"); if let Some(ref i) = identity_file { sess.userauth_pubkey_file(u, None, Path::new(i), None)?; } else if let Some(ref p) = password { sess.userauth_password(u, p).unwrap(); } else { sess.userauth_agent(u)?; } if sess.authenticated() { Ok(Bootstrap { hostname: hostname.into(), _stream: tcp, session: sess, is_root: u == "root", }) } else { Err(Error::Bootstrap("Failed to authenticate to host".into())) } } pub fn run(&mut self, preinstall_script: Option<&str>, postinstall_script: Option<&str>) -> Result<()> { let mut auth = try!(Auth::new(&env::current_dir().unwrap())); let agent_cert = try!(auth.add("host", &self.hostname)); // As we are in a project directory, it's safe to assume that // the auth public key must be present. let mut fh = File::open("auth.crt")?; let mut auth_cert = String::new(); fh.read_to_string(&mut auth_cert)?; // Load project config let conf: ProjectConfig = read_conf(project::CONFIGNAME)?; // Install and run bootstrap script let script = BOOTSTRAP_SOURCE.replace("{{AGENTCERT}}", &agent_cert.secret()) .replace("{{AUTHCERT}}", &auth_cert) .replace("{{AUTHHOST}}", &conf.auth_server) .replace("{{AUTHPORT}}", &conf.auth_update_port.to_string()) .replace("{{PREINSTALL}}", preinstall_script.unwrap_or("")) .replace("{{POSTINSTALL}}", postinstall_script.unwrap_or("")) .replace("{{SUDO}}", if self.is_root { "" } else { "sudo" }); let bootstrap_path = self.channel_exec("/bin/sh -c \"mktemp 2>/dev/null || mktemp -t in-bootstrap\"")?; // Deliberately omit terminating EOS delimiter as it breaks // FreeBSD and works fine without it. let cmd = format!("chmod u+x {0} && cat << \"EOS\" > {0} {1}", bootstrap_path.trim(), script); self.channel_exec(&cmd)?; self.channel_exec(&bootstrap_path)?; Ok(()) } fn channel_exec(&mut self, cmd: &str) -> Result<String> { let mut channel = self.session.channel_session()?; channel.exec(cmd)?; channel.send_eof()?; channel.wait_eof()?; let mut out = String::new(); channel.read_to_string(&mut out)?; if channel.exit_status()? == 0 { Ok(out) } else { let mut stderr = channel.stderr(); let mut err = String::new(); stderr.read_to_string(&mut err)?; Err(Error::Bootstrap(format!("stdout: {}\nstderr: {}", out, err))) } } }
new
identifier_name
main.rs
#![feature(plugin, no_std, start, core_intrinsics)]
use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
#![no_std] #![plugin(macro_platformtree)] extern crate zinc;
random_line_split
main.rs
#![feature(plugin, no_std, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn
(args: &pt::run_args) { use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
run
identifier_name
main.rs
#![feature(plugin, no_std, start, core_intrinsics)] #![no_std] #![plugin(macro_platformtree)] extern crate zinc; use zinc::drivers::chario::CharIO; platformtree!( tiva_c@mcu { clock { source = "MOSC"; xtal = "X16_0MHz"; pll = true; div = 5; } timer { /* The mcu contain both 16/32bit and "wide" 32/64bit timers. */ timer@w0 { /* prescale sysclk to 1Mhz since the wait code expects 1us * granularity */ prescale = 80; mode = "periodic"; } } gpio { a { uart_rx@0 { direction = "in"; function = 1; } uart_tx@1 { direction = "in"; function = 1; } } f { txled@2 { direction = "out"; } } } uart { uart@0 { mode = "115200,8n1"; } } } os { single_task { loop = "run"; args { timer = &timer; uart = &uart; txled = &txled; uart_tx = &uart_tx; } } } ); fn run(args: &pt::run_args)
{ use zinc::hal::timer::Timer; use zinc::hal::pin::Gpio; args.uart.puts("Hello, world\r\n"); let mut i = 0; loop { args.txled.set_high(); args.uart.puts("Waiting for "); args.uart.puti(i); args.uart.puts(" seconds...\r\n"); i += 1; args.txled.set_low(); args.timer.wait(1); } }
identifier_body
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { let element = HTMLDataListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) } } impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn
(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
Options
identifier_name
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement> { let element = HTMLDataListElement::new_inherited(localName, prefix, document);
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) }
random_line_split
htmldatalistelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::htmlcollection::{CollectionFilter, HTMLCollection}; use dom::htmlelement::HTMLElement; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, window_from_node}; use string_cache::Atom; #[dom_struct] pub struct HTMLDataListElement { htmlelement: HTMLElement } impl HTMLDataListElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLDataListElement { HTMLDataListElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLDataListElement>
} impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> Root<HTMLCollection> { #[derive(JSTraceable, HeapSizeOf)] struct HTMLDataListOptionsFilter; impl CollectionFilter for HTMLDataListOptionsFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { elem.is::<HTMLOptionElement>() } } let filter = box HTMLDataListOptionsFilter; let window = window_from_node(self); HTMLCollection::create(window.r(), self.upcast(), filter) } }
{ let element = HTMLDataListElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) }
identifier_body
CancelTextCommand.js
var CancelTextCommand = function() { this.Extends = SimpleCommand; this.execute = function(note) { //alert("CancelTextCommand"); var mediator = note.getBody(); var textEditor = null; if (mediator instanceof ModelObjectsTextsEditorMediator) { textEditor = mediator.getViewComponent().gridListSplitter.right.modelObjectsTextsEditor; } else
var properties = { "state": SjamayeeMediator.STATE_LIST, "textEditor": textEditor }; this.sendNotification(SjamayeeFacade.DATA_MODEL_CHANGE, properties); //this.sendNotification(SjamayeeFacade.TEXT_CANCELED,mediator); var toolBarMediator = null; if (mediator instanceof ModelObjectsTextsEditorMediator) { toolBarMediator = this.facade.retrieveMediator(ModelObjectsListMediator.ID); } else { toolBarMediator = this.facade.retrieveMediator(ModelRelationsGridMediator.ID); } toolBarMediator.setMessageText("Text canceled."); }; }; CancelTextCommand = new Class(new CancelTextCommand());
{ textEditor = mediator.getViewComponent().gridListSplitter.right.modelRelationsTextsEditor; }
conditional_block
CancelTextCommand.js
var CancelTextCommand = function() { this.Extends = SimpleCommand; this.execute = function(note) { //alert("CancelTextCommand"); var mediator = note.getBody(); var textEditor = null; if (mediator instanceof ModelObjectsTextsEditorMediator) { textEditor = mediator.getViewComponent().gridListSplitter.right.modelObjectsTextsEditor;
} else { textEditor = mediator.getViewComponent().gridListSplitter.right.modelRelationsTextsEditor; } var properties = { "state": SjamayeeMediator.STATE_LIST, "textEditor": textEditor }; this.sendNotification(SjamayeeFacade.DATA_MODEL_CHANGE, properties); //this.sendNotification(SjamayeeFacade.TEXT_CANCELED,mediator); var toolBarMediator = null; if (mediator instanceof ModelObjectsTextsEditorMediator) { toolBarMediator = this.facade.retrieveMediator(ModelObjectsListMediator.ID); } else { toolBarMediator = this.facade.retrieveMediator(ModelRelationsGridMediator.ID); } toolBarMediator.setMessageText("Text canceled."); }; }; CancelTextCommand = new Class(new CancelTextCommand());
random_line_split
experiment.py
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socket sys.path.append('./code') from argparse import ArgumentParser from pickle import Unpickler, dump from subprocess import Popen, PIPE from os import path from warnings import warn from time import time, strftime, localtime from numpy import ceil, argsort from numpy.random import rand, randint from distutils.version import StrictVersion from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from httplib import HTTPConnection from getopt import getopt class Experiment: """ @type time: float @ivar time: time at initialization of experiment @type duration: float @ivar duration: time in seconds between initialization and saving @type script: string @ivar script: stores the content of the main Python script @type platform: string @ivar platform: information about operating system @type processors: string @ivar processors: some information about the processors @type environ: string @ivar environ: environment variables at point of initialization @type hostname: string @ivar hostname: hostname of server running the experiment @type cwd: string @ivar cwd: working directory at execution time @type comment: string @ivar comment: a comment describing the experiment @type results: dictionary @ivar results: container to store experimental results @type commit: string @ivar commit: git commit hash @type modified: boolean @ivar modified: indicates uncommited changes @type filename: string @ivar filename: path to stored results @type seed: int @ivar seed: random seed used through the experiment @type versions: dictionary @ivar versions: versions of Python, numpy and scipy """ def __str__(self): """ Summarize information about the experiment. @rtype: string @return: summary of the experiment """ strl = [] # date and duration of experiment strl.append(strftime('date \t\t %a, %d %b %Y %H:%M:%S', localtime(self.time))) strl.append('duration \t ' + str(int(self.duration)) + 's') strl.append('hostname \t ' + self.hostname) # commit hash if self.commit: if self.modified: strl.append('commit \t\t ' + self.commit + ' (modified)') else: strl.append('commit \t\t ' + self.commit) # results strl.append('results \t {' + ', '.join(map(str, self.results.keys())) + '}') # comment if self.comment: strl.append('\n' + self.comment) return '\n'.join(strl) def __del__(self): self.status(None) def __init__(self, filename='', comment='', seed=None, server=None, port=8000): """ If the filename is given and points to an existing experiment, load it. Otherwise store the current timestamp and try to get commit information from the repository in the current directory. @type filename: string @param filename: path to where the experiment will be stored @type comment: string @param comment: a comment describing the experiment @type seed: integer @param seed: random seed used in the experiment """ self.id = 0 self.time = time() self.comment = comment self.filename = filename self.results = {} self.seed = seed self.script = '' self.cwd = '' self.platform = '' self.processors = '' self.environ = '' self.duration = 0 self.versions = {} self.server = '' if self.seed is None: self.seed = int((time() + 1e6 * rand()) * 1e3) % 4294967295 # set random seed random.seed(self.seed) numpy.random.seed(self.seed) if self.filename: # load given experiment self.load() else: # identifies the experiment self.id = randint(1E8) # check if a comment was passed via the command line parser = ArgumentParser(add_help=False) parser.add_argument('--comment') optlist, argv = parser.parse_known_args(sys.argv[1:]) optlist = vars(optlist) # remove comment command line argument from argument list sys.argv[1:] = argv # comment given as command line argument self.comment = optlist.get('comment', '') # get OS information self.platform = sys.platform # arguments to the program self.argv = sys.argv self.script_path = sys.argv[0] try: with open(sys.argv[0]) as handle: # store python script self.script = handle.read() except: warn('Unable to read Python script.') # environment variables self.environ = os.environ self.cwd = os.getcwd() self.hostname = socket.gethostname() # store some information about the processor(s) if self.platform == 'linux2': cmd = 'egrep "processor|model name|cpu MHz|cache size" /proc/cpuinfo' with os.popen(cmd) as handle: self.processors = handle.read() elif self.platform == 'darwin': cmd = 'system_profiler SPHardwareDataType | egrep "Processor|Cores|L2|Bus"' with os.popen(cmd) as handle: self.processors = handle.read() # version information self.versions['python'] = sys.version self.versions['numpy'] = numpy.__version__ self.versions['scipy'] = scipy.__version__ # store information about git repository if path.isdir('.git'): # get commit hash pr1 = Popen(['git', 'log', '-1'], stdout=PIPE) pr2 = Popen(['head', '-1'], stdin=pr1.stdout, stdout=PIPE) pr3 = Popen(['cut', '-d', ' ', '-f', '2'], stdin=pr2.stdout, stdout=PIPE) self.commit = pr3.communicate()[0][:-1] # check if project contains uncommitted changes pr1 = Popen(['git', 'status', '--porcelain'], stdout=PIPE) pr2 = Popen(['egrep', '^.M'], stdin=pr1.stdout, stdout=PIPE) self.modified = pr2.communicate()[0] if self.modified: warn('Uncommitted changes.') else: # no git repository self.commit = None self.modified = False # server managing experiments self.server = server self.port = port self.status('running') def status(self, status, **kwargs): if self.server: try: conn = HTTPConnection(self.server, self.port) conn.request('GET', '/version/') resp = conn.getresponse() if not resp.read().startswith('Experiment'): raise RuntimeError() HTTPConnection(self.server, self.port).request('POST', '', str(dict({ 'id': self.id, 'version': __version__, 'status': status, 'hostname': self.hostname, 'cwd': self.cwd, 'script_path': self.script_path, 'script': self.script, 'comment': self.comment, 'time': self.time, }, **kwargs))) except: warn('Unable to connect to \'{0}:{1}\'.'.format(self.server, self.port)) def progress(self, progress): self.status('PROGRESS', progress=progress) def save(self, filename=None, overwrite=False): """ Store results. If a filename is given, the default is overwritten. @type filename: string @param filename: path to where the experiment will be stored @type overwrite: boolean @param overwrite: overwrite existing files """ self.duration = time() - self.time if filename is None: filename = self.filename else: # replace {0} and {1} by date and time tmp1 = strftime('%d%m%Y', localtime(time())) tmp2 = strftime('%H%M%S', localtime(time())) filename = filename.format(tmp1, tmp2) self.filename = filename # make sure directory exists try: os.makedirs(path.dirname(filename)) except OSError: pass # make sure filename is unique counter = 0 pieces = path.splitext(filename) if not overwrite: while path.exists(filename): counter += 1 filename = pieces[0] + '.' + str(counter) + pieces[1] if counter: warn(''.join(pieces) + ' already exists. Saving to ' + filename + '.') # store experiment with open(filename, 'wb') as handle: dump({ 'version': __version__, 'id': self.id, 'time': self.time, 'seed': self.seed, 'duration': self.duration, 'environ': self.environ, 'hostname': self.hostname, 'cwd': self.cwd, 'argv': self.argv, 'script': self.script, 'script_path': self.script_path, 'processors': self.processors, 'platform': self.platform, 'comment': self.comment, 'commit': self.commit, 'modified': self.modified, 'versions': self.versions, 'results': self.results}, handle, 1) self.status('SAVE', filename=filename, duration=self.duration) def load(self, filename=None): """ Loads experimental results from the specified file. @type filename: string @param filename: path to where the experiment is stored """ if filename: self.filename = filename with open(self.filename, 'rb') as handle: res = load(handle) self.time = res['time'] self.seed = res['seed'] self.duration = res['duration'] self.processors = res['processors'] self.environ = res['environ'] self.platform = res['platform'] self.comment = res['comment'] self.commit = res['commit'] self.modified = res['modified'] self.versions = res['versions'] self.results = res['results'] self.argv = res['argv'] \ if StrictVersion(res['version']) >= '0.3.1' else None self.script = res['script'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.script_path = res['script_path'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.cwd = res['cwd'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.hostname = res['hostname'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.id = res['id'] \ if StrictVersion(res['version']) >= '0.4.0' else None def __getitem__(self, key): return self.results[key] def __setitem__(self, key, value): self.results[key] = value def __delitem__(self, key): del self.results[key] class ExperimentRequestHandler(BaseHTTPRequestHandler): """ Renders HTML showing running and finished experiments. """ xpck_path = '' running = {} finished = {} def do_GET(self): """ Renders HTML displaying running and saved experiments. """ # number of bars representing progress max_bars = 20 if self.path == '/version/': self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write('Experiment {0}'.format(__version__)) elif self.path.startswith('/running/'): id = int([s for s in self.path.split('/') if s != ''][-1]) # display running experiment if id in ExperimentRequestHandler.running: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Experiment</h2>') instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Hostname:</th><td>{0}</td></tr>'.format(instance['hostname'])) self.wfile.write('<tr><th>Status:</th><td class="running">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) self.wfile.write(HTML_FOOTER) elif id in ExperimentRequestHandler.finished: self.send_response(302) self.send_header('Location', '/finished/{0}/'.format(id)) self.end_headers() else: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) elif self.path.startswith('/finished/'): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) id = int([s for s in self.path.split('/') if s != ''][-1]) # display finished experiment if id in ExperimentRequestHandler.finished: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<h2>Experiment</h2>') self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Results:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['filename']))) self.wfile.write('<tr><th>Status:</th><td class="finished">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>End:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['duration'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Results</h2>') try: experiment = Experiment(os.path.join(instance['cwd'], instance['filename'])) except: self.wfile.write('Could not open file.') else: self.wfile.write('<table>') for key, value in experiment.results.items(): self.wfile.write('<tr><th>{0}</th><td>{1}</td></tr>'.format(key, value)) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) else: self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) else: files = [] if 'xpck_path' in ExperimentRequestHandler.__dict__: if ExperimentRequestHandler.xpck_path != '': for path in ExperimentRequestHandler.xpck_path.split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] if 'XPCK_PATH' in os.environ: for path in os.environ['XPCK_PATH'].split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Running</h2>') # display running experiments if ExperimentRequestHandler.running: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Experiment</th>') self.wfile.write('<th>Hostname</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] for instance in ExperimentRequestHandler.running.values()] ids = ExperimentRequestHandler.running.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/running/{1}/">{0}</a></td>'.format( instance['script_path'], instance['id'])) self.wfile.write('<td>{0}</td>'.format(instance['hostname'])) self.wfile.write('<td class="running">{0}</td>'.format(instance['status'])) self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No running experiments.') self.wfile.write('<h2>Saved</h2>') # display saved experiments if ExperimentRequestHandler.finished: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Results</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>End</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] + instance['duration'] for instance in ExperimentRequestHandler.finished.values()] ids = ExperimentRequestHandler.finished.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/finished/{1}/">{0}</a></td>'.format( instance['filename'], instance['id'])) self.wfile.write('<td class="finished">saved</td>') self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'] + instance['duration'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No saved experiments.') self.wfile.write(HTML_FOOTER) def do_POST(self):
class XUnpickler(Unpickler): """ An extension of the Unpickler class which resolves some backwards compatibility issues of Numpy. """ def find_class(self, module, name): """ Helps Unpickler to find certain Numpy modules. """ try: numpy_version = StrictVersion(numpy.__version__) if numpy_version >= '1.5.0': if module == 'numpy.core.defmatrix': module = 'numpy.matrixlib.defmatrix' except ValueError: pass return Unpickler.find_class(self, module, name) def load(file): return XUnpickler(file).load() def main(argv): """ Load and display experiment information. """ if len(argv) < 2: print 'Usage:', argv[0], '[--server] [--port=<port>] [--path=<path>] [filename]' return 0 optlist, argv = getopt(argv[1:], '', ['server', 'port=', 'path=']) optlist = dict(optlist) if '--server' in optlist: try: ExperimentRequestHandler.xpck_path = optlist.get('--path', '') port = optlist.get('--port', 8000) # start server server = HTTPServer(('', port), ExperimentRequestHandler) server.serve_forever() except KeyboardInterrupt: server.socket.close() return 0 # load experiment experiment = Experiment(sys.argv[1]) if len(argv) > 1: # print arguments for arg in argv[1:]: try: print experiment[arg] except: print experiment[int(arg)] return 0 # print summary of experiment print experiment return 0 HTML_HEADER = '''<html> <head> <title>Experiments</title> <style type="text/css"> body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 11pt; color: black; background: white; padding: 0pt 20pt; } h2 { margin-top: 20pt; font-size: 16pt; } table { border-collapse: collapse; } tr:nth-child(even) { background: #f4f4f4; } th { font-size: 12pt; text-align: left; padding: 2pt 10pt 3pt 0pt; } td { font-size: 10pt; padding: 3pt 10pt 2pt 0pt; } pre { font-size: 10pt; background: #f4f4f4; padding: 5pt; } a { text-decoration: none; color: #04a; } .running { color: #08b; } .finished { color: #390; } .comment { min-width: 200pt; font-style: italic; } .progress { color: #ccc; } .progress .bars { color: black; } </style> </head> <body>''' HTML_FOOTER = ''' </body> </html>''' if __name__ == '__main__': sys.exit(main(sys.argv))
instances = ExperimentRequestHandler.running instance = eval(self.rfile.read(int(self.headers['Content-Length']))) if instance['status'] is 'PROGRESS': if instance['id'] not in instances: instances[instance['id']] = instance instances[instance['id']]['status'] = 'running' instances[instance['id']]['progress'] = instance['progress'] elif instance['status'] is 'SAVE': ExperimentRequestHandler.finished[instance['id']] = instance ExperimentRequestHandler.finished[instance['id']]['status'] = 'saved' else: if instance['id'] in instances: progress = instances[instance['id']]['progress'] else: progress = 0 instances[instance['id']] = instance instances[instance['id']]['progress'] = progress if instance['status'] is None: try: del instances[instance['id']] except: pass
identifier_body
experiment.py
#!/usr/bin/env python """ Manage and display experimental results. """ __license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>' __author__ = 'Lucas Theis <lucas@theis.io>' __docformat__ = 'epytext' __version__ = '0.4.3' import sys import os import numpy import random import scipy import socket sys.path.append('./code') from argparse import ArgumentParser from pickle import Unpickler, dump from subprocess import Popen, PIPE from os import path from warnings import warn from time import time, strftime, localtime from numpy import ceil, argsort from numpy.random import rand, randint from distutils.version import StrictVersion from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from httplib import HTTPConnection from getopt import getopt class Experiment: """ @type time: float @ivar time: time at initialization of experiment @type duration: float @ivar duration: time in seconds between initialization and saving @type script: string @ivar script: stores the content of the main Python script @type platform: string @ivar platform: information about operating system @type processors: string @ivar processors: some information about the processors @type environ: string @ivar environ: environment variables at point of initialization @type hostname: string @ivar hostname: hostname of server running the experiment @type cwd: string @ivar cwd: working directory at execution time @type comment: string @ivar comment: a comment describing the experiment @type results: dictionary @ivar results: container to store experimental results @type commit: string @ivar commit: git commit hash @type modified: boolean @ivar modified: indicates uncommited changes @type filename: string @ivar filename: path to stored results @type seed: int @ivar seed: random seed used through the experiment @type versions: dictionary @ivar versions: versions of Python, numpy and scipy """ def __str__(self): """ Summarize information about the experiment. @rtype: string @return: summary of the experiment """ strl = [] # date and duration of experiment strl.append(strftime('date \t\t %a, %d %b %Y %H:%M:%S', localtime(self.time))) strl.append('duration \t ' + str(int(self.duration)) + 's') strl.append('hostname \t ' + self.hostname) # commit hash if self.commit: if self.modified: strl.append('commit \t\t ' + self.commit + ' (modified)') else: strl.append('commit \t\t ' + self.commit) # results strl.append('results \t {' + ', '.join(map(str, self.results.keys())) + '}') # comment if self.comment: strl.append('\n' + self.comment) return '\n'.join(strl) def __del__(self): self.status(None) def __init__(self, filename='', comment='', seed=None, server=None, port=8000): """ If the filename is given and points to an existing experiment, load it. Otherwise store the current timestamp and try to get commit information from the repository in the current directory. @type filename: string @param filename: path to where the experiment will be stored @type comment: string @param comment: a comment describing the experiment @type seed: integer @param seed: random seed used in the experiment """ self.id = 0 self.time = time() self.comment = comment self.filename = filename self.results = {} self.seed = seed self.script = '' self.cwd = '' self.platform = '' self.processors = '' self.environ = '' self.duration = 0 self.versions = {} self.server = '' if self.seed is None: self.seed = int((time() + 1e6 * rand()) * 1e3) % 4294967295 # set random seed random.seed(self.seed) numpy.random.seed(self.seed) if self.filename: # load given experiment self.load() else: # identifies the experiment self.id = randint(1E8) # check if a comment was passed via the command line parser = ArgumentParser(add_help=False) parser.add_argument('--comment') optlist, argv = parser.parse_known_args(sys.argv[1:]) optlist = vars(optlist) # remove comment command line argument from argument list sys.argv[1:] = argv # comment given as command line argument self.comment = optlist.get('comment', '') # get OS information self.platform = sys.platform # arguments to the program self.argv = sys.argv self.script_path = sys.argv[0] try: with open(sys.argv[0]) as handle: # store python script self.script = handle.read() except: warn('Unable to read Python script.') # environment variables self.environ = os.environ self.cwd = os.getcwd() self.hostname = socket.gethostname() # store some information about the processor(s) if self.platform == 'linux2': cmd = 'egrep "processor|model name|cpu MHz|cache size" /proc/cpuinfo' with os.popen(cmd) as handle: self.processors = handle.read() elif self.platform == 'darwin': cmd = 'system_profiler SPHardwareDataType | egrep "Processor|Cores|L2|Bus"' with os.popen(cmd) as handle: self.processors = handle.read() # version information self.versions['python'] = sys.version self.versions['numpy'] = numpy.__version__ self.versions['scipy'] = scipy.__version__ # store information about git repository if path.isdir('.git'): # get commit hash pr1 = Popen(['git', 'log', '-1'], stdout=PIPE) pr2 = Popen(['head', '-1'], stdin=pr1.stdout, stdout=PIPE) pr3 = Popen(['cut', '-d', ' ', '-f', '2'], stdin=pr2.stdout, stdout=PIPE) self.commit = pr3.communicate()[0][:-1] # check if project contains uncommitted changes pr1 = Popen(['git', 'status', '--porcelain'], stdout=PIPE) pr2 = Popen(['egrep', '^.M'], stdin=pr1.stdout, stdout=PIPE) self.modified = pr2.communicate()[0] if self.modified: warn('Uncommitted changes.') else: # no git repository self.commit = None self.modified = False # server managing experiments self.server = server self.port = port self.status('running') def status(self, status, **kwargs): if self.server: try: conn = HTTPConnection(self.server, self.port) conn.request('GET', '/version/') resp = conn.getresponse() if not resp.read().startswith('Experiment'): raise RuntimeError() HTTPConnection(self.server, self.port).request('POST', '', str(dict({ 'id': self.id, 'version': __version__, 'status': status, 'hostname': self.hostname, 'cwd': self.cwd, 'script_path': self.script_path, 'script': self.script, 'comment': self.comment, 'time': self.time, }, **kwargs))) except: warn('Unable to connect to \'{0}:{1}\'.'.format(self.server, self.port)) def
(self, progress): self.status('PROGRESS', progress=progress) def save(self, filename=None, overwrite=False): """ Store results. If a filename is given, the default is overwritten. @type filename: string @param filename: path to where the experiment will be stored @type overwrite: boolean @param overwrite: overwrite existing files """ self.duration = time() - self.time if filename is None: filename = self.filename else: # replace {0} and {1} by date and time tmp1 = strftime('%d%m%Y', localtime(time())) tmp2 = strftime('%H%M%S', localtime(time())) filename = filename.format(tmp1, tmp2) self.filename = filename # make sure directory exists try: os.makedirs(path.dirname(filename)) except OSError: pass # make sure filename is unique counter = 0 pieces = path.splitext(filename) if not overwrite: while path.exists(filename): counter += 1 filename = pieces[0] + '.' + str(counter) + pieces[1] if counter: warn(''.join(pieces) + ' already exists. Saving to ' + filename + '.') # store experiment with open(filename, 'wb') as handle: dump({ 'version': __version__, 'id': self.id, 'time': self.time, 'seed': self.seed, 'duration': self.duration, 'environ': self.environ, 'hostname': self.hostname, 'cwd': self.cwd, 'argv': self.argv, 'script': self.script, 'script_path': self.script_path, 'processors': self.processors, 'platform': self.platform, 'comment': self.comment, 'commit': self.commit, 'modified': self.modified, 'versions': self.versions, 'results': self.results}, handle, 1) self.status('SAVE', filename=filename, duration=self.duration) def load(self, filename=None): """ Loads experimental results from the specified file. @type filename: string @param filename: path to where the experiment is stored """ if filename: self.filename = filename with open(self.filename, 'rb') as handle: res = load(handle) self.time = res['time'] self.seed = res['seed'] self.duration = res['duration'] self.processors = res['processors'] self.environ = res['environ'] self.platform = res['platform'] self.comment = res['comment'] self.commit = res['commit'] self.modified = res['modified'] self.versions = res['versions'] self.results = res['results'] self.argv = res['argv'] \ if StrictVersion(res['version']) >= '0.3.1' else None self.script = res['script'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.script_path = res['script_path'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.cwd = res['cwd'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.hostname = res['hostname'] \ if StrictVersion(res['version']) >= '0.4.0' else None self.id = res['id'] \ if StrictVersion(res['version']) >= '0.4.0' else None def __getitem__(self, key): return self.results[key] def __setitem__(self, key, value): self.results[key] = value def __delitem__(self, key): del self.results[key] class ExperimentRequestHandler(BaseHTTPRequestHandler): """ Renders HTML showing running and finished experiments. """ xpck_path = '' running = {} finished = {} def do_GET(self): """ Renders HTML displaying running and saved experiments. """ # number of bars representing progress max_bars = 20 if self.path == '/version/': self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write('Experiment {0}'.format(__version__)) elif self.path.startswith('/running/'): id = int([s for s in self.path.split('/') if s != ''][-1]) # display running experiment if id in ExperimentRequestHandler.running: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Experiment</h2>') instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Hostname:</th><td>{0}</td></tr>'.format(instance['hostname'])) self.wfile.write('<tr><th>Status:</th><td class="running">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) self.wfile.write(HTML_FOOTER) elif id in ExperimentRequestHandler.finished: self.send_response(302) self.send_header('Location', '/finished/{0}/'.format(id)) self.end_headers() else: self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) elif self.path.startswith('/finished/'): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) id = int([s for s in self.path.split('/') if s != ''][-1]) # display finished experiment if id in ExperimentRequestHandler.finished: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<h2>Experiment</h2>') self.wfile.write('<table>') self.wfile.write('<tr><th>Experiment:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['script_path']))) self.wfile.write('<tr><th>Results:</th><td>{0}</td></tr>'.format( os.path.join(instance['cwd'], instance['filename']))) self.wfile.write('<tr><th>Status:</th><td class="finished">{0}</td></tr>'.format(instance['status'])) self.wfile.write('<tr><th>Progress:</th><td class="progress"><span class="bars">{0}</span>{1}</td></tr>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<tr><th>Start:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<tr><th>End:</th><td>{0}</td></tr>'.format( strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['duration'])))) self.wfile.write('<tr><th>Comment:</th><td>{0}</td></tr>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</table>') self.wfile.write('<h2>Results</h2>') try: experiment = Experiment(os.path.join(instance['cwd'], instance['filename'])) except: self.wfile.write('Could not open file.') else: self.wfile.write('<table>') for key, value in experiment.results.items(): self.wfile.write('<tr><th>{0}</th><td>{1}</td></tr>'.format(key, value)) self.wfile.write('</table>') self.wfile.write('<h2>Script</h2>') self.wfile.write('<pre>{0}</pre>'.format(instance['script'])) else: self.wfile.write('<h2>404</h2>') self.wfile.write('Requested experiment not found.') self.wfile.write(HTML_FOOTER) else: files = [] if 'xpck_path' in ExperimentRequestHandler.__dict__: if ExperimentRequestHandler.xpck_path != '': for path in ExperimentRequestHandler.xpck_path.split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] if 'XPCK_PATH' in os.environ: for path in os.environ['XPCK_PATH'].split(':'): files += [os.path.join(path, f) for f in os.listdir(path) if f.endswith('.xpck')] self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(HTML_HEADER) self.wfile.write('<h2>Running</h2>') # display running experiments if ExperimentRequestHandler.running: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Experiment</th>') self.wfile.write('<th>Hostname</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] for instance in ExperimentRequestHandler.running.values()] ids = ExperimentRequestHandler.running.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.running[id] num_bars = int(instance['progress']) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/running/{1}/">{0}</a></td>'.format( instance['script_path'], instance['id'])) self.wfile.write('<td>{0}</td>'.format(instance['hostname'])) self.wfile.write('<td class="running">{0}</td>'.format(instance['status'])) self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No running experiments.') self.wfile.write('<h2>Saved</h2>') # display saved experiments if ExperimentRequestHandler.finished: self.wfile.write('<table>') self.wfile.write('<tr>') self.wfile.write('<th>Results</th>') self.wfile.write('<th>Status</th>') self.wfile.write('<th>Progress</th>') self.wfile.write('<th>Start</th>') self.wfile.write('<th>End</th>') self.wfile.write('<th>Comment</th>') self.wfile.write('</tr>') # sort ids by start time of experiment times = [instance['time'] + instance['duration'] for instance in ExperimentRequestHandler.finished.values()] ids = ExperimentRequestHandler.finished.keys() ids = [ids[i] for i in argsort(times)][::-1] for id in ids: instance = ExperimentRequestHandler.finished[id] if id in ExperimentRequestHandler.running: progress = ExperimentRequestHandler.running[id]['progress'] else: progress = 100 num_bars = int(progress) * max_bars / 100 self.wfile.write('<tr>') self.wfile.write('<td class="filepath"><a href="/finished/{1}/">{0}</a></td>'.format( instance['filename'], instance['id'])) self.wfile.write('<td class="finished">saved</td>') self.wfile.write('<td class="progress"><span class="bars">{0}</span>{1}</td>'.format( '|' * num_bars, '|' * (max_bars - num_bars))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'])))) self.wfile.write('<td>{0}</td>'.format(strftime('%a, %d %b %Y %H:%M:%S', localtime(instance['time'] + instance['duration'])))) self.wfile.write('<td class="comment">{0}</td>'.format( instance['comment'] if instance['comment'] else '-')) self.wfile.write('</tr>') self.wfile.write('</table>') else: self.wfile.write('No saved experiments.') self.wfile.write(HTML_FOOTER) def do_POST(self): instances = ExperimentRequestHandler.running instance = eval(self.rfile.read(int(self.headers['Content-Length']))) if instance['status'] is 'PROGRESS': if instance['id'] not in instances: instances[instance['id']] = instance instances[instance['id']]['status'] = 'running' instances[instance['id']]['progress'] = instance['progress'] elif instance['status'] is 'SAVE': ExperimentRequestHandler.finished[instance['id']] = instance ExperimentRequestHandler.finished[instance['id']]['status'] = 'saved' else: if instance['id'] in instances: progress = instances[instance['id']]['progress'] else: progress = 0 instances[instance['id']] = instance instances[instance['id']]['progress'] = progress if instance['status'] is None: try: del instances[instance['id']] except: pass class XUnpickler(Unpickler): """ An extension of the Unpickler class which resolves some backwards compatibility issues of Numpy. """ def find_class(self, module, name): """ Helps Unpickler to find certain Numpy modules. """ try: numpy_version = StrictVersion(numpy.__version__) if numpy_version >= '1.5.0': if module == 'numpy.core.defmatrix': module = 'numpy.matrixlib.defmatrix' except ValueError: pass return Unpickler.find_class(self, module, name) def load(file): return XUnpickler(file).load() def main(argv): """ Load and display experiment information. """ if len(argv) < 2: print 'Usage:', argv[0], '[--server] [--port=<port>] [--path=<path>] [filename]' return 0 optlist, argv = getopt(argv[1:], '', ['server', 'port=', 'path=']) optlist = dict(optlist) if '--server' in optlist: try: ExperimentRequestHandler.xpck_path = optlist.get('--path', '') port = optlist.get('--port', 8000) # start server server = HTTPServer(('', port), ExperimentRequestHandler) server.serve_forever() except KeyboardInterrupt: server.socket.close() return 0 # load experiment experiment = Experiment(sys.argv[1]) if len(argv) > 1: # print arguments for arg in argv[1:]: try: print experiment[arg] except: print experiment[int(arg)] return 0 # print summary of experiment print experiment return 0 HTML_HEADER = '''<html> <head> <title>Experiments</title> <style type="text/css"> body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 11pt; color: black; background: white; padding: 0pt 20pt; } h2 { margin-top: 20pt; font-size: 16pt; } table { border-collapse: collapse; } tr:nth-child(even) { background: #f4f4f4; } th { font-size: 12pt; text-align: left; padding: 2pt 10pt 3pt 0pt; } td { font-size: 10pt; padding: 3pt 10pt 2pt 0pt; } pre { font-size: 10pt; background: #f4f4f4; padding: 5pt; } a { text-decoration: none; color: #04a; } .running { color: #08b; } .finished { color: #390; } .comment { min-width: 200pt; font-style: italic; } .progress { color: #ccc; } .progress .bars { color: black; } </style> </head> <body>''' HTML_FOOTER = ''' </body> </html>''' if __name__ == '__main__': sys.exit(main(sys.argv))
progress
identifier_name