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
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer
} impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = self.pos; while self.valid_ws() { self.pos += 1; } self.pos - prev_pos } fn string(&mut self) -> Option<String> { let mut tok = Vec::<u8>::new(); loop { if self.eof() { break } match self.ch() { b' ' => break, b'\t' => break, b'\r' => break, b'\n' => break, b'"' => break, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn quoted_string(&mut self) -> Option<String> { let mut tok = Vec::<u8>::new(); self.pos += 1; loop { if self.eof() { break; } match self.ch() { b'"' => { self.pos += 1; break; }, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn valid_ws(&self) -> bool { if self.eof() { return false; } match self.ch() { b' ' => true, b'\t' => true, b'\r' => true, b'\n' => true, _ => false } } } impl<'a> Iterator for Lexer<'a> { type Item = String; fn next(&mut self) -> Option<String> { self.skip_ws(); if self.eof() { return None; } match self.ch() { b'"' => self.quoted_string(), _ => self.string() } } } #[test] fn tokenize() { let src = b" foo bar \"a b\" baz "; let lexer = Lexer::new(src); let tokens: Vec<_> = lexer.collect(); assert_eq!(4, tokens.len()); assert_eq!("foo".to_string(), tokens[0]); assert_eq!("bar".to_string(), tokens[1]); assert_eq!("a b".to_string(), tokens[2]); assert_eq!("baz".to_string(), tokens[3]); }
{ Lexer { src: src, pos: 0 } }
identifier_body
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer { Lexer { src: src, pos: 0 } } } impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = self.pos; while self.valid_ws() { self.pos += 1; } self.pos - prev_pos } fn string(&mut self) -> Option<String> {
match self.ch() { b' ' => break, b'\t' => break, b'\r' => break, b'\n' => break, b'"' => break, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn quoted_string(&mut self) -> Option<String> { let mut tok = Vec::<u8>::new(); self.pos += 1; loop { if self.eof() { break; } match self.ch() { b'"' => { self.pos += 1; break; }, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn valid_ws(&self) -> bool { if self.eof() { return false; } match self.ch() { b' ' => true, b'\t' => true, b'\r' => true, b'\n' => true, _ => false } } } impl<'a> Iterator for Lexer<'a> { type Item = String; fn next(&mut self) -> Option<String> { self.skip_ws(); if self.eof() { return None; } match self.ch() { b'"' => self.quoted_string(), _ => self.string() } } } #[test] fn tokenize() { let src = b" foo bar \"a b\" baz "; let lexer = Lexer::new(src); let tokens: Vec<_> = lexer.collect(); assert_eq!(4, tokens.len()); assert_eq!("foo".to_string(), tokens[0]); assert_eq!("bar".to_string(), tokens[1]); assert_eq!("a b".to_string(), tokens[2]); assert_eq!("baz".to_string(), tokens[3]); }
let mut tok = Vec::<u8>::new(); loop { if self.eof() { break }
random_line_split
FontLineShapeRenderer.js
Clazz.declarePackage ("org.jmol.render"); Clazz.load (["org.jmol.render.ShapeRenderer", "org.jmol.util.Point3f", "$.Point3i", "$.Vector3f"], "org.jmol.render.FontLineShapeRenderer", ["java.lang.Float", "org.jmol.constant.EnumAxesMode", "org.jmol.util.TextFormat"], function () { c$ = Clazz.decorateAsClass (function () { this.imageFontScaling = 0; this.atomA = null; this.atomB = null; this.atomC = null; this.atomD = null; this.font3d = null; this.pt0 = null; this.pt1 = null; this.pt2 = null; this.pointT = null;
this.pointT3 = null; this.vectorT = null; this.vectorT2 = null; this.vectorT3 = null; this.tickInfo = null; this.draw000 = true; this.endcap = 3; Clazz.instantialize (this, arguments); }, org.jmol.render, "FontLineShapeRenderer", org.jmol.render.ShapeRenderer); Clazz.prepareFields (c$, function () { this.pt0 = new org.jmol.util.Point3i (); this.pt1 = new org.jmol.util.Point3i (); this.pt2 = new org.jmol.util.Point3i (); this.pointT = new org.jmol.util.Point3f (); this.pointT2 = new org.jmol.util.Point3f (); this.pointT3 = new org.jmol.util.Point3f (); this.vectorT = new org.jmol.util.Vector3f (); this.vectorT2 = new org.jmol.util.Vector3f (); this.vectorT3 = new org.jmol.util.Vector3f (); }); Clazz.defineMethod (c$, "getDiameter", function (z, madOrPixels) { var diameter; var isMad = (madOrPixels > 20); switch (this.exportType) { case 1: diameter = (isMad ? madOrPixels : Clazz.doubleToInt (Math.floor (this.viewer.unscaleToScreen (z, madOrPixels * 2) * 1000))); break; default: if (isMad) { diameter = this.viewer.scaleToScreen (z, madOrPixels); } else { if (this.g3d.isAntialiased ()) madOrPixels += madOrPixels; diameter = madOrPixels; }} return diameter; }, "~N,~N"); Clazz.defineMethod (c$, "renderLine", function (p0, p1, diameter, pt0, pt1, drawTicks) { pt0.set (Clazz.doubleToInt (Math.floor (p0.x)), Clazz.doubleToInt (Math.floor (p0.y)), Clazz.doubleToInt (Math.floor (p0.z))); pt1.set (Clazz.doubleToInt (Math.floor (p1.x)), Clazz.doubleToInt (Math.floor (p1.y)), Clazz.doubleToInt (Math.floor (p1.z))); if (diameter < 0) this.g3d.drawDottedLine (pt0, pt1); else this.g3d.fillCylinder (this.endcap, diameter, pt0, pt1); if (!drawTicks || this.tickInfo == null) return; this.atomA.screenX = pt0.x; this.atomA.screenY = pt0.y; this.atomA.screenZ = pt0.z; this.atomB.screenX = pt1.x; this.atomB.screenY = pt1.y; this.atomB.screenZ = pt1.z; this.drawTicks (this.atomA, this.atomB, diameter, true); }, "org.jmol.util.Point3f,org.jmol.util.Point3f,~N,org.jmol.util.Point3i,org.jmol.util.Point3i,~B"); Clazz.defineMethod (c$, "drawTicks", function (pt1, pt2, diameter, withLabels) { if (Float.isNaN (this.tickInfo.first)) this.tickInfo.first = 0; this.drawTicks (pt1, pt2, this.tickInfo.ticks.x, 8, diameter, (!withLabels ? null : this.tickInfo.tickLabelFormats == null ? ["%0.2f"] : this.tickInfo.tickLabelFormats)); this.drawTicks (pt1, pt2, this.tickInfo.ticks.y, 4, diameter, null); this.drawTicks (pt1, pt2, this.tickInfo.ticks.z, 2, diameter, null); }, "org.jmol.util.Point3fi,org.jmol.util.Point3fi,~N,~B"); Clazz.defineMethod (c$, "drawTicks", ($fz = function (ptA, ptB, dx, length, diameter, formats) { if (dx == 0) return; if (this.g3d.isAntialiased ()) length *= 2; this.vectorT2.set (ptB.screenX, ptB.screenY, 0); this.vectorT.set (ptA.screenX, ptA.screenY, 0); this.vectorT2.sub (this.vectorT); if (this.vectorT2.length () < 50) return; var signFactor = this.tickInfo.signFactor; this.vectorT.setT (ptB); this.vectorT.sub (ptA); var d0 = this.vectorT.length (); if (this.tickInfo.scale != null) { if (Float.isNaN (this.tickInfo.scale.x)) { var a = this.viewer.getUnitCellInfo (0); if (!Float.isNaN (a)) this.vectorT.set (this.vectorT.x / a, this.vectorT.y / this.viewer.getUnitCellInfo (1), this.vectorT.z / this.viewer.getUnitCellInfo (2)); } else { this.vectorT.set (this.vectorT.x * this.tickInfo.scale.x, this.vectorT.y * this.tickInfo.scale.y, this.vectorT.z * this.tickInfo.scale.z); }}var d = this.vectorT.length () + 0.0001 * dx; if (d < dx) return; var f = dx / d * d0 / d; this.vectorT.scale (f); var dz = (ptB.screenZ - ptA.screenZ) / (d / dx); d += this.tickInfo.first; var p = (Clazz.doubleToInt (Math.floor (this.tickInfo.first / dx))) * dx - this.tickInfo.first; this.pointT.scaleAdd2 (p / dx, this.vectorT, ptA); p += this.tickInfo.first; var z = ptA.screenZ; if (diameter < 0) diameter = 1; this.vectorT2.set (-this.vectorT2.y, this.vectorT2.x, 0); this.vectorT2.scale (length / this.vectorT2.length ()); var ptRef = this.tickInfo.reference; if (ptRef == null) { this.pointT3.setT (this.viewer.getBoundBoxCenter ()); if (this.viewer.getAxesMode () === org.jmol.constant.EnumAxesMode.BOUNDBOX) { this.pointT3.x += 1.0; this.pointT3.y += 1.0; this.pointT3.z += 1.0; }} else { this.pointT3.setT (ptRef); }this.viewer.transformPtScr (this.pointT3, this.pt2); var horizontal = (Math.abs (this.vectorT2.x / this.vectorT2.y) < 0.2); var centerX = horizontal; var centerY = !horizontal; var rightJustify = !centerX && (this.vectorT2.x < 0); var drawLabel = (formats != null && formats.length > 0); var x; var y; var val = new Array (1); var i = (this.draw000 ? 0 : -1); while (p < d) { if (p >= this.tickInfo.first) { this.pointT2.setT (this.pointT); this.viewer.transformPt3f (this.pointT2, this.pointT2); this.drawLine (Clazz.doubleToInt (Math.floor (this.pointT2.x)), Clazz.doubleToInt (Math.floor (this.pointT2.y)), Clazz.floatToInt (z), (x = Clazz.doubleToInt (Math.floor (this.pointT2.x + this.vectorT2.x))), (y = Clazz.doubleToInt (Math.floor (this.pointT2.y + this.vectorT2.y))), Clazz.floatToInt (z), diameter); if (drawLabel && (this.draw000 || p != 0)) { val[0] = new Float ((p == 0 ? 0 : p * signFactor)); var s = org.jmol.util.TextFormat.sprintf (formats[i % formats.length], "f", val); this.drawString (x, y, Clazz.floatToInt (z), 4, rightJustify, centerX, centerY, Clazz.doubleToInt (Math.floor (this.pointT2.y)), s); }}this.pointT.add (this.vectorT); p += dx; z += dz; i++; } }, $fz.isPrivate = true, $fz), "org.jmol.util.Point3fi,org.jmol.util.Point3fi,~N,~N,~N,~A"); Clazz.defineMethod (c$, "drawLine", function (x1, y1, z1, x2, y2, z2, diameter) { this.pt0.set (x1, y1, z1); this.pt1.set (x2, y2, z2); if (diameter < 0) { this.g3d.drawDashedLine (4, 2, this.pt0, this.pt1); return 1; }this.g3d.fillCylinder (2, diameter, this.pt0, this.pt1); return Clazz.doubleToInt ((diameter + 1) / 2); }, "~N,~N,~N,~N,~N,~N,~N"); Clazz.defineMethod (c$, "drawString", function (x, y, z, radius, rightJustify, centerX, centerY, yRef, sVal) { if (sVal == null) return; var width = this.font3d.stringWidth (sVal); var height = this.font3d.getAscent (); var xT = x; if (rightJustify) xT -= Clazz.doubleToInt (radius / 2) + 2 + width; else if (centerX) xT -= Clazz.doubleToInt (radius / 2) + 2 + Clazz.doubleToInt (width / 2); else xT += Clazz.doubleToInt (radius / 2) + 2; var yT = y; if (centerY) yT += Clazz.doubleToInt (height / 2); else if (yRef == 0 || yRef < y) yT += height; else yT -= Clazz.doubleToInt (radius / 2); var zT = z - radius - 2; if (zT < 1) zT = 1; this.g3d.drawString (sVal, this.font3d, xT, yT, zT, zT, 0); }, "~N,~N,~N,~N,~B,~B,~B,~N,~S"); });
this.pointT2 = null;
random_line_split
webpack.prod.config.js
const assign = require('object-assign'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const baseConfig = require('./webpack.base.config.js'); const config = Object.assign(baseConfig, {}); Object.assign = assign; // No hot reload, just straight compiling. // Keep this in sync with webpack.config.js and .babelrc config.module.rules.push({ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: ['latest', 'react'], plugins: ['transform-decorators-legacy'], },
test: /(\.scss|\.css)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ 'css-loader', 'sass-loader', ], }), }); module.exports = config;
}); // Extract all the sass and scss into a separate file. config.plugins.push(new ExtractTextPlugin('styles.css')); config.module.rules.push({
random_line_split
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloyan@kaloyan.info> * * @author * brainworXX GmbH <info@brainworxx.de> * * @license * http://opensource.org/licenses/LGPL-2.1 * * GNU Lesser General Public License Version 2.1 * * kreXX Copyright (C) 2014-2022 Brainworxx GmbH * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class Eventhandler { /** * Here we store our callbacks. * * @var {Function[]} */ protected storage:Function[][] = []; /** * Instance of the kreXX dom tools class. */ protected kdt:Kdt; /** * Creating a Kdt instance, and registering of our event handler * * @param {string} selector */ constructor(selector:string) { this.kdt = new Kdt(); // Register the event handler. let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', this.handle); } } /** * Adds an event listener to a list of elements. * * @param {string} selector * @param {string} eventName * @param {Function} callBack * */ public addEvent(selector:string, eventName:string, callBack:EventListener|Function): void { // We use the clickHandler instead. if (eventName === 'click') { this.addToStorage(selector, callBack); } else { /** @type {NodeList} */ let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener(eventName, (callBack as EventListener)); } } } /** * Prevent the bubbling of an event in the kdt event handler. * * @param {Event} event */ public preventBubble (event:Event): void { event.stop = true; } /** * Add another event to the storage. * * @param {string} selector * @param {Function} callback */ protected addToStorage(selector:string, callback:Function): void { if (!(selector in this.storage)) { this.storage[selector] = []; } this.storage[selector].push(callback); } /** * Whenever a click is bubbled on a kreXX instance, we try to find * the according callback, and simply call it. * * @param {Event} event * @event click */ protected handle = (event:Event): void => { // We stop the event in its tracks. event.stopPropagation(); event.stop = false; let element:Node = (event.target as Node); let selector:string; let i:number; let callbackArray:Function[] = []; do { // We need to test the element on all selectors. for (selector in this.storage) { if ((element as Element).matches(selector) === false) { continue; } callbackArray = this.storage[selector]; // Got to call them all. for (i = 0; i < callbackArray.length; i++) { callbackArray[i](event, element); if (event.stop) { // Our "implementation" of stopPropagation(). return; } } } // Time to test the parent. element = (element as Node).parentNode; // Test if we have reached the top of the rabbit hole. if (element === event.currentTarget) { element = null; } } while (element !== null && typeof (element as Element).matches === 'function'); }; /** * Triggers an event on an element. * * @param {Element} el * @param {string} eventName */ public triggerEvent(el:Element, eventName:string): void { /** @type {Event} */
el.dispatchEvent(event); } }
let event:Event = new Event(eventName, {bubbles: true,cancelable: false});
random_line_split
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloyan@kaloyan.info> * * @author * brainworXX GmbH <info@brainworxx.de> * * @license * http://opensource.org/licenses/LGPL-2.1 * * GNU Lesser General Public License Version 2.1 * * kreXX Copyright (C) 2014-2022 Brainworxx GmbH * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class Eventhandler { /** * Here we store our callbacks. * * @var {Function[]} */ protected storage:Function[][] = []; /** * Instance of the kreXX dom tools class. */ protected kdt:Kdt; /** * Creating a Kdt instance, and registering of our event handler * * @param {string} selector */ constructor(selector:string) { this.kdt = new Kdt(); // Register the event handler. let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', this.handle); } } /** * Adds an event listener to a list of elements. * * @param {string} selector * @param {string} eventName * @param {Function} callBack * */ public addEvent(selector:string, eventName:string, callBack:EventListener|Function): void { // We use the clickHandler instead. if (eventName === 'click') { this.addToStorage(selector, callBack); } else { /** @type {NodeList} */ let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener(eventName, (callBack as EventListener)); } } } /** * Prevent the bubbling of an event in the kdt event handler. * * @param {Event} event */ public preventBubble (event:Event): void { event.stop = true; } /** * Add another event to the storage. * * @param {string} selector * @param {Function} callback */ protected addToStorage(selector:string, callback:Function): void
/** * Whenever a click is bubbled on a kreXX instance, we try to find * the according callback, and simply call it. * * @param {Event} event * @event click */ protected handle = (event:Event): void => { // We stop the event in its tracks. event.stopPropagation(); event.stop = false; let element:Node = (event.target as Node); let selector:string; let i:number; let callbackArray:Function[] = []; do { // We need to test the element on all selectors. for (selector in this.storage) { if ((element as Element).matches(selector) === false) { continue; } callbackArray = this.storage[selector]; // Got to call them all. for (i = 0; i < callbackArray.length; i++) { callbackArray[i](event, element); if (event.stop) { // Our "implementation" of stopPropagation(). return; } } } // Time to test the parent. element = (element as Node).parentNode; // Test if we have reached the top of the rabbit hole. if (element === event.currentTarget) { element = null; } } while (element !== null && typeof (element as Element).matches === 'function'); }; /** * Triggers an event on an element. * * @param {Element} el * @param {string} eventName */ public triggerEvent(el:Element, eventName:string): void { /** @type {Event} */ let event:Event = new Event(eventName, {bubbles: true,cancelable: false}); el.dispatchEvent(event); } }
{ if (!(selector in this.storage)) { this.storage[selector] = []; } this.storage[selector].push(callback); }
identifier_body
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloyan@kaloyan.info> * * @author * brainworXX GmbH <info@brainworxx.de> * * @license * http://opensource.org/licenses/LGPL-2.1 * * GNU Lesser General Public License Version 2.1 * * kreXX Copyright (C) 2014-2022 Brainworxx GmbH * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class Eventhandler { /** * Here we store our callbacks. * * @var {Function[]} */ protected storage:Function[][] = []; /** * Instance of the kreXX dom tools class. */ protected kdt:Kdt; /** * Creating a Kdt instance, and registering of our event handler * * @param {string} selector */
(selector:string) { this.kdt = new Kdt(); // Register the event handler. let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', this.handle); } } /** * Adds an event listener to a list of elements. * * @param {string} selector * @param {string} eventName * @param {Function} callBack * */ public addEvent(selector:string, eventName:string, callBack:EventListener|Function): void { // We use the clickHandler instead. if (eventName === 'click') { this.addToStorage(selector, callBack); } else { /** @type {NodeList} */ let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener(eventName, (callBack as EventListener)); } } } /** * Prevent the bubbling of an event in the kdt event handler. * * @param {Event} event */ public preventBubble (event:Event): void { event.stop = true; } /** * Add another event to the storage. * * @param {string} selector * @param {Function} callback */ protected addToStorage(selector:string, callback:Function): void { if (!(selector in this.storage)) { this.storage[selector] = []; } this.storage[selector].push(callback); } /** * Whenever a click is bubbled on a kreXX instance, we try to find * the according callback, and simply call it. * * @param {Event} event * @event click */ protected handle = (event:Event): void => { // We stop the event in its tracks. event.stopPropagation(); event.stop = false; let element:Node = (event.target as Node); let selector:string; let i:number; let callbackArray:Function[] = []; do { // We need to test the element on all selectors. for (selector in this.storage) { if ((element as Element).matches(selector) === false) { continue; } callbackArray = this.storage[selector]; // Got to call them all. for (i = 0; i < callbackArray.length; i++) { callbackArray[i](event, element); if (event.stop) { // Our "implementation" of stopPropagation(). return; } } } // Time to test the parent. element = (element as Node).parentNode; // Test if we have reached the top of the rabbit hole. if (element === event.currentTarget) { element = null; } } while (element !== null && typeof (element as Element).matches === 'function'); }; /** * Triggers an event on an element. * * @param {Element} el * @param {string} eventName */ public triggerEvent(el:Element, eventName:string): void { /** @type {Event} */ let event:Event = new Event(eventName, {bubbles: true,cancelable: false}); el.dispatchEvent(event); } }
constructor
identifier_name
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloyan@kaloyan.info> * * @author * brainworXX GmbH <info@brainworxx.de> * * @license * http://opensource.org/licenses/LGPL-2.1 * * GNU Lesser General Public License Version 2.1 * * kreXX Copyright (C) 2014-2022 Brainworxx GmbH * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class Eventhandler { /** * Here we store our callbacks. * * @var {Function[]} */ protected storage:Function[][] = []; /** * Instance of the kreXX dom tools class. */ protected kdt:Kdt; /** * Creating a Kdt instance, and registering of our event handler * * @param {string} selector */ constructor(selector:string) { this.kdt = new Kdt(); // Register the event handler. let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', this.handle); } } /** * Adds an event listener to a list of elements. * * @param {string} selector * @param {string} eventName * @param {Function} callBack * */ public addEvent(selector:string, eventName:string, callBack:EventListener|Function): void { // We use the clickHandler instead. if (eventName === 'click') { this.addToStorage(selector, callBack); } else { /** @type {NodeList} */ let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener(eventName, (callBack as EventListener)); } } } /** * Prevent the bubbling of an event in the kdt event handler. * * @param {Event} event */ public preventBubble (event:Event): void { event.stop = true; } /** * Add another event to the storage. * * @param {string} selector * @param {Function} callback */ protected addToStorage(selector:string, callback:Function): void { if (!(selector in this.storage)) { this.storage[selector] = []; } this.storage[selector].push(callback); } /** * Whenever a click is bubbled on a kreXX instance, we try to find * the according callback, and simply call it. * * @param {Event} event * @event click */ protected handle = (event:Event): void => { // We stop the event in its tracks. event.stopPropagation(); event.stop = false; let element:Node = (event.target as Node); let selector:string; let i:number; let callbackArray:Function[] = []; do { // We need to test the element on all selectors. for (selector in this.storage) { if ((element as Element).matches(selector) === false) { continue; } callbackArray = this.storage[selector]; // Got to call them all. for (i = 0; i < callbackArray.length; i++) { callbackArray[i](event, element); if (event.stop) { // Our "implementation" of stopPropagation(). return; } } } // Time to test the parent. element = (element as Node).parentNode; // Test if we have reached the top of the rabbit hole. if (element === event.currentTarget)
} while (element !== null && typeof (element as Element).matches === 'function'); }; /** * Triggers an event on an element. * * @param {Element} el * @param {string} eventName */ public triggerEvent(el:Element, eventName:string): void { /** @type {Event} */ let event:Event = new Event(eventName, {bubbles: true,cancelable: false}); el.dispatchEvent(event); } }
{ element = null; }
conditional_block
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}", str::from_utf8(data.as_slice())); } } // Encode array of u8 bytes pub fn EncodeBytes(source: &[u8])->Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); while i < maxLen { let b1 = (bytes[i] & 0b11111100) >> 2; output.push(BaseIndex(b1)); if (i + 1) < maxLen { let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)); output.push(BaseIndex(b2)); if (i + 2) < maxLen { let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6)); output.push(BaseIndex(b3)); let b4 = bytes[i+2] & 0b111111; output.push(BaseIndex(b4)); } else { let b3 = ((bytes[i+1] & 0b1111) << 2); output.push(BaseIndex(b3)); output.push(b'='); } } else { output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); } i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); if source.len() % 4 != 0 { return output; } while i < maxLen { let value1:u8 = BaseIndexToByte(bytes[i]); let value2:u8 = BaseIndexToByte(bytes[i+1]); let value3:u8 = BaseIndexToByte(bytes[i+2]); let value4:u8 = BaseIndexToByte(bytes[i+3]); let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4; let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2; let b3: u8 = (value3 & 0b11) << 6 | value4; output.push(b1); output.push(b2); output.push(b3); i += 4; } output } // Decode str pub fn
(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8 { match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } } // Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'} b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } } } } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0"); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("ab"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("YWI="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("easure."); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("ZWFzdXJlLg=="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU="); ::Base64::Debug::PrintBytes(decoded); decoded = ::Base64::DecodeStr("TW"); ::Base64::Debug::PrintBytes(decoded); }
DecodeStr
identifier_name
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}", str::from_utf8(data.as_slice())); } } // Encode array of u8 bytes pub fn EncodeBytes(source: &[u8])->Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); while i < maxLen { let b1 = (bytes[i] & 0b11111100) >> 2; output.push(BaseIndex(b1)); if (i + 1) < maxLen { let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)); output.push(BaseIndex(b2)); if (i + 2) < maxLen { let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6)); output.push(BaseIndex(b3)); let b4 = bytes[i+2] & 0b111111; output.push(BaseIndex(b4)); } else { let b3 = ((bytes[i+1] & 0b1111) << 2); output.push(BaseIndex(b3)); output.push(b'='); } } else { output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); } i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); if source.len() % 4 != 0 { return output; } while i < maxLen { let value1:u8 = BaseIndexToByte(bytes[i]); let value2:u8 = BaseIndexToByte(bytes[i+1]); let value3:u8 = BaseIndexToByte(bytes[i+2]); let value4:u8 = BaseIndexToByte(bytes[i+3]); let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4; let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2; let b3: u8 = (value3 & 0b11) << 6 | value4; output.push(b1); output.push(b2); output.push(b3); i += 4; } output } // Decode str pub fn DecodeStr(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8 { match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } } // Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'}
} } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0"); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("ab"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("YWI="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("easure."); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("ZWFzdXJlLg=="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU="); ::Base64::Debug::PrintBytes(decoded); decoded = ::Base64::DecodeStr("TW"); ::Base64::Debug::PrintBytes(decoded); }
b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } }
random_line_split
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}", str::from_utf8(data.as_slice())); } } // Encode array of u8 bytes pub fn EncodeBytes(source: &[u8])->Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); while i < maxLen { let b1 = (bytes[i] & 0b11111100) >> 2; output.push(BaseIndex(b1)); if (i + 1) < maxLen { let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)); output.push(BaseIndex(b2)); if (i + 2) < maxLen { let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6)); output.push(BaseIndex(b3)); let b4 = bytes[i+2] & 0b111111; output.push(BaseIndex(b4)); } else { let b3 = ((bytes[i+1] & 0b1111) << 2); output.push(BaseIndex(b3)); output.push(b'='); } } else { output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); } i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); if source.len() % 4 != 0 { return output; } while i < maxLen { let value1:u8 = BaseIndexToByte(bytes[i]); let value2:u8 = BaseIndexToByte(bytes[i+1]); let value3:u8 = BaseIndexToByte(bytes[i+2]); let value4:u8 = BaseIndexToByte(bytes[i+3]); let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4; let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2; let b3: u8 = (value3 & 0b11) << 6 | value4; output.push(b1); output.push(b2); output.push(b3); i += 4; } output } // Decode str pub fn DecodeStr(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8
// Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'} b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } } } } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0"); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("ab"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("YWI="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("easure."); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("ZWFzdXJlLg=="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU="); ::Base64::Debug::PrintBytes(decoded); decoded = ::Base64::DecodeStr("TW"); ::Base64::Debug::PrintBytes(decoded); }
{ match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } }
identifier_body
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}", str::from_utf8(data.as_slice())); } } // Encode array of u8 bytes pub fn EncodeBytes(source: &[u8])->Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); while i < maxLen { let b1 = (bytes[i] & 0b11111100) >> 2; output.push(BaseIndex(b1)); if (i + 1) < maxLen { let b2 = (((bytes[i] & 0b11) << 4) | ((bytes[i+1] & 0b11110000) >> 4)); output.push(BaseIndex(b2)); if (i + 2) < maxLen { let b3 = (((bytes[i+1] & 0b1111) << 2) | ((bytes[i+2] & 0b11000000) >> 6)); output.push(BaseIndex(b3)); let b4 = bytes[i+2] & 0b111111; output.push(BaseIndex(b4)); } else { let b3 = ((bytes[i+1] & 0b1111) << 2); output.push(BaseIndex(b3)); output.push(b'='); } } else
i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; let mut i =0; let mut output:Vec<u8> = vec![]; let maxLen = bytes.len(); if source.len() % 4 != 0 { return output; } while i < maxLen { let value1:u8 = BaseIndexToByte(bytes[i]); let value2:u8 = BaseIndexToByte(bytes[i+1]); let value3:u8 = BaseIndexToByte(bytes[i+2]); let value4:u8 = BaseIndexToByte(bytes[i+3]); let b1: u8 = value1 << 2 | (value2 & 0b00110000) >> 4; let b2: u8 = (value2 & 0b1111) << 4 | (value3 & 0b111100) >> 2; let b3: u8 = (value3 & 0b11) << 6 | value4; output.push(b1); output.push(b2); output.push(b3); i += 4; } output } // Decode str pub fn DecodeStr(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8 { match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } } // Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'} b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } } } } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2ljaW5nIGVsaXQsIHNlZCBkbyBlaXVzbW9kIHRlbXBvciBpbmNpZGlkdW50IHV0"); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("ab"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("YWI="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("easure."); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("ZWFzdXJlLg=="); ::Base64::Debug::PrintBytes(decoded); encoded = ::Base64::EncodeStr("C:\\Users\\AppData\\Local\\Viky Notes\\VikyNotes.exe"); ::Base64::Debug::PrintBytes(encoded); decoded = ::Base64::DecodeStr("QzpcVXNlcnNcQXBwRGF0YVxMb2NhbFxWaWt5IE5vdGVzXFZpa3lOb3Rlcy5leGU="); ::Base64::Debug::PrintBytes(decoded); decoded = ::Base64::DecodeStr("TW"); ::Base64::Debug::PrintBytes(decoded); }
{ output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); }
conditional_block
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of # ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ############################################################################### from PyQt4.QtCore import Qt from PyQt4.QtGui import QColor from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui from lazyflow.operators import OpMultiArraySlicer2 from ilastik.utility.exportingOperator import ExportingGui class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ): """ A subclass of the generic data export gui that creates custom layer viewers. """ def __init__(self, *args, **kwargs): super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs) self._exporting_operator = None def set_exporting_operator(self, op): self._exporting_operator = op def get_exporting_operator(self, lane=0): return self._exporting_operator.getLane(lane) def createLayerViewer(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane) def get_export_dialog_title(self):
@property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic() from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout group = QGroupBox("Export Object Feature Table", self.drawer) group.setLayout(QVBoxLayout()) self.drawer.layout().addWidget(group) btn = QPushButton("Configure and export", group) btn.clicked.connect(self.show_export_dialog) group.layout().addWidget(btn) def _createDefault16ColorColorTable(): colors = [] # Transparent for the zero label colors.append(QColor(0,0,0,0)) # ilastik v0.5 colors colors.append( QColor( Qt.red ) ) colors.append( QColor( Qt.green ) ) colors.append( QColor( Qt.yellow ) ) colors.append( QColor( Qt.blue ) ) colors.append( QColor( Qt.magenta ) ) colors.append( QColor( Qt.darkYellow ) ) colors.append( QColor( Qt.lightGray ) ) # Additional colors colors.append( QColor(255, 105, 180) ) #hot pink colors.append( QColor(102, 205, 170) ) #dark aquamarine colors.append( QColor(165, 42, 42) ) #brown colors.append( QColor(0, 0, 128) ) #navy colors.append( QColor(255, 165, 0) ) #orange colors.append( QColor(173, 255, 47) ) #green-yellow colors.append( QColor(128,0, 128) ) #purple colors.append( QColor(240, 230, 140) ) #khaki # colors.append( QColor(192, 192, 192) ) #silver # colors.append( QColor(69, 69, 69) ) # dark grey # colors.append( QColor( Qt.cyan ) ) assert len(colors) == 16 return [c.rgba() for c in colors] class ObjectClassificationResultsViewer(DataExportLayerViewerGui): _colorTable16 = _createDefault16ColorColorTable() def setupLayers(self): layers = [] opLane = self.topLevelOperatorView selection_names = opLane.SelectionNames.value selection = selection_names[ opLane.InputSelection.value ] # This code depends on a specific order for the export slots. # If those change, update this function! assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities'] if selection == "Object Predictions": fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = "Prediction - Exported" exportLayer.visible = True layers.append(exportLayer) previewSlot = self.topLevelOperatorView.ImageToExport if previewSlot.ready(): previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 ) previewLayer.name = "Prediction - Preview" previewLayer.visible = False layers.append(previewLayer) elif selection == "Object Probabilities": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers elif selection == 'Pixel Probabilities': exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers else: assert False, "Unknown selection." rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = "Raw Data" rawLayer.opacity = 1.0 layers.append(rawLayer) return layers def _initPredictionLayers(self, predictionSlot): layers = [] opLane = self.topLevelOperatorView # Use a slicer to provide a separate slot for each channel layer opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent ) opSlicer.Input.connect( predictionSlot ) opSlicer.AxisFlag.setValue('c') for channel, channelSlot in enumerate(opSlicer.Slices): if channelSlot.ready(): drange = channelSlot.meta.drange or (0.0, 1.0) predictsrc = LazyflowSource(channelSlot) predictLayer = AlphaModulatedLayer( predictsrc, tintColor=QColor.fromRgba(self._colorTable16[channel+1]), # FIXME: This is weird. Why are range and normalize both set to the same thing? range=drange, normalize=drange ) predictLayer.opacity = 1.0 predictLayer.visible = True predictLayer.name = "Probability Channel #{}".format( channel+1 ) layers.append(predictLayer) return layers
return "Export Object Information"
identifier_body
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of # ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ############################################################################### from PyQt4.QtCore import Qt from PyQt4.QtGui import QColor from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui from lazyflow.operators import OpMultiArraySlicer2 from ilastik.utility.exportingOperator import ExportingGui class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ): """ A subclass of the generic data export gui that creates custom layer viewers. """ def __init__(self, *args, **kwargs): super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs) self._exporting_operator = None def set_exporting_operator(self, op): self._exporting_operator = op def get_exporting_operator(self, lane=0): return self._exporting_operator.getLane(lane) def createLayerViewer(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane) def get_export_dialog_title(self): return "Export Object Information" @property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic() from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout group = QGroupBox("Export Object Feature Table", self.drawer) group.setLayout(QVBoxLayout()) self.drawer.layout().addWidget(group) btn = QPushButton("Configure and export", group) btn.clicked.connect(self.show_export_dialog) group.layout().addWidget(btn) def _createDefault16ColorColorTable(): colors = [] # Transparent for the zero label colors.append(QColor(0,0,0,0)) # ilastik v0.5 colors colors.append( QColor( Qt.red ) ) colors.append( QColor( Qt.green ) ) colors.append( QColor( Qt.yellow ) ) colors.append( QColor( Qt.blue ) ) colors.append( QColor( Qt.magenta ) ) colors.append( QColor( Qt.darkYellow ) ) colors.append( QColor( Qt.lightGray ) ) # Additional colors colors.append( QColor(255, 105, 180) ) #hot pink colors.append( QColor(102, 205, 170) ) #dark aquamarine colors.append( QColor(165, 42, 42) ) #brown colors.append( QColor(0, 0, 128) ) #navy colors.append( QColor(255, 165, 0) ) #orange colors.append( QColor(173, 255, 47) ) #green-yellow colors.append( QColor(128,0, 128) ) #purple colors.append( QColor(240, 230, 140) ) #khaki # colors.append( QColor(192, 192, 192) ) #silver # colors.append( QColor(69, 69, 69) ) # dark grey # colors.append( QColor( Qt.cyan ) ) assert len(colors) == 16 return [c.rgba() for c in colors] class ObjectClassificationResultsViewer(DataExportLayerViewerGui): _colorTable16 = _createDefault16ColorColorTable() def setupLayers(self): layers = [] opLane = self.topLevelOperatorView selection_names = opLane.SelectionNames.value selection = selection_names[ opLane.InputSelection.value ] # This code depends on a specific order for the export slots. # If those change, update this function! assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities'] if selection == "Object Predictions":
elif selection == "Object Probabilities": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers elif selection == 'Pixel Probabilities': exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers else: assert False, "Unknown selection." rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = "Raw Data" rawLayer.opacity = 1.0 layers.append(rawLayer) return layers def _initPredictionLayers(self, predictionSlot): layers = [] opLane = self.topLevelOperatorView # Use a slicer to provide a separate slot for each channel layer opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent ) opSlicer.Input.connect( predictionSlot ) opSlicer.AxisFlag.setValue('c') for channel, channelSlot in enumerate(opSlicer.Slices): if channelSlot.ready(): drange = channelSlot.meta.drange or (0.0, 1.0) predictsrc = LazyflowSource(channelSlot) predictLayer = AlphaModulatedLayer( predictsrc, tintColor=QColor.fromRgba(self._colorTable16[channel+1]), # FIXME: This is weird. Why are range and normalize both set to the same thing? range=drange, normalize=drange ) predictLayer.opacity = 1.0 predictLayer.visible = True predictLayer.name = "Probability Channel #{}".format( channel+1 ) layers.append(predictLayer) return layers
fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = "Prediction - Exported" exportLayer.visible = True layers.append(exportLayer) previewSlot = self.topLevelOperatorView.ImageToExport if previewSlot.ready(): previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 ) previewLayer.name = "Prediction - Preview" previewLayer.visible = False layers.append(previewLayer)
conditional_block
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of # ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ############################################################################### from PyQt4.QtCore import Qt from PyQt4.QtGui import QColor from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui from lazyflow.operators import OpMultiArraySlicer2 from ilastik.utility.exportingOperator import ExportingGui class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ): """ A subclass of the generic data export gui that creates custom layer viewers. """ def __init__(self, *args, **kwargs): super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs) self._exporting_operator = None def set_exporting_operator(self, op): self._exporting_operator = op def get_exporting_operator(self, lane=0): return self._exporting_operator.getLane(lane) def createLayerViewer(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane)
@property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic() from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout group = QGroupBox("Export Object Feature Table", self.drawer) group.setLayout(QVBoxLayout()) self.drawer.layout().addWidget(group) btn = QPushButton("Configure and export", group) btn.clicked.connect(self.show_export_dialog) group.layout().addWidget(btn) def _createDefault16ColorColorTable(): colors = [] # Transparent for the zero label colors.append(QColor(0,0,0,0)) # ilastik v0.5 colors colors.append( QColor( Qt.red ) ) colors.append( QColor( Qt.green ) ) colors.append( QColor( Qt.yellow ) ) colors.append( QColor( Qt.blue ) ) colors.append( QColor( Qt.magenta ) ) colors.append( QColor( Qt.darkYellow ) ) colors.append( QColor( Qt.lightGray ) ) # Additional colors colors.append( QColor(255, 105, 180) ) #hot pink colors.append( QColor(102, 205, 170) ) #dark aquamarine colors.append( QColor(165, 42, 42) ) #brown colors.append( QColor(0, 0, 128) ) #navy colors.append( QColor(255, 165, 0) ) #orange colors.append( QColor(173, 255, 47) ) #green-yellow colors.append( QColor(128,0, 128) ) #purple colors.append( QColor(240, 230, 140) ) #khaki # colors.append( QColor(192, 192, 192) ) #silver # colors.append( QColor(69, 69, 69) ) # dark grey # colors.append( QColor( Qt.cyan ) ) assert len(colors) == 16 return [c.rgba() for c in colors] class ObjectClassificationResultsViewer(DataExportLayerViewerGui): _colorTable16 = _createDefault16ColorColorTable() def setupLayers(self): layers = [] opLane = self.topLevelOperatorView selection_names = opLane.SelectionNames.value selection = selection_names[ opLane.InputSelection.value ] # This code depends on a specific order for the export slots. # If those change, update this function! assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities'] if selection == "Object Predictions": fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = "Prediction - Exported" exportLayer.visible = True layers.append(exportLayer) previewSlot = self.topLevelOperatorView.ImageToExport if previewSlot.ready(): previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 ) previewLayer.name = "Prediction - Preview" previewLayer.visible = False layers.append(previewLayer) elif selection == "Object Probabilities": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers elif selection == 'Pixel Probabilities': exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers else: assert False, "Unknown selection." rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = "Raw Data" rawLayer.opacity = 1.0 layers.append(rawLayer) return layers def _initPredictionLayers(self, predictionSlot): layers = [] opLane = self.topLevelOperatorView # Use a slicer to provide a separate slot for each channel layer opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent ) opSlicer.Input.connect( predictionSlot ) opSlicer.AxisFlag.setValue('c') for channel, channelSlot in enumerate(opSlicer.Slices): if channelSlot.ready(): drange = channelSlot.meta.drange or (0.0, 1.0) predictsrc = LazyflowSource(channelSlot) predictLayer = AlphaModulatedLayer( predictsrc, tintColor=QColor.fromRgba(self._colorTable16[channel+1]), # FIXME: This is weird. Why are range and normalize both set to the same thing? range=drange, normalize=drange ) predictLayer.opacity = 1.0 predictLayer.visible = True predictLayer.name = "Probability Channel #{}".format( channel+1 ) layers.append(predictLayer) return layers
def get_export_dialog_title(self): return "Export Object Information"
random_line_split
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # In addition, as a special exception, the copyright holders of # ilastik give you permission to combine ilastik with applets, # workflows and plugins which are not covered under the GNU # General Public License. # # See the LICENSE file for details. License information is also available # on the ilastik web site at: # http://ilastik.org/license.html ############################################################################### from PyQt4.QtCore import Qt from PyQt4.QtGui import QColor from volumina.api import LazyflowSource, ColortableLayer, AlphaModulatedLayer from ilastik.applets.dataExport.dataExportGui import DataExportGui, DataExportLayerViewerGui from lazyflow.operators import OpMultiArraySlicer2 from ilastik.utility.exportingOperator import ExportingGui class ObjectClassificationDataExportGui( DataExportGui, ExportingGui ): """ A subclass of the generic data export gui that creates custom layer viewers. """ def __init__(self, *args, **kwargs): super(ObjectClassificationDataExportGui, self).__init__(*args, **kwargs) self._exporting_operator = None def set_exporting_operator(self, op): self._exporting_operator = op def get_exporting_operator(self, lane=0): return self._exporting_operator.getLane(lane) def
(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane) def get_export_dialog_title(self): return "Export Object Information" @property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): super(ObjectClassificationDataExportGui, self)._initAppletDrawerUic() from PyQt4.QtGui import QGroupBox, QPushButton, QVBoxLayout group = QGroupBox("Export Object Feature Table", self.drawer) group.setLayout(QVBoxLayout()) self.drawer.layout().addWidget(group) btn = QPushButton("Configure and export", group) btn.clicked.connect(self.show_export_dialog) group.layout().addWidget(btn) def _createDefault16ColorColorTable(): colors = [] # Transparent for the zero label colors.append(QColor(0,0,0,0)) # ilastik v0.5 colors colors.append( QColor( Qt.red ) ) colors.append( QColor( Qt.green ) ) colors.append( QColor( Qt.yellow ) ) colors.append( QColor( Qt.blue ) ) colors.append( QColor( Qt.magenta ) ) colors.append( QColor( Qt.darkYellow ) ) colors.append( QColor( Qt.lightGray ) ) # Additional colors colors.append( QColor(255, 105, 180) ) #hot pink colors.append( QColor(102, 205, 170) ) #dark aquamarine colors.append( QColor(165, 42, 42) ) #brown colors.append( QColor(0, 0, 128) ) #navy colors.append( QColor(255, 165, 0) ) #orange colors.append( QColor(173, 255, 47) ) #green-yellow colors.append( QColor(128,0, 128) ) #purple colors.append( QColor(240, 230, 140) ) #khaki # colors.append( QColor(192, 192, 192) ) #silver # colors.append( QColor(69, 69, 69) ) # dark grey # colors.append( QColor( Qt.cyan ) ) assert len(colors) == 16 return [c.rgba() for c in colors] class ObjectClassificationResultsViewer(DataExportLayerViewerGui): _colorTable16 = _createDefault16ColorColorTable() def setupLayers(self): layers = [] opLane = self.topLevelOperatorView selection_names = opLane.SelectionNames.value selection = selection_names[ opLane.InputSelection.value ] # This code depends on a specific order for the export slots. # If those change, update this function! assert selection in ['Object Predictions', 'Object Probabilities', 'Pixel Probabilities'] if selection == "Object Predictions": fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = "Prediction - Exported" exportLayer.visible = True layers.append(exportLayer) previewSlot = self.topLevelOperatorView.ImageToExport if previewSlot.ready(): previewLayer = ColortableLayer( LazyflowSource(previewSlot), colorTable=self._colorTable16 ) previewLayer.name = "Prediction - Preview" previewLayer.visible = False layers.append(previewLayer) elif selection == "Object Probabilities": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers elif selection == 'Pixel Probabilities': exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers previewLayers = self._initPredictionLayers(opLane.ImageToExport) for layer in previewLayers: layer.visible = False layer.name = layer.name + "- Preview" layers += previewLayers else: assert False, "Unknown selection." rawSlot = self.topLevelOperatorView.RawData if rawSlot.ready(): rawLayer = self.createStandardLayerFromSlot(rawSlot) rawLayer.name = "Raw Data" rawLayer.opacity = 1.0 layers.append(rawLayer) return layers def _initPredictionLayers(self, predictionSlot): layers = [] opLane = self.topLevelOperatorView # Use a slicer to provide a separate slot for each channel layer opSlicer = OpMultiArraySlicer2( parent=opLane.viewed_operator().parent ) opSlicer.Input.connect( predictionSlot ) opSlicer.AxisFlag.setValue('c') for channel, channelSlot in enumerate(opSlicer.Slices): if channelSlot.ready(): drange = channelSlot.meta.drange or (0.0, 1.0) predictsrc = LazyflowSource(channelSlot) predictLayer = AlphaModulatedLayer( predictsrc, tintColor=QColor.fromRgba(self._colorTable16[channel+1]), # FIXME: This is weird. Why are range and normalize both set to the same thing? range=drange, normalize=drange ) predictLayer.opacity = 1.0 predictLayer.visible = True predictLayer.name = "Probability Channel #{}".format( channel+1 ) layers.append(predictLayer) return layers
createLayerViewer
identifier_name
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <select name="date" [(ngModel)]="date" (change)="onChangeDate()"> <option *ngFor="let date of dateList" (value)="date">{{date}}</option> </select> </div> </form> <p *ngIf="loading">読み込み中です</p> <table class="table" *ngIf="!loading"> <tr *ngFor="let program of programs"> <th style="width:80px">{{program.start|date:'HH:mm'}} <td>{{program.title}}</td> <td class="text-right"> <button type="button" class="btn btn-default" (click)="onClickRecording(program.id)" *ngIf="program.canRecording"> <span class="glyphicon glyphicon-play" aria-hidden="true"></span> </button> </td> </tr> </table> ` }) export class ProgramListComponent implements OnInit{ @Input() public stationId:string; @Input() public onPlay:(url:string)=>void; private programs:IProgram[] = []; private date:string; private dateList:string[] = []; private loading:boolean = false; constructor(private appService:AppService){ } ngOnInit(){ let start = new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tmp.setDate(tmp.getDate() + 1 )){ this.dat
new Date(); this.date = today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) this.onChangeDate(); } private onChangeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((programs:IProgram[])=>{ this.loading = false; programs.forEach((p)=>{ p.canRecording = new Date(p.end) < new Date(); }); this.programs = programs; }); } /** * 録音実行 */ private onClickRecording = (program_id) =>{ this.appService.recording(program_id).then((result) =>{ if(result.result){ window.open('./api/library/' + program_id); } else if(result.message){ alert(result.message); } }); }; }
eList.push(tmp.getFullYear() + '-' + ('00' + (tmp.getMonth() + 1)).slice(-2) + '-' + ('00' + tmp.getDate()).slice(-2)); } let today =
conditional_block
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: `
</select> </div> </form> <p *ngIf="loading">読み込み中です</p> <table class="table" *ngIf="!loading"> <tr *ngFor="let program of programs"> <th style="width:80px">{{program.start|date:'HH:mm'}} <td>{{program.title}}</td> <td class="text-right"> <button type="button" class="btn btn-default" (click)="onClickRecording(program.id)" *ngIf="program.canRecording"> <span class="glyphicon glyphicon-play" aria-hidden="true"></span> </button> </td> </tr> </table> ` }) export class ProgramListComponent implements OnInit{ @Input() public stationId:string; @Input() public onPlay:(url:string)=>void; private programs:IProgram[] = []; private date:string; private dateList:string[] = []; private loading:boolean = false; constructor(private appService:AppService){ } ngOnInit(){ let start = new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tmp.setDate(tmp.getDate() + 1 )){ this.dateList.push(tmp.getFullYear() + '-' + ('00' + (tmp.getMonth() + 1)).slice(-2) + '-' + ('00' + tmp.getDate()).slice(-2)); } let today = new Date(); this.date = today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) this.onChangeDate(); } private onChangeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((programs:IProgram[])=>{ this.loading = false; programs.forEach((p)=>{ p.canRecording = new Date(p.end) < new Date(); }); this.programs = programs; }); } /** * 録音実行 */ private onClickRecording = (program_id) =>{ this.appService.recording(program_id).then((result) =>{ if(result.result){ window.open('./api/library/' + program_id); } else if(result.message){ alert(result.message); } }); }; }
<form> <div class="form-group"> <label for="pass">日付</label> <select name="date" [(ngModel)]="date" (change)="onChangeDate()"> <option *ngFor="let date of dateList" (value)="date">{{date}}</option>
random_line_split
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <select name="date" [(ngModel)]="date" (change)="onChangeDate()"> <option *ngFor="let date of dateList" (value)="date">{{date}}</option> </select> </div> </form> <p *ngIf="loading">読み込み中です</p> <table class="table" *ngIf="!loading"> <tr *ngFor="let program of programs"> <th style="width:80px">{{program.start|date:'HH:mm'}} <td>{{program.title}}</td> <td class="text-right"> <button type="button" class="btn btn-default" (click)="onClickRecording(program.id)" *ngIf="program.canRecording"> <span class="glyphicon glyphicon-play" aria-hidden="true"></span> </button> </td> </tr> </table> ` }) export class ProgramListComponent implements OnInit{ @Input() public stationId:string; @Input() public onPlay:(url:string)=>void; private programs:IProgram[] = []; private date:string; private dateList:string[] = []; private loading:boolean = false; constructor(private appService:AppService){ } ngOnInit(){
t = new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tmp.setDate(tmp.getDate() + 1 )){ this.dateList.push(tmp.getFullYear() + '-' + ('00' + (tmp.getMonth() + 1)).slice(-2) + '-' + ('00' + tmp.getDate()).slice(-2)); } let today = new Date(); this.date = today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) this.onChangeDate(); } private onChangeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((programs:IProgram[])=>{ this.loading = false; programs.forEach((p)=>{ p.canRecording = new Date(p.end) < new Date(); }); this.programs = programs; }); } /** * 録音実行 */ private onClickRecording = (program_id) =>{ this.appService.recording(program_id).then((result) =>{ if(result.result){ window.open('./api/library/' + program_id); } else if(result.message){ alert(result.message); } }); }; }
let star
identifier_name
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <select name="date" [(ngModel)]="date" (change)="onChangeDate()"> <option *ngFor="let date of dateList" (value)="date">{{date}}</option> </select> </div> </form> <p *ngIf="loading">読み込み中です</p> <table class="table" *ngIf="!loading"> <tr *ngFor="let program of programs"> <th style="width:80px">{{program.start|date:'HH:mm'}} <td>{{program.title}}</td> <td class="text-right"> <button type="button" class="btn btn-default" (click)="onClickRecording(program.id)" *ngIf="program.canRecording"> <span class="glyphicon glyphicon-play" aria-hidden="true"></span> </button> </td> </tr> </table> ` }) export class ProgramListComponent implements OnInit{ @Input() public stationId:string; @Input() public onPlay:(url:string)=>void; private programs:IProgram[] = []; private date:string; private dateList:string[] = []; private loading:boolean = false; constructor(private appService:AppService){ } ngOnInit(){ let start
angeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((programs:IProgram[])=>{ this.loading = false; programs.forEach((p)=>{ p.canRecording = new Date(p.end) < new Date(); }); this.programs = programs; }); } /** * 録音実行 */ private onClickRecording = (program_id) =>{ this.appService.recording(program_id).then((result) =>{ if(result.result){ window.open('./api/library/' + program_id); } else if(result.message){ alert(result.message); } }); }; }
= new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tmp.setDate(tmp.getDate() + 1 )){ this.dateList.push(tmp.getFullYear() + '-' + ('00' + (tmp.getMonth() + 1)).slice(-2) + '-' + ('00' + tmp.getDate()).slice(-2)); } let today = new Date(); this.date = today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) this.onChangeDate(); } private onCh
identifier_body
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0,
1 << 3, 1 << 29, 1 << 23, 1 << 17, 1 << 10, 1 << 4, 1 << 30, 1 << 24, 1 << 11, 1 << 05, 1 << 31, 1 << 25]; pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7] | S[8] | S[9] | S[10] | S[11]; pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26] | S[27] | S[28] | S[29] | S[30] | S[31]; pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3]; pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7]; pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27]; pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31]; pub const CAN_UPLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_8); pub const CAN_UPRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_8); pub const CAN_DOWNLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_1); pub const CAN_DOWNRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_1); #[derive(Clone, PartialEq, Show, Copy)] pub struct Move { pub src: u16, pub dst: u16, pub jump: bool, __dummy: () } #[derive(Clone, PartialEq, Show, Copy)] pub enum Direction{ UpLeft, UpRight, DownLeft, DownRight } impl Move { pub fn new(src: u16, dst: u16, jump: bool) -> Move { assert!(src < 32); assert!(dst < 32); Move { src: src, dst: dst, jump: jump, __dummy: () } } pub fn calc_direction(&self) -> Option<Direction> { let (src, dst) = (S[self.src as usize], S[self.dst as usize]); if src.up_left() ^ dst == 0 { Some(Direction::UpLeft) } else if src.up_right() ^ dst == 0 { Some(Direction::UpRight) } else if src.down_right() ^ dst == 0 { Some(Direction::DownRight) } else if src.down_left() ^ dst == 0 { Some(Direction::DownLeft) } else { None } } } #[derive(Clone, Copy)] pub enum Cell { Empty = 0, Pw, Pb, Kw, Kb } pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ]; #[derive(Show, Clone, Copy, PartialEq)] pub enum MoveCode { Success, VoidPiece, IllegalMove, WrongPiece, Quit, InputFail } impl BitMove for Bitboard { #[inline] fn up_left(&self) -> Bitboard { self.rotate_left(7) } #[inline] fn up_right(&self) -> Bitboard { self.rotate_left(1) } #[inline] fn down_left(&self) -> Bitboard { self.rotate_right(1) } #[inline] fn down_right(&self) -> Bitboard { self.rotate_right(7) } #[inline] fn is(&self) -> bool { *self != 0 } } // Maps from Bitboard indicating a position to the number // of that position itself pub fn bbumap(b: Bitboard) -> Bitboard { S.iter().position(|&x| x == b).unwrap() as u32 } #[inline] pub fn high_bit(mut board: Bitboard) -> Bitboard { board |= board >> 1; board |= board >> 2; board |= board >> 4; board |= board >> 8; board |= board >> 16; board - (board >> 1) } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "assertion failed")] fn test_move_validation() { let _ = Move::new(0, 100, false); } #[test] fn test_move_validation2() { let _ = Move::new(1,2,false); let _ = Move::new(31,0,false); } #[test] fn test_direction_calculation() { let m = Move::new(9, 12, true); assert_eq!(m.calc_direction(), Some(Direction::UpLeft)); let m = Move::new(9, 13, false); assert_eq!(m.calc_direction(), Some(Direction::UpRight)); let m = Move::new(21, 17, false); assert_eq!(m.calc_direction(), Some(Direction::DownLeft)); let m = Move::new(21, 18, false); assert_eq!(m.calc_direction(), Some(Direction::DownRight)); let m = Move::new(21, 12, false); assert_eq!(m.calc_direction(), None); } }
1 << 19, 1 << 13, 1 << 7, 1 << 1, 1 << 26, 1 << 20, 1 << 14, 1 << 8, 1 << 27, 1 << 21, 1 << 15, 1 << 9, 1 << 2, 1 << 28, 1 << 22, 1 << 16,
random_line_split
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, 1 << 19, 1 << 13, 1 << 7, 1 << 1, 1 << 26, 1 << 20, 1 << 14, 1 << 8, 1 << 27, 1 << 21, 1 << 15, 1 << 9, 1 << 2, 1 << 28, 1 << 22, 1 << 16, 1 << 3, 1 << 29, 1 << 23, 1 << 17, 1 << 10, 1 << 4, 1 << 30, 1 << 24, 1 << 11, 1 << 05, 1 << 31, 1 << 25]; pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7] | S[8] | S[9] | S[10] | S[11]; pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26] | S[27] | S[28] | S[29] | S[30] | S[31]; pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3]; pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7]; pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27]; pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31]; pub const CAN_UPLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_8); pub const CAN_UPRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_8); pub const CAN_DOWNLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_1); pub const CAN_DOWNRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_1); #[derive(Clone, PartialEq, Show, Copy)] pub struct Move { pub src: u16, pub dst: u16, pub jump: bool, __dummy: () } #[derive(Clone, PartialEq, Show, Copy)] pub enum Direction{ UpLeft, UpRight, DownLeft, DownRight } impl Move { pub fn new(src: u16, dst: u16, jump: bool) -> Move { assert!(src < 32); assert!(dst < 32); Move { src: src, dst: dst, jump: jump, __dummy: () } } pub fn calc_direction(&self) -> Option<Direction> { let (src, dst) = (S[self.src as usize], S[self.dst as usize]); if src.up_left() ^ dst == 0 { Some(Direction::UpLeft) } else if src.up_right() ^ dst == 0 { Some(Direction::UpRight) } else if src.down_right() ^ dst == 0 { Some(Direction::DownRight) } else if src.down_left() ^ dst == 0 { Some(Direction::DownLeft) } else { None } } } #[derive(Clone, Copy)] pub enum Cell { Empty = 0, Pw, Pb, Kw, Kb } pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ]; #[derive(Show, Clone, Copy, PartialEq)] pub enum MoveCode { Success, VoidPiece, IllegalMove, WrongPiece, Quit, InputFail } impl BitMove for Bitboard { #[inline] fn up_left(&self) -> Bitboard { self.rotate_left(7) } #[inline] fn up_right(&self) -> Bitboard { self.rotate_left(1) } #[inline] fn down_left(&self) -> Bitboard { self.rotate_right(1) } #[inline] fn down_right(&self) -> Bitboard { self.rotate_right(7) } #[inline] fn is(&self) -> bool
} // Maps from Bitboard indicating a position to the number // of that position itself pub fn bbumap(b: Bitboard) -> Bitboard { S.iter().position(|&x| x == b).unwrap() as u32 } #[inline] pub fn high_bit(mut board: Bitboard) -> Bitboard { board |= board >> 1; board |= board >> 2; board |= board >> 4; board |= board >> 8; board |= board >> 16; board - (board >> 1) } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "assertion failed")] fn test_move_validation() { let _ = Move::new(0, 100, false); } #[test] fn test_move_validation2() { let _ = Move::new(1,2,false); let _ = Move::new(31,0,false); } #[test] fn test_direction_calculation() { let m = Move::new(9, 12, true); assert_eq!(m.calc_direction(), Some(Direction::UpLeft)); let m = Move::new(9, 13, false); assert_eq!(m.calc_direction(), Some(Direction::UpRight)); let m = Move::new(21, 17, false); assert_eq!(m.calc_direction(), Some(Direction::DownLeft)); let m = Move::new(21, 18, false); assert_eq!(m.calc_direction(), Some(Direction::DownRight)); let m = Move::new(21, 12, false); assert_eq!(m.calc_direction(), None); } }
{ *self != 0 }
identifier_body
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, 1 << 19, 1 << 13, 1 << 7, 1 << 1, 1 << 26, 1 << 20, 1 << 14, 1 << 8, 1 << 27, 1 << 21, 1 << 15, 1 << 9, 1 << 2, 1 << 28, 1 << 22, 1 << 16, 1 << 3, 1 << 29, 1 << 23, 1 << 17, 1 << 10, 1 << 4, 1 << 30, 1 << 24, 1 << 11, 1 << 05, 1 << 31, 1 << 25]; pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7] | S[8] | S[9] | S[10] | S[11]; pub const WP_INIT: Bitboard = S[20] | S[21] | S[22] | S[23] | S[24] | S[25] | S[26] | S[27] | S[28] | S[29] | S[30] | S[31]; pub const ROW_1: Bitboard = S[0] | S[1] | S[2] | S[3]; pub const ROW_2: Bitboard = S[4] | S[5] | S[6] | S[7]; pub const ROW_7: Bitboard = S[24] | S[25] | S[26] | S[27]; pub const ROW_8: Bitboard = S[28] | S[29] | S[30] | S[31]; pub const CAN_UPLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_8); pub const CAN_UPRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_8); pub const CAN_DOWNLEFT: Bitboard = !(S[0] | S[8] | S[16] | S[24] | ROW_1); pub const CAN_DOWNRIGHT: Bitboard = !(S[7] | S[15] | S[23] | S[31] | ROW_1); #[derive(Clone, PartialEq, Show, Copy)] pub struct Move { pub src: u16, pub dst: u16, pub jump: bool, __dummy: () } #[derive(Clone, PartialEq, Show, Copy)] pub enum Direction{ UpLeft, UpRight, DownLeft, DownRight } impl Move { pub fn
(src: u16, dst: u16, jump: bool) -> Move { assert!(src < 32); assert!(dst < 32); Move { src: src, dst: dst, jump: jump, __dummy: () } } pub fn calc_direction(&self) -> Option<Direction> { let (src, dst) = (S[self.src as usize], S[self.dst as usize]); if src.up_left() ^ dst == 0 { Some(Direction::UpLeft) } else if src.up_right() ^ dst == 0 { Some(Direction::UpRight) } else if src.down_right() ^ dst == 0 { Some(Direction::DownRight) } else if src.down_left() ^ dst == 0 { Some(Direction::DownLeft) } else { None } } } #[derive(Clone, Copy)] pub enum Cell { Empty = 0, Pw, Pb, Kw, Kb } pub const CELLTABLE: [&'static str; 5] = [ "---", "WHI", "BLK", "KWH", "KBK" ]; #[derive(Show, Clone, Copy, PartialEq)] pub enum MoveCode { Success, VoidPiece, IllegalMove, WrongPiece, Quit, InputFail } impl BitMove for Bitboard { #[inline] fn up_left(&self) -> Bitboard { self.rotate_left(7) } #[inline] fn up_right(&self) -> Bitboard { self.rotate_left(1) } #[inline] fn down_left(&self) -> Bitboard { self.rotate_right(1) } #[inline] fn down_right(&self) -> Bitboard { self.rotate_right(7) } #[inline] fn is(&self) -> bool { *self != 0 } } // Maps from Bitboard indicating a position to the number // of that position itself pub fn bbumap(b: Bitboard) -> Bitboard { S.iter().position(|&x| x == b).unwrap() as u32 } #[inline] pub fn high_bit(mut board: Bitboard) -> Bitboard { board |= board >> 1; board |= board >> 2; board |= board >> 4; board |= board >> 8; board |= board >> 16; board - (board >> 1) } #[cfg(test)] mod test { use super::*; #[test] #[should_panic(expected = "assertion failed")] fn test_move_validation() { let _ = Move::new(0, 100, false); } #[test] fn test_move_validation2() { let _ = Move::new(1,2,false); let _ = Move::new(31,0,false); } #[test] fn test_direction_calculation() { let m = Move::new(9, 12, true); assert_eq!(m.calc_direction(), Some(Direction::UpLeft)); let m = Move::new(9, 13, false); assert_eq!(m.calc_direction(), Some(Direction::UpRight)); let m = Move::new(21, 17, false); assert_eq!(m.calc_direction(), Some(Direction::DownLeft)); let m = Move::new(21, 18, false); assert_eq!(m.calc_direction(), Some(Direction::DownRight)); let m = Move::new(21, 12, false); assert_eq!(m.calc_direction(), None); } }
new
identifier_name
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: content = content.encode("unicode-escape") except LookupError: content = content.encode("string-escape") return Markup(content) def html_attrs(*args, **kwargs): attr = HtmlAttr() attr.update(*args, **kwargs) return six.text_type(attr) def add_css_class(original_class, *css_classes): css = CssClassList() css.append(original_class) css.append(css_classes) return six.text_type(css) class CssClassList(object): def __init__(self): self.classes = [] def __iter__(self): return iter(self.classes) def __len__(self): return len(self.classes) def copy(self): value = CssClassList() value.classes.extend(self.classes) return value def append(self, value): if isinstance(value, six.text_type): value = re.sub(r'\s+', ' ', value.strip()) if len(value) == 1: value = value[0] if isinstance(value, (tuple, list)): for val in value: self.append(val) else: if value not in self.classes: self.classes.append(value) def __contains__(self, item): return item in self.classes def __str__(self): return " ".join(str(c) for c in self.classes if c) class CssStyle(dict): def render(self): return ";".join("%s:%s" % (key.replace("_", "-"), value) for (key, value) in six.iteritems(self)) def __str__(self): return self.render() def copy(self): return CssStyle(super(CssStyle, self).copy()) def _normalize(key): if key.endswith("_"): key = key[:-1] key = key.replace("__", ":").replace("_", "-") return key class HtmlAttr(object): def __init__(self): self.attrs = {} self.styles = CssStyle() self.classes = CssClassList() def copy(self): attr = HtmlAttr() attr.attrs = self.attrs.copy() attr.styles = self.styles.copy() attr.classes = self.classes.copy() return attr def dict(self): return dict(self) def __setitem__(self, key, value): self.set(key, value) def __getitem__(self, item): return dict(self)[item] def __len__(self): return len(dict(self)) def get(self, key): return dict(self).get(key) def set(self, key, value): key = _normalize(key) if key in {"class"}: self.classes.append(value) elif key == "style": self.styles.update(value) else: self.attrs[key] = value def update(self, *args, **attrs): values = {} values.update(*args, **attrs) for k, v in values.items(): self.set(k, v) def __iter__(self): for k, v in six.iteritems(self.attrs): yield k, v if self.classes: yield "class", six.text_type(self.classes) if self.styles: yield "style", self.styles.render() def render(self): pairs = [] for key, value in self: if value is None or value is False: continue if value is True: pairs.append(key) else: if not isinstance(value, six.string_types): value = html_json(value) pairs.append("%s='%s'" % (key, str(value))) return " ".join(pairs) def __str__(self): return self.render() class Element(object): def __init__(self, tag): self.tag = tag self.attrib = HtmlAttr() self.children = [] def __call__(self, **kwargs): el = self.copy() el.attrib.update(kwargs) return el def __getitem__(self, item):
def copy(self): el = self.__class__(self.tag) el.attrib = self.attrib.copy() el.children = self.children[:] return el def mutate(self, tag): el = tag.copy() el.attrib.update(self.attrib.copy()) el.children = self.children[:] return el def append(self, child): if child is None: return if isinstance(child, (list, tuple)): for c in child: self.append(c) else: self.children.append(child) def convert_to_text(self, el, *args, **kwargs): return el.render(*args, **kwargs) if hasattr(el, 'render') else force_text(el) def render_children(self, *args, **kwargs): return "".join(filter(None, (self.convert_to_text(c, *args, **kwargs)for c in self.children))) def render(self, ctx=None): if self.attrib.get('if') is False: return None attrs = self.attrib content = self.render_children(ctx) tag = _normalize(self.tag) return u"<{tag} {attrs}>{content}</{tag}>".format(**locals()) def __str__(self): return self.render() def __html__(self): return self.render() class Empty(Element): def render(self, *args, **kwargs): return self.render_children(*args, **kwargs) empty = Empty("none") for name in "html body link meta div span form section article aside main ul li ol dl dd dt p a strong "\ "i fieldset legend b em input select button label nav textarea " \ "table tbody tfoot thead tr td th figure caption img".split(" "): __all__.append(name) globals()[name] = Element(name) if __name__ == '__main__': print(input(type="radio", checked=False).render())
el = self.copy() if not isinstance(item, (list, tuple)): item = [item] for c in item: el.append(c) return el
identifier_body
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: content = content.encode("unicode-escape") except LookupError: content = content.encode("string-escape") return Markup(content) def html_attrs(*args, **kwargs): attr = HtmlAttr() attr.update(*args, **kwargs) return six.text_type(attr) def add_css_class(original_class, *css_classes): css = CssClassList() css.append(original_class) css.append(css_classes) return six.text_type(css) class CssClassList(object): def __init__(self): self.classes = [] def __iter__(self): return iter(self.classes) def __len__(self): return len(self.classes) def copy(self): value = CssClassList() value.classes.extend(self.classes) return value def append(self, value): if isinstance(value, six.text_type): value = re.sub(r'\s+', ' ', value.strip()) if len(value) == 1: value = value[0] if isinstance(value, (tuple, list)): for val in value: self.append(val) else: if value not in self.classes: self.classes.append(value) def __contains__(self, item): return item in self.classes def __str__(self):
def render(self): return ";".join("%s:%s" % (key.replace("_", "-"), value) for (key, value) in six.iteritems(self)) def __str__(self): return self.render() def copy(self): return CssStyle(super(CssStyle, self).copy()) def _normalize(key): if key.endswith("_"): key = key[:-1] key = key.replace("__", ":").replace("_", "-") return key class HtmlAttr(object): def __init__(self): self.attrs = {} self.styles = CssStyle() self.classes = CssClassList() def copy(self): attr = HtmlAttr() attr.attrs = self.attrs.copy() attr.styles = self.styles.copy() attr.classes = self.classes.copy() return attr def dict(self): return dict(self) def __setitem__(self, key, value): self.set(key, value) def __getitem__(self, item): return dict(self)[item] def __len__(self): return len(dict(self)) def get(self, key): return dict(self).get(key) def set(self, key, value): key = _normalize(key) if key in {"class"}: self.classes.append(value) elif key == "style": self.styles.update(value) else: self.attrs[key] = value def update(self, *args, **attrs): values = {} values.update(*args, **attrs) for k, v in values.items(): self.set(k, v) def __iter__(self): for k, v in six.iteritems(self.attrs): yield k, v if self.classes: yield "class", six.text_type(self.classes) if self.styles: yield "style", self.styles.render() def render(self): pairs = [] for key, value in self: if value is None or value is False: continue if value is True: pairs.append(key) else: if not isinstance(value, six.string_types): value = html_json(value) pairs.append("%s='%s'" % (key, str(value))) return " ".join(pairs) def __str__(self): return self.render() class Element(object): def __init__(self, tag): self.tag = tag self.attrib = HtmlAttr() self.children = [] def __call__(self, **kwargs): el = self.copy() el.attrib.update(kwargs) return el def __getitem__(self, item): el = self.copy() if not isinstance(item, (list, tuple)): item = [item] for c in item: el.append(c) return el def copy(self): el = self.__class__(self.tag) el.attrib = self.attrib.copy() el.children = self.children[:] return el def mutate(self, tag): el = tag.copy() el.attrib.update(self.attrib.copy()) el.children = self.children[:] return el def append(self, child): if child is None: return if isinstance(child, (list, tuple)): for c in child: self.append(c) else: self.children.append(child) def convert_to_text(self, el, *args, **kwargs): return el.render(*args, **kwargs) if hasattr(el, 'render') else force_text(el) def render_children(self, *args, **kwargs): return "".join(filter(None, (self.convert_to_text(c, *args, **kwargs)for c in self.children))) def render(self, ctx=None): if self.attrib.get('if') is False: return None attrs = self.attrib content = self.render_children(ctx) tag = _normalize(self.tag) return u"<{tag} {attrs}>{content}</{tag}>".format(**locals()) def __str__(self): return self.render() def __html__(self): return self.render() class Empty(Element): def render(self, *args, **kwargs): return self.render_children(*args, **kwargs) empty = Empty("none") for name in "html body link meta div span form section article aside main ul li ol dl dd dt p a strong "\ "i fieldset legend b em input select button label nav textarea " \ "table tbody tfoot thead tr td th figure caption img".split(" "): __all__.append(name) globals()[name] = Element(name) if __name__ == '__main__': print(input(type="radio", checked=False).render())
return " ".join(str(c) for c in self.classes if c) class CssStyle(dict):
random_line_split
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: content = content.encode("unicode-escape") except LookupError: content = content.encode("string-escape") return Markup(content) def html_attrs(*args, **kwargs): attr = HtmlAttr() attr.update(*args, **kwargs) return six.text_type(attr) def add_css_class(original_class, *css_classes): css = CssClassList() css.append(original_class) css.append(css_classes) return six.text_type(css) class CssClassList(object): def __init__(self): self.classes = [] def __iter__(self): return iter(self.classes) def __len__(self): return len(self.classes) def
(self): value = CssClassList() value.classes.extend(self.classes) return value def append(self, value): if isinstance(value, six.text_type): value = re.sub(r'\s+', ' ', value.strip()) if len(value) == 1: value = value[0] if isinstance(value, (tuple, list)): for val in value: self.append(val) else: if value not in self.classes: self.classes.append(value) def __contains__(self, item): return item in self.classes def __str__(self): return " ".join(str(c) for c in self.classes if c) class CssStyle(dict): def render(self): return ";".join("%s:%s" % (key.replace("_", "-"), value) for (key, value) in six.iteritems(self)) def __str__(self): return self.render() def copy(self): return CssStyle(super(CssStyle, self).copy()) def _normalize(key): if key.endswith("_"): key = key[:-1] key = key.replace("__", ":").replace("_", "-") return key class HtmlAttr(object): def __init__(self): self.attrs = {} self.styles = CssStyle() self.classes = CssClassList() def copy(self): attr = HtmlAttr() attr.attrs = self.attrs.copy() attr.styles = self.styles.copy() attr.classes = self.classes.copy() return attr def dict(self): return dict(self) def __setitem__(self, key, value): self.set(key, value) def __getitem__(self, item): return dict(self)[item] def __len__(self): return len(dict(self)) def get(self, key): return dict(self).get(key) def set(self, key, value): key = _normalize(key) if key in {"class"}: self.classes.append(value) elif key == "style": self.styles.update(value) else: self.attrs[key] = value def update(self, *args, **attrs): values = {} values.update(*args, **attrs) for k, v in values.items(): self.set(k, v) def __iter__(self): for k, v in six.iteritems(self.attrs): yield k, v if self.classes: yield "class", six.text_type(self.classes) if self.styles: yield "style", self.styles.render() def render(self): pairs = [] for key, value in self: if value is None or value is False: continue if value is True: pairs.append(key) else: if not isinstance(value, six.string_types): value = html_json(value) pairs.append("%s='%s'" % (key, str(value))) return " ".join(pairs) def __str__(self): return self.render() class Element(object): def __init__(self, tag): self.tag = tag self.attrib = HtmlAttr() self.children = [] def __call__(self, **kwargs): el = self.copy() el.attrib.update(kwargs) return el def __getitem__(self, item): el = self.copy() if not isinstance(item, (list, tuple)): item = [item] for c in item: el.append(c) return el def copy(self): el = self.__class__(self.tag) el.attrib = self.attrib.copy() el.children = self.children[:] return el def mutate(self, tag): el = tag.copy() el.attrib.update(self.attrib.copy()) el.children = self.children[:] return el def append(self, child): if child is None: return if isinstance(child, (list, tuple)): for c in child: self.append(c) else: self.children.append(child) def convert_to_text(self, el, *args, **kwargs): return el.render(*args, **kwargs) if hasattr(el, 'render') else force_text(el) def render_children(self, *args, **kwargs): return "".join(filter(None, (self.convert_to_text(c, *args, **kwargs)for c in self.children))) def render(self, ctx=None): if self.attrib.get('if') is False: return None attrs = self.attrib content = self.render_children(ctx) tag = _normalize(self.tag) return u"<{tag} {attrs}>{content}</{tag}>".format(**locals()) def __str__(self): return self.render() def __html__(self): return self.render() class Empty(Element): def render(self, *args, **kwargs): return self.render_children(*args, **kwargs) empty = Empty("none") for name in "html body link meta div span form section article aside main ul li ol dl dd dt p a strong "\ "i fieldset legend b em input select button label nav textarea " \ "table tbody tfoot thead tr td th figure caption img".split(" "): __all__.append(name) globals()[name] = Element(name) if __name__ == '__main__': print(input(type="radio", checked=False).render())
copy
identifier_name
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: content = content.encode("unicode-escape") except LookupError: content = content.encode("string-escape") return Markup(content) def html_attrs(*args, **kwargs): attr = HtmlAttr() attr.update(*args, **kwargs) return six.text_type(attr) def add_css_class(original_class, *css_classes): css = CssClassList() css.append(original_class) css.append(css_classes) return six.text_type(css) class CssClassList(object): def __init__(self): self.classes = [] def __iter__(self): return iter(self.classes) def __len__(self): return len(self.classes) def copy(self): value = CssClassList() value.classes.extend(self.classes) return value def append(self, value): if isinstance(value, six.text_type): value = re.sub(r'\s+', ' ', value.strip()) if len(value) == 1: value = value[0] if isinstance(value, (tuple, list)): for val in value: self.append(val) else: if value not in self.classes: self.classes.append(value) def __contains__(self, item): return item in self.classes def __str__(self): return " ".join(str(c) for c in self.classes if c) class CssStyle(dict): def render(self): return ";".join("%s:%s" % (key.replace("_", "-"), value) for (key, value) in six.iteritems(self)) def __str__(self): return self.render() def copy(self): return CssStyle(super(CssStyle, self).copy()) def _normalize(key): if key.endswith("_"): key = key[:-1] key = key.replace("__", ":").replace("_", "-") return key class HtmlAttr(object): def __init__(self): self.attrs = {} self.styles = CssStyle() self.classes = CssClassList() def copy(self): attr = HtmlAttr() attr.attrs = self.attrs.copy() attr.styles = self.styles.copy() attr.classes = self.classes.copy() return attr def dict(self): return dict(self) def __setitem__(self, key, value): self.set(key, value) def __getitem__(self, item): return dict(self)[item] def __len__(self): return len(dict(self)) def get(self, key): return dict(self).get(key) def set(self, key, value): key = _normalize(key) if key in {"class"}: self.classes.append(value) elif key == "style":
else: self.attrs[key] = value def update(self, *args, **attrs): values = {} values.update(*args, **attrs) for k, v in values.items(): self.set(k, v) def __iter__(self): for k, v in six.iteritems(self.attrs): yield k, v if self.classes: yield "class", six.text_type(self.classes) if self.styles: yield "style", self.styles.render() def render(self): pairs = [] for key, value in self: if value is None or value is False: continue if value is True: pairs.append(key) else: if not isinstance(value, six.string_types): value = html_json(value) pairs.append("%s='%s'" % (key, str(value))) return " ".join(pairs) def __str__(self): return self.render() class Element(object): def __init__(self, tag): self.tag = tag self.attrib = HtmlAttr() self.children = [] def __call__(self, **kwargs): el = self.copy() el.attrib.update(kwargs) return el def __getitem__(self, item): el = self.copy() if not isinstance(item, (list, tuple)): item = [item] for c in item: el.append(c) return el def copy(self): el = self.__class__(self.tag) el.attrib = self.attrib.copy() el.children = self.children[:] return el def mutate(self, tag): el = tag.copy() el.attrib.update(self.attrib.copy()) el.children = self.children[:] return el def append(self, child): if child is None: return if isinstance(child, (list, tuple)): for c in child: self.append(c) else: self.children.append(child) def convert_to_text(self, el, *args, **kwargs): return el.render(*args, **kwargs) if hasattr(el, 'render') else force_text(el) def render_children(self, *args, **kwargs): return "".join(filter(None, (self.convert_to_text(c, *args, **kwargs)for c in self.children))) def render(self, ctx=None): if self.attrib.get('if') is False: return None attrs = self.attrib content = self.render_children(ctx) tag = _normalize(self.tag) return u"<{tag} {attrs}>{content}</{tag}>".format(**locals()) def __str__(self): return self.render() def __html__(self): return self.render() class Empty(Element): def render(self, *args, **kwargs): return self.render_children(*args, **kwargs) empty = Empty("none") for name in "html body link meta div span form section article aside main ul li ol dl dd dt p a strong "\ "i fieldset legend b em input select button label nav textarea " \ "table tbody tfoot thead tr td th figure caption img".split(" "): __all__.append(name) globals()[name] = Element(name) if __name__ == '__main__': print(input(type="radio", checked=False).render())
self.styles.update(value)
conditional_block
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import Axon from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Chassis.Pipeline import Pipeline class Source(Axon.ThreadedComponent.threadedcomponent): value = 1 sleep = 1 def
(self): while 1: self.send(str(self.value), "outbox") time.sleep(self.sleep) Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
main
identifier_name
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Chassis.Pipeline import Pipeline class Source(Axon.ThreadedComponent.threadedcomponent): value = 1 sleep = 1 def main(self): while 1: self.send(str(self.value), "outbox") time.sleep(self.sleep) Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
import time import Axon
random_line_split
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import Axon from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Chassis.Pipeline import Pipeline class Source(Axon.ThreadedComponent.threadedcomponent):
Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
value = 1 sleep = 1 def main(self): while 1: self.send(str(self.value), "outbox") time.sleep(self.sleep)
identifier_body
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import Axon from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Chassis.Pipeline import Pipeline class Source(Axon.ThreadedComponent.threadedcomponent): value = 1 sleep = 1 def main(self): while 1:
Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
self.send(str(self.value), "outbox") time.sleep(self.sleep)
conditional_block
SeqCal.js
function SeqCal()
SeqCal.prototype = Object.create(Plugin.prototype); SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.getHours(); return h % 12; }).join(','); this.draw = function(ctx) { ctx.save(); ctx.beginPath(); ctx.fillStyle = this.fillStyle; ctx.rect(this.x, this.y, this.w, this.h); ctx.closePath(); ctx.stroke(); var colorCodes = ['#fff', '#f7b9b9', '#f95959', '#f70404']; var lvl = this.lvl >= colorCodes.length ? colorCodes.length - 1 : this.evts.length; ctx.fillStyle = colorCodes[lvl]; ctx.fill(); //draw lablel ctx.beginPath(); ctx.font = "12px Arial"; ctx.fillStyle = '#000'; ctx.textBaseline = "middle"; Drawable.prototype.drawLabel.call(this, ctx, this.label, "center"); ctx.restore(); } } Day.prototype = Object.create(Drawable.prototype); Day.prototype.constructor = Day;
{ Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) : inpSize; if (!this.data || !(this.data instanceof Array) || (0 == this.data.length)) { return false; } this.clear(); layout.clear(); var days = this.data.reduce(function(r, a) { var dt = new Date(a.date), date = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); r[date.getTime()] = r[date.getTime()] || []; r[date.getTime()].push(a); return r; }, Object.create(null)); for (var i in days) { layout.add(new Day(days[i])); } layout.table(inpSize); this.add(layout); } this.view = function() { this.addSettings([{ 'title': 'SeqCal Cols', 'type': 'number', 'value': inpSize, 'input.name': 'inpSize', 'input.group': 'input-group', 'input.class': 'form-control' }]); this.draw(); } this.onZoom = function(zoom) { if (this.isView()) { layout.margin.y += zoom * 100; this.draw(); } } }
identifier_body
SeqCal.js
function SeqCal() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) : inpSize; if (!this.data || !(this.data instanceof Array) || (0 == this.data.length))
this.clear(); layout.clear(); var days = this.data.reduce(function(r, a) { var dt = new Date(a.date), date = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); r[date.getTime()] = r[date.getTime()] || []; r[date.getTime()].push(a); return r; }, Object.create(null)); for (var i in days) { layout.add(new Day(days[i])); } layout.table(inpSize); this.add(layout); } this.view = function() { this.addSettings([{ 'title': 'SeqCal Cols', 'type': 'number', 'value': inpSize, 'input.name': 'inpSize', 'input.group': 'input-group', 'input.class': 'form-control' }]); this.draw(); } this.onZoom = function(zoom) { if (this.isView()) { layout.margin.y += zoom * 100; this.draw(); } } } SeqCal.prototype = Object.create(Plugin.prototype); SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.getHours(); return h % 12; }).join(','); this.draw = function(ctx) { ctx.save(); ctx.beginPath(); ctx.fillStyle = this.fillStyle; ctx.rect(this.x, this.y, this.w, this.h); ctx.closePath(); ctx.stroke(); var colorCodes = ['#fff', '#f7b9b9', '#f95959', '#f70404']; var lvl = this.lvl >= colorCodes.length ? colorCodes.length - 1 : this.evts.length; ctx.fillStyle = colorCodes[lvl]; ctx.fill(); //draw lablel ctx.beginPath(); ctx.font = "12px Arial"; ctx.fillStyle = '#000'; ctx.textBaseline = "middle"; Drawable.prototype.drawLabel.call(this, ctx, this.label, "center"); ctx.restore(); } } Day.prototype = Object.create(Drawable.prototype); Day.prototype.constructor = Day;
{ return false; }
conditional_block
SeqCal.js
function
() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) : inpSize; if (!this.data || !(this.data instanceof Array) || (0 == this.data.length)) { return false; } this.clear(); layout.clear(); var days = this.data.reduce(function(r, a) { var dt = new Date(a.date), date = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); r[date.getTime()] = r[date.getTime()] || []; r[date.getTime()].push(a); return r; }, Object.create(null)); for (var i in days) { layout.add(new Day(days[i])); } layout.table(inpSize); this.add(layout); } this.view = function() { this.addSettings([{ 'title': 'SeqCal Cols', 'type': 'number', 'value': inpSize, 'input.name': 'inpSize', 'input.group': 'input-group', 'input.class': 'form-control' }]); this.draw(); } this.onZoom = function(zoom) { if (this.isView()) { layout.margin.y += zoom * 100; this.draw(); } } } SeqCal.prototype = Object.create(Plugin.prototype); SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.getHours(); return h % 12; }).join(','); this.draw = function(ctx) { ctx.save(); ctx.beginPath(); ctx.fillStyle = this.fillStyle; ctx.rect(this.x, this.y, this.w, this.h); ctx.closePath(); ctx.stroke(); var colorCodes = ['#fff', '#f7b9b9', '#f95959', '#f70404']; var lvl = this.lvl >= colorCodes.length ? colorCodes.length - 1 : this.evts.length; ctx.fillStyle = colorCodes[lvl]; ctx.fill(); //draw lablel ctx.beginPath(); ctx.font = "12px Arial"; ctx.fillStyle = '#000'; ctx.textBaseline = "middle"; Drawable.prototype.drawLabel.call(this, ctx, this.label, "center"); ctx.restore(); } } Day.prototype = Object.create(Drawable.prototype); Day.prototype.constructor = Day;
SeqCal
identifier_name
SeqCal.js
function SeqCal() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) : inpSize; if (!this.data || !(this.data instanceof Array) || (0 == this.data.length)) { return false; } this.clear(); layout.clear(); var days = this.data.reduce(function(r, a) { var dt = new Date(a.date), date = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); r[date.getTime()] = r[date.getTime()] || []; r[date.getTime()].push(a); return r; }, Object.create(null)); for (var i in days) { layout.add(new Day(days[i])); } layout.table(inpSize); this.add(layout); } this.view = function() { this.addSettings([{ 'title': 'SeqCal Cols', 'type': 'number', 'value': inpSize, 'input.name': 'inpSize', 'input.group': 'input-group', 'input.class': 'form-control' }]); this.draw(); } this.onZoom = function(zoom) { if (this.isView()) { layout.margin.y += zoom * 100; this.draw(); }
SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.getHours(); return h % 12; }).join(','); this.draw = function(ctx) { ctx.save(); ctx.beginPath(); ctx.fillStyle = this.fillStyle; ctx.rect(this.x, this.y, this.w, this.h); ctx.closePath(); ctx.stroke(); var colorCodes = ['#fff', '#f7b9b9', '#f95959', '#f70404']; var lvl = this.lvl >= colorCodes.length ? colorCodes.length - 1 : this.evts.length; ctx.fillStyle = colorCodes[lvl]; ctx.fill(); //draw lablel ctx.beginPath(); ctx.font = "12px Arial"; ctx.fillStyle = '#000'; ctx.textBaseline = "middle"; Drawable.prototype.drawLabel.call(this, ctx, this.label, "center"); ctx.restore(); } } Day.prototype = Object.create(Drawable.prototype); Day.prototype.constructor = Day;
} } SeqCal.prototype = Object.create(Plugin.prototype);
random_line_split
screenshot.py
from lib.common import helpers class Module:
def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the output as a .PNG.'), 'Background' : False, 'OutputExtension' : 'png', 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-TimedScreenshot.ps1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Ratio' : { 'Description' : "JPEG Compression ratio: 1 to 100.", 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): script = """ function Get-Screenshot { param ( [Parameter(Mandatory = $False)] [string] $Ratio ) Add-Type -Assembly System.Windows.Forms; $ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen; $ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height; $DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject); $DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size); $DrawingGraphics.Dispose(); $ms = New-Object System.IO.MemoryStream; if ($Ratio) { try { $iQual = [convert]::ToInt32($Ratio); } catch { $iQual=80; } if ($iQual -gt 100){ $iQual=100; } elseif ($iQual -lt 1){ $iQual=1; } $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters; $encoderParams.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, $iQual); $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.FormatDescription -eq \"JPEG\" } $ScreenshotObject.save($ms, $jpegCodec, $encoderParams); } else { $ScreenshotObject.save($ms, [Drawing.Imaging.ImageFormat]::Png); } $ScreenshotObject.Dispose(); [convert]::ToBase64String($ms.ToArray()); } Get-Screenshot""" if self.options['Ratio']['Value']: if self.options['Ratio']['Value']!='0': self.info['OutputExtension'] = 'jpg' else: self.options['Ratio']['Value'] = '' self.info['OutputExtension'] = 'png' else: self.info['OutputExtension'] = 'png' for option,values in self.options.iteritems(): if option.lower() != "agent": if values['Value'] and values['Value'] != '': if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else: script += " -" + str(option) + " " + str(values['Value']) return script
identifier_body
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the output as a .PNG.'), 'Background' : False, 'OutputExtension' : 'png', 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-TimedScreenshot.ps1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Ratio' : { 'Description' : "JPEG Compression ratio: 1 to 100.", 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def
(self): script = """ function Get-Screenshot { param ( [Parameter(Mandatory = $False)] [string] $Ratio ) Add-Type -Assembly System.Windows.Forms; $ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen; $ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height; $DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject); $DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size); $DrawingGraphics.Dispose(); $ms = New-Object System.IO.MemoryStream; if ($Ratio) { try { $iQual = [convert]::ToInt32($Ratio); } catch { $iQual=80; } if ($iQual -gt 100){ $iQual=100; } elseif ($iQual -lt 1){ $iQual=1; } $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters; $encoderParams.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, $iQual); $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.FormatDescription -eq \"JPEG\" } $ScreenshotObject.save($ms, $jpegCodec, $encoderParams); } else { $ScreenshotObject.save($ms, [Drawing.Imaging.ImageFormat]::Png); } $ScreenshotObject.Dispose(); [convert]::ToBase64String($ms.ToArray()); } Get-Screenshot""" if self.options['Ratio']['Value']: if self.options['Ratio']['Value']!='0': self.info['OutputExtension'] = 'jpg' else: self.options['Ratio']['Value'] = '' self.info['OutputExtension'] = 'png' else: self.info['OutputExtension'] = 'png' for option,values in self.options.iteritems(): if option.lower() != "agent": if values['Value'] and values['Value'] != '': if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else: script += " -" + str(option) + " " + str(values['Value']) return script
generate
identifier_name
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the output as a .PNG.'), 'Background' : False, 'OutputExtension' : 'png', 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-TimedScreenshot.ps1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Ratio' : { 'Description' : "JPEG Compression ratio: 1 to 100.", 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): script = """ function Get-Screenshot { param ( [Parameter(Mandatory = $False)] [string] $Ratio ) Add-Type -Assembly System.Windows.Forms; $ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen; $ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height; $DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject); $DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size); $DrawingGraphics.Dispose(); $ms = New-Object System.IO.MemoryStream; if ($Ratio) { try { $iQual = [convert]::ToInt32($Ratio); } catch { $iQual=80; } if ($iQual -gt 100){ $iQual=100; } elseif ($iQual -lt 1){ $iQual=1; } $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters; $encoderParams.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, $iQual); $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.FormatDescription -eq \"JPEG\" } $ScreenshotObject.save($ms, $jpegCodec, $encoderParams); } else { $ScreenshotObject.save($ms, [Drawing.Imaging.ImageFormat]::Png); } $ScreenshotObject.Dispose(); [convert]::ToBase64String($ms.ToArray()); } Get-Screenshot""" if self.options['Ratio']['Value']: if self.options['Ratio']['Value']!='0': self.info['OutputExtension'] = 'jpg' else: self.options['Ratio']['Value'] = '' self.info['OutputExtension'] = 'png' else: self.info['OutputExtension'] = 'png' for option,values in self.options.iteritems(): if option.lower() != "agent": if values['Value'] and values['Value'] != '': if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else:
return script
script += " -" + str(option) + " " + str(values['Value'])
conditional_block
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the output as a .PNG.'), 'Background' : False, 'OutputExtension' : 'png', 'NeedsAdmin' : False, 'OpsecSafe' : True, 'MinPSVersion' : '2', 'Comments': [ 'https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-TimedScreenshot.ps1' ] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : {
'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Ratio' : { 'Description' : "JPEG Compression ratio: 1 to 100.", 'Required' : False, 'Value' : '' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self): script = """ function Get-Screenshot { param ( [Parameter(Mandatory = $False)] [string] $Ratio ) Add-Type -Assembly System.Windows.Forms; $ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen; $ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height; $DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject); $DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size); $DrawingGraphics.Dispose(); $ms = New-Object System.IO.MemoryStream; if ($Ratio) { try { $iQual = [convert]::ToInt32($Ratio); } catch { $iQual=80; } if ($iQual -gt 100){ $iQual=100; } elseif ($iQual -lt 1){ $iQual=1; } $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters; $encoderParams.Param[0] = New-Object Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality, $iQual); $jpegCodec = [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.FormatDescription -eq \"JPEG\" } $ScreenshotObject.save($ms, $jpegCodec, $encoderParams); } else { $ScreenshotObject.save($ms, [Drawing.Imaging.ImageFormat]::Png); } $ScreenshotObject.Dispose(); [convert]::ToBase64String($ms.ToArray()); } Get-Screenshot""" if self.options['Ratio']['Value']: if self.options['Ratio']['Value']!='0': self.info['OutputExtension'] = 'jpg' else: self.options['Ratio']['Value'] = '' self.info['OutputExtension'] = 'png' else: self.info['OutputExtension'] = 'png' for option,values in self.options.iteritems(): if option.lower() != "agent": if values['Value'] and values['Value'] != '': if values['Value'].lower() == "true": # if we're just adding a switch script += " -" + str(option) else: script += " -" + str(option) + " " + str(values['Value']) return script
random_line_split
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pagesWithRedirects = ['/manage-va-debt/your-debt/']; const shouldIgnore = url => { const parsedUrl = new URL(url); return ( !url.endsWith('auth/login/callback/') && !url.includes('playbook/') && !url.includes('pittsburgh-health-care/') && !/.*opt-out-information-sharing.*/.test(url) && !pagesWithRedirects.some(redirectUrl => parsedUrl.pathname === redirectUrl) ); }; function
() { return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), ) .then(urls => { const onlyTest508Rules = [ // 404 page contains 2 search auto-suggest elements with the same element ID, // which violates WCAG 2.0 standards. This element id is referenced by // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID // of one of the elements, search won't work. '/404.html', // This is here because aXe bug flags the custom select component on this page '/find-locations/', // This is here because an aXe bug flags the autosuggest component on this page '/education/gi-bill-comparison-tool/', /* Using the Microsoft Healthbot framework, the chatbot currently violates two rules in the WCAG 2.0(A) ruleset: aria-valid-attr-value and aria-required-children. There are open Github issues with Microsoft to address these. The 508 ruleset is slightly less strict to test on chatbot for now. */ '/coronavirus-chatbot/', ]; // Whitelist of URLs to only test against the 'section508' rule set and not // the stricter 'wcag2a' rule set. For each URL added to this list, please // add a comment explaining why it cannot be tested against stricter rules. return { urls, onlyTest508Rules }; }); } module.exports = { sitemapURLs };
sitemapURLs
identifier_name
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pagesWithRedirects = ['/manage-va-debt/your-debt/']; const shouldIgnore = url => { const parsedUrl = new URL(url); return ( !url.endsWith('auth/login/callback/') && !url.includes('playbook/') && !url.includes('pittsburgh-health-care/') && !/.*opt-out-information-sharing.*/.test(url) && !pagesWithRedirects.some(redirectUrl => parsedUrl.pathname === redirectUrl) ); }; function sitemapURLs()
module.exports = { sitemapURLs };
{ return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), ) .then(urls => { const onlyTest508Rules = [ // 404 page contains 2 search auto-suggest elements with the same element ID, // which violates WCAG 2.0 standards. This element id is referenced by // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID // of one of the elements, search won't work. '/404.html', // This is here because aXe bug flags the custom select component on this page '/find-locations/', // This is here because an aXe bug flags the autosuggest component on this page '/education/gi-bill-comparison-tool/', /* Using the Microsoft Healthbot framework, the chatbot currently violates two rules in the WCAG 2.0(A) ruleset: aria-valid-attr-value and aria-required-children. There are open Github issues with Microsoft to address these. The 508 ruleset is slightly less strict to test on chatbot for now. */ '/coronavirus-chatbot/', ]; // Whitelist of URLs to only test against the 'section508' rule set and not // the stricter 'wcag2a' rule set. For each URL added to this list, please // add a comment explaining why it cannot be tested against stricter rules. return { urls, onlyTest508Rules }; }); }
identifier_body
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pagesWithRedirects = ['/manage-va-debt/your-debt/']; const shouldIgnore = url => { const parsedUrl = new URL(url); return ( !url.endsWith('auth/login/callback/') && !url.includes('playbook/') && !url.includes('pittsburgh-health-care/') && !/.*opt-out-information-sharing.*/.test(url) && !pagesWithRedirects.some(redirectUrl => parsedUrl.pathname === redirectUrl) ); }; function sitemapURLs() { return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), )
// 404 page contains 2 search auto-suggest elements with the same element ID, // which violates WCAG 2.0 standards. This element id is referenced by // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID // of one of the elements, search won't work. '/404.html', // This is here because aXe bug flags the custom select component on this page '/find-locations/', // This is here because an aXe bug flags the autosuggest component on this page '/education/gi-bill-comparison-tool/', /* Using the Microsoft Healthbot framework, the chatbot currently violates two rules in the WCAG 2.0(A) ruleset: aria-valid-attr-value and aria-required-children. There are open Github issues with Microsoft to address these. The 508 ruleset is slightly less strict to test on chatbot for now. */ '/coronavirus-chatbot/', ]; // Whitelist of URLs to only test against the 'section508' rule set and not // the stricter 'wcag2a' rule set. For each URL added to this list, please // add a comment explaining why it cannot be tested against stricter rules. return { urls, onlyTest508Rules }; }); } module.exports = { sitemapURLs };
.then(urls => { const onlyTest508Rules = [
random_line_split
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, alphanums, alphas, delimitedList, dictOf, ) from great_expectations.core.urn import ge_urn from great_expectations.core.util import convert_to_json_serializable from great_expectations.exceptions import EvaluationParameterError logger = logging.getLogger(__name__) _epsilon = 1e-12 class EvaluationParameterParser: """ This Evaluation Parameter Parser uses pyparsing to provide a basic expression language capable of evaluating parameters using values available only at run time. expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* The parser is modified from: https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py """ # map operator symbols to corresponding arithmetic operations opn = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow, } fn = { "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "abs": abs, "trunc": lambda a: int(a), "round": round, "sgn": lambda a: -1 if a < -_epsilon else 1 if a > _epsilon else 0, "now": datetime.datetime.now, "datetime": datetime.datetime, "timedelta": datetime.timedelta, } def __init__(self): self.exprStack = [] self._parser = None def push_first(self, toks): self.exprStack.append(toks[0]) def push_unary_minus(self, toks): for t in toks: if t == "-": self.exprStack.append("unary -") else: break def clear_stack(self): del self.exprStack[:] def get_parser(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only match whole words e = CaselessKeyword("E") pi = CaselessKeyword("PI") # fnumber = Combine(Word("+-"+nums, nums) + # Optional("." + Optional(Word(nums))) + # Optional(e + Word("+-"+nums, nums))) # or use provided pyparsing_common.number, but convert back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r"[+-]?(?:\d+|\.\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?") ge_urn = Combine( Literal("urn:great_expectations:") + Word(alphas, f"{alphanums}_$:?=%.&") ) variable = Word(alphas, f"{alphanums}_$") ident = ge_urn | variable plus, minus, mult, div = map(Literal, "+-*/") lpar, rpar = map(Suppress, "()") addop = plus | minus multop = mult | div expop = Literal("^") expr = Forward() expr_list = delimitedList(Group(expr)) # We will allow functions either to accept *only* keyword # expressions or *only* non-keyword expressions # define function keyword arguments key = Word(f"{alphas}_") + Suppress("=") # value = (fnumber | Word(alphanums)) value = expr keyval = dictOf(key.setParseAction(self.push_first), value) kwarglist = delimitedList(keyval) # add parse action that replaces the function identifier with a (name, number of args, has_fn_kwargs) tuple # 20211009 - JPC - Note that it's important that we consider kwarglist # first as part of disabling backtracking for the function's arguments fn_call = (ident + lpar + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), 0, False)) ) | ( (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), False)) ) ^ (ident + lpar - Group(kwarglist) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), True)) ) ) atom = ( addop[...] + ( (fn_call | pi | e | fnumber | ident).setParseAction(self.push_first) | Group(lpar + expr + rpar) ) ).setParseAction(self.push_unary_minus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left # exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom + (expop + factor).setParseAction(self.push_first)[...] term = factor + (multop + factor).setParseAction(self.push_first)[...] expr <<= term + (addop + term).setParseAction(self.push_first)[...] self._parser = expr return self._parser def evaluate_stack(self, s): op, num_args, has_fn_kwargs = s.pop(), 0, False if isinstance(op, tuple): op, num_args, has_fn_kwargs = op if op == "unary -": return -self.evaluate_stack(s) if op in "+-*/^": # note: operands are pushed onto the stack in reverse order op2 = self.evaluate_stack(s) op1 = self.evaluate_stack(s) return self.opn[op](op1, op2) elif op == "PI": return math.pi # 3.1415926535 elif op == "E": return math.e # 2.718281828 elif op in self.fn: # note: args are pushed onto the stack in reverse order if has_fn_kwargs: kwargs = dict() for _ in range(num_args): v = self.evaluate_stack(s) k = s.pop() kwargs.update({k: v}) return self.fn[op](**kwargs) else: args = reversed([self.evaluate_stack(s) for _ in range(num_args)]) return self.fn[op](*args) else: # try to evaluate as int first, then as float if int fails # NOTE: JPC - 20200403 - Originally I considered returning the raw op here if parsing as float also # fails, but I decided against it to instead require that the *entire* expression evaluates # numerically UNLESS there is *exactly one* expression to substitute (see cases where len(L) == 1 in the # parse_evaluation_parameter method. try: return int(op) except ValueError: return float(op) def build_evaluation_parameters( expectation_args: dict, evaluation_parameters: Optional[dict] = None, interactive_evaluation: bool = True, data_context=None, ) -> Tuple[dict, dict]: """Build a dictionary of parameters to evaluate, using the provided evaluation_parameters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work. """ evaluation_args = copy.deepcopy(expectation_args) substituted_parameters = {} # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and "$PARAMETER" in value: # We do not even need to search for a value if we are not going to do interactive evaluation if not interactive_evaluation: continue # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config param_key = f"$PARAMETER.{value['$PARAMETER']}" if param_key in value: evaluation_args[key] = evaluation_args[key][param_key] del expectation_args[key][param_key] # If not, try to parse the evaluation parameter and substitute, which will raise # an exception if we do not have a value else: raw_value = value["$PARAMETER"] parameter_value = parse_evaluation_parameter( raw_value, evaluation_parameters=evaluation_parameters, data_context=data_context, ) evaluation_args[key] = parameter_value # Once we've substituted, we also track that we did so substituted_parameters[key] = parameter_value return evaluation_args, substituted_parameters expr = EvaluationParameterParser() def find_evaluation_parameter_dependencies(parameter_expression): """Parse a parameter expression to identify dependencies including GE URNs. Args: parameter_expression: the parameter to parse Returns: a dictionary including: - "urns": set of strings that are valid GE URN objects - "other": set of non-GE URN strings that are required to evaluate the parameter expression """ expr = EvaluationParameterParser() dependencies = {"urns": set(), "other": set()} # Calling get_parser clears the stack parser = expr.get_parser() try: _ = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)} at line {err.line}, column {err.column}" ) except AttributeError as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)}" ) for word in expr.exprStack: if isinstance(word, (int, float)): continue if not isinstance(word, str): # If we have a function that itself is a tuple (e.g. (trunc, 1)) continue if word in expr.opn or word in expr.fn or word == "unary -": # operations and functions continue # if this is parseable as a number, then we do not include it try: _ = float(word) continue except ValueError: pass try: _ = ge_urn.parseString(word) dependencies["urns"].add(word) continue except ParseException: # This particular evaluation_parameter or operator is not a valid URN pass # If we got this far, it's a legitimate "other" evaluation parameter dependencies["other"].add(word) return dependencies def parse_evaluation_parameter( parameter_expression: str, evaluation_parameters: Optional[Dict[str, Any]] = None, data_context: Optional[Any] = None, # Cannot type 'DataContext' due to import cycle ) -> Any: """Use the provided evaluation_parameters dict to parse a given parameter expression. Args: parameter_expression (str): A string, potentially containing basic arithmetic operations and functions, and variables to be substituted evaluation_parameters (dict): A dictionary of name-value pairs consisting of values to substitute data_context (DataContext): A data context to use to obtain metrics, if necessary The parser will allow arithmetic operations +, -, /, *, as well as basic functions, including trunc() and round() to obtain integer values when needed for certain expectations (e.g. expect_column_value_length_to_be_between). Valid variables must begin with an alphabetic character and may contain alphanumeric characters plus '_' and '$', EXCEPT if they begin with the string "urn:great_expectations" in which case they may also include additional characters to support inclusion of GE URLs (see :ref:`evaluation_parameters` for more information). """ if evaluation_parameters is None: evaluation_parameters = {} # Calling get_parser clears the stack parser = expr.get_parser() try: L = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: L = ["Parse Failure", parameter_expression, (str(err), err.line, err.column)] # Represents a valid parser result of a single function that has no arguments if len(L) == 1 and isinstance(L[0], tuple) and L[0][2] is False: # Necessary to catch `now()` (which only needs to be evaluated with `expr.exprStack`) # NOTE: 20211122 - Chetan - Any future built-ins that are zero arity functions will match this behavior pass elif len(L) == 1 and L[0] not in evaluation_parameters: # In this special case there were no operations to find, so only one value, but we don't have something to # substitute for that value try: res = ge_urn.parseString(L[0]) if res["urn_type"] == "stores": store = data_context.stores.get(res["store_name"]) return store.get_query_result( res["metric_name"], res.get("metric_kwargs", {}) ) else:
except ParseException as e: logger.debug( f"Parse exception while parsing evaluation parameter: {str(e)}" ) raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") except AttributeError: logger.warning("Unable to get store for store-type valuation parameter.") raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") elif len(L) == 1: # In this case, we *do* have a substitution for a single type. We treat this specially because in this # case, we allow complex type substitutions (i.e. do not coerce to string as part of parsing) # NOTE: 20201023 - JPC - to support MetricDefinition as an evaluation parameter type, we need to handle that # case here; is the evaluation parameter provided here in fact a metric definition? return evaluation_parameters[L[0]] elif len(L) == 0 or L[0] != "Parse Failure": for i, ob in enumerate(expr.exprStack): if isinstance(ob, str) and ob in evaluation_parameters: expr.exprStack[i] = str(evaluation_parameters[ob]) else: err_str, err_line, err_col = L[-1] raise EvaluationParameterError( f"Parse Failure: {err_str}\nStatement: {err_line}\nColumn: {err_col}" ) try: result = expr.evaluate_stack(expr.exprStack) result = convert_to_json_serializable(result) except Exception as e: exception_traceback = traceback.format_exc() exception_message = ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.debug(exception_message, e, exc_info=True) raise EvaluationParameterError( f"Error while evaluating evaluation parameter expression: {str(e)}" ) return result def _deduplicate_evaluation_parameter_dependencies(dependencies: dict) -> dict: deduplicated = {} for suite_name, required_metrics in dependencies.items(): deduplicated[suite_name] = [] metrics = set() metric_kwargs = {} for metric in required_metrics: if isinstance(metric, str): metrics.add(metric) elif isinstance(metric, dict): # There is a single metric_kwargs_id object in this construction for kwargs_id, metric_list in metric["metric_kwargs_id"].items(): if kwargs_id not in metric_kwargs: metric_kwargs[kwargs_id] = set() for metric_name in metric_list: metric_kwargs[kwargs_id].add(metric_name) deduplicated[suite_name] = list(metrics) if len(metric_kwargs) > 0: deduplicated[suite_name] = deduplicated[suite_name] + [ { "metric_kwargs_id": { metric_kwargs: list(metrics_set) for (metric_kwargs, metrics_set) in metric_kwargs.items() } } ] return deduplicated EvaluationParameterIdentifier = namedtuple( "EvaluationParameterIdentifier", ["expectation_suite_name", "metric_name", "metric_kwargs_id"], )
logger.error( "Unrecognized urn_type in ge_urn: must be 'stores' to use a metric store." ) raise EvaluationParameterError( f"No value found for $PARAMETER {str(L[0])}" )
conditional_block
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, alphanums, alphas, delimitedList, dictOf, ) from great_expectations.core.urn import ge_urn from great_expectations.core.util import convert_to_json_serializable from great_expectations.exceptions import EvaluationParameterError logger = logging.getLogger(__name__) _epsilon = 1e-12 class EvaluationParameterParser: """ This Evaluation Parameter Parser uses pyparsing to provide a basic expression language capable of evaluating parameters using values available only at run time. expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* The parser is modified from: https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py """ # map operator symbols to corresponding arithmetic operations opn = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow, } fn = { "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "abs": abs, "trunc": lambda a: int(a), "round": round, "sgn": lambda a: -1 if a < -_epsilon else 1 if a > _epsilon else 0, "now": datetime.datetime.now, "datetime": datetime.datetime, "timedelta": datetime.timedelta, } def __init__(self): self.exprStack = [] self._parser = None def push_first(self, toks): self.exprStack.append(toks[0]) def push_unary_minus(self, toks):
def clear_stack(self): del self.exprStack[:] def get_parser(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only match whole words e = CaselessKeyword("E") pi = CaselessKeyword("PI") # fnumber = Combine(Word("+-"+nums, nums) + # Optional("." + Optional(Word(nums))) + # Optional(e + Word("+-"+nums, nums))) # or use provided pyparsing_common.number, but convert back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r"[+-]?(?:\d+|\.\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?") ge_urn = Combine( Literal("urn:great_expectations:") + Word(alphas, f"{alphanums}_$:?=%.&") ) variable = Word(alphas, f"{alphanums}_$") ident = ge_urn | variable plus, minus, mult, div = map(Literal, "+-*/") lpar, rpar = map(Suppress, "()") addop = plus | minus multop = mult | div expop = Literal("^") expr = Forward() expr_list = delimitedList(Group(expr)) # We will allow functions either to accept *only* keyword # expressions or *only* non-keyword expressions # define function keyword arguments key = Word(f"{alphas}_") + Suppress("=") # value = (fnumber | Word(alphanums)) value = expr keyval = dictOf(key.setParseAction(self.push_first), value) kwarglist = delimitedList(keyval) # add parse action that replaces the function identifier with a (name, number of args, has_fn_kwargs) tuple # 20211009 - JPC - Note that it's important that we consider kwarglist # first as part of disabling backtracking for the function's arguments fn_call = (ident + lpar + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), 0, False)) ) | ( (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), False)) ) ^ (ident + lpar - Group(kwarglist) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), True)) ) ) atom = ( addop[...] + ( (fn_call | pi | e | fnumber | ident).setParseAction(self.push_first) | Group(lpar + expr + rpar) ) ).setParseAction(self.push_unary_minus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left # exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom + (expop + factor).setParseAction(self.push_first)[...] term = factor + (multop + factor).setParseAction(self.push_first)[...] expr <<= term + (addop + term).setParseAction(self.push_first)[...] self._parser = expr return self._parser def evaluate_stack(self, s): op, num_args, has_fn_kwargs = s.pop(), 0, False if isinstance(op, tuple): op, num_args, has_fn_kwargs = op if op == "unary -": return -self.evaluate_stack(s) if op in "+-*/^": # note: operands are pushed onto the stack in reverse order op2 = self.evaluate_stack(s) op1 = self.evaluate_stack(s) return self.opn[op](op1, op2) elif op == "PI": return math.pi # 3.1415926535 elif op == "E": return math.e # 2.718281828 elif op in self.fn: # note: args are pushed onto the stack in reverse order if has_fn_kwargs: kwargs = dict() for _ in range(num_args): v = self.evaluate_stack(s) k = s.pop() kwargs.update({k: v}) return self.fn[op](**kwargs) else: args = reversed([self.evaluate_stack(s) for _ in range(num_args)]) return self.fn[op](*args) else: # try to evaluate as int first, then as float if int fails # NOTE: JPC - 20200403 - Originally I considered returning the raw op here if parsing as float also # fails, but I decided against it to instead require that the *entire* expression evaluates # numerically UNLESS there is *exactly one* expression to substitute (see cases where len(L) == 1 in the # parse_evaluation_parameter method. try: return int(op) except ValueError: return float(op) def build_evaluation_parameters( expectation_args: dict, evaluation_parameters: Optional[dict] = None, interactive_evaluation: bool = True, data_context=None, ) -> Tuple[dict, dict]: """Build a dictionary of parameters to evaluate, using the provided evaluation_parameters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work. """ evaluation_args = copy.deepcopy(expectation_args) substituted_parameters = {} # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and "$PARAMETER" in value: # We do not even need to search for a value if we are not going to do interactive evaluation if not interactive_evaluation: continue # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config param_key = f"$PARAMETER.{value['$PARAMETER']}" if param_key in value: evaluation_args[key] = evaluation_args[key][param_key] del expectation_args[key][param_key] # If not, try to parse the evaluation parameter and substitute, which will raise # an exception if we do not have a value else: raw_value = value["$PARAMETER"] parameter_value = parse_evaluation_parameter( raw_value, evaluation_parameters=evaluation_parameters, data_context=data_context, ) evaluation_args[key] = parameter_value # Once we've substituted, we also track that we did so substituted_parameters[key] = parameter_value return evaluation_args, substituted_parameters expr = EvaluationParameterParser() def find_evaluation_parameter_dependencies(parameter_expression): """Parse a parameter expression to identify dependencies including GE URNs. Args: parameter_expression: the parameter to parse Returns: a dictionary including: - "urns": set of strings that are valid GE URN objects - "other": set of non-GE URN strings that are required to evaluate the parameter expression """ expr = EvaluationParameterParser() dependencies = {"urns": set(), "other": set()} # Calling get_parser clears the stack parser = expr.get_parser() try: _ = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)} at line {err.line}, column {err.column}" ) except AttributeError as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)}" ) for word in expr.exprStack: if isinstance(word, (int, float)): continue if not isinstance(word, str): # If we have a function that itself is a tuple (e.g. (trunc, 1)) continue if word in expr.opn or word in expr.fn or word == "unary -": # operations and functions continue # if this is parseable as a number, then we do not include it try: _ = float(word) continue except ValueError: pass try: _ = ge_urn.parseString(word) dependencies["urns"].add(word) continue except ParseException: # This particular evaluation_parameter or operator is not a valid URN pass # If we got this far, it's a legitimate "other" evaluation parameter dependencies["other"].add(word) return dependencies def parse_evaluation_parameter( parameter_expression: str, evaluation_parameters: Optional[Dict[str, Any]] = None, data_context: Optional[Any] = None, # Cannot type 'DataContext' due to import cycle ) -> Any: """Use the provided evaluation_parameters dict to parse a given parameter expression. Args: parameter_expression (str): A string, potentially containing basic arithmetic operations and functions, and variables to be substituted evaluation_parameters (dict): A dictionary of name-value pairs consisting of values to substitute data_context (DataContext): A data context to use to obtain metrics, if necessary The parser will allow arithmetic operations +, -, /, *, as well as basic functions, including trunc() and round() to obtain integer values when needed for certain expectations (e.g. expect_column_value_length_to_be_between). Valid variables must begin with an alphabetic character and may contain alphanumeric characters plus '_' and '$', EXCEPT if they begin with the string "urn:great_expectations" in which case they may also include additional characters to support inclusion of GE URLs (see :ref:`evaluation_parameters` for more information). """ if evaluation_parameters is None: evaluation_parameters = {} # Calling get_parser clears the stack parser = expr.get_parser() try: L = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: L = ["Parse Failure", parameter_expression, (str(err), err.line, err.column)] # Represents a valid parser result of a single function that has no arguments if len(L) == 1 and isinstance(L[0], tuple) and L[0][2] is False: # Necessary to catch `now()` (which only needs to be evaluated with `expr.exprStack`) # NOTE: 20211122 - Chetan - Any future built-ins that are zero arity functions will match this behavior pass elif len(L) == 1 and L[0] not in evaluation_parameters: # In this special case there were no operations to find, so only one value, but we don't have something to # substitute for that value try: res = ge_urn.parseString(L[0]) if res["urn_type"] == "stores": store = data_context.stores.get(res["store_name"]) return store.get_query_result( res["metric_name"], res.get("metric_kwargs", {}) ) else: logger.error( "Unrecognized urn_type in ge_urn: must be 'stores' to use a metric store." ) raise EvaluationParameterError( f"No value found for $PARAMETER {str(L[0])}" ) except ParseException as e: logger.debug( f"Parse exception while parsing evaluation parameter: {str(e)}" ) raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") except AttributeError: logger.warning("Unable to get store for store-type valuation parameter.") raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") elif len(L) == 1: # In this case, we *do* have a substitution for a single type. We treat this specially because in this # case, we allow complex type substitutions (i.e. do not coerce to string as part of parsing) # NOTE: 20201023 - JPC - to support MetricDefinition as an evaluation parameter type, we need to handle that # case here; is the evaluation parameter provided here in fact a metric definition? return evaluation_parameters[L[0]] elif len(L) == 0 or L[0] != "Parse Failure": for i, ob in enumerate(expr.exprStack): if isinstance(ob, str) and ob in evaluation_parameters: expr.exprStack[i] = str(evaluation_parameters[ob]) else: err_str, err_line, err_col = L[-1] raise EvaluationParameterError( f"Parse Failure: {err_str}\nStatement: {err_line}\nColumn: {err_col}" ) try: result = expr.evaluate_stack(expr.exprStack) result = convert_to_json_serializable(result) except Exception as e: exception_traceback = traceback.format_exc() exception_message = ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.debug(exception_message, e, exc_info=True) raise EvaluationParameterError( f"Error while evaluating evaluation parameter expression: {str(e)}" ) return result def _deduplicate_evaluation_parameter_dependencies(dependencies: dict) -> dict: deduplicated = {} for suite_name, required_metrics in dependencies.items(): deduplicated[suite_name] = [] metrics = set() metric_kwargs = {} for metric in required_metrics: if isinstance(metric, str): metrics.add(metric) elif isinstance(metric, dict): # There is a single metric_kwargs_id object in this construction for kwargs_id, metric_list in metric["metric_kwargs_id"].items(): if kwargs_id not in metric_kwargs: metric_kwargs[kwargs_id] = set() for metric_name in metric_list: metric_kwargs[kwargs_id].add(metric_name) deduplicated[suite_name] = list(metrics) if len(metric_kwargs) > 0: deduplicated[suite_name] = deduplicated[suite_name] + [ { "metric_kwargs_id": { metric_kwargs: list(metrics_set) for (metric_kwargs, metrics_set) in metric_kwargs.items() } } ] return deduplicated EvaluationParameterIdentifier = namedtuple( "EvaluationParameterIdentifier", ["expectation_suite_name", "metric_name", "metric_kwargs_id"], )
for t in toks: if t == "-": self.exprStack.append("unary -") else: break
identifier_body
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, alphanums, alphas, delimitedList, dictOf, ) from great_expectations.core.urn import ge_urn from great_expectations.core.util import convert_to_json_serializable from great_expectations.exceptions import EvaluationParameterError logger = logging.getLogger(__name__) _epsilon = 1e-12 class EvaluationParameterParser: """ This Evaluation Parameter Parser uses pyparsing to provide a basic expression language capable of evaluating parameters using values available only at run time. expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* The parser is modified from: https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py """ # map operator symbols to corresponding arithmetic operations opn = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow, } fn = { "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "abs": abs, "trunc": lambda a: int(a), "round": round, "sgn": lambda a: -1 if a < -_epsilon else 1 if a > _epsilon else 0, "now": datetime.datetime.now, "datetime": datetime.datetime, "timedelta": datetime.timedelta, } def __init__(self): self.exprStack = [] self._parser = None def push_first(self, toks): self.exprStack.append(toks[0]) def push_unary_minus(self, toks): for t in toks: if t == "-": self.exprStack.append("unary -") else: break def clear_stack(self): del self.exprStack[:] def get_parser(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only match whole words e = CaselessKeyword("E") pi = CaselessKeyword("PI") # fnumber = Combine(Word("+-"+nums, nums) + # Optional("." + Optional(Word(nums))) + # Optional(e + Word("+-"+nums, nums))) # or use provided pyparsing_common.number, but convert back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r"[+-]?(?:\d+|\.\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?") ge_urn = Combine( Literal("urn:great_expectations:") + Word(alphas, f"{alphanums}_$:?=%.&") ) variable = Word(alphas, f"{alphanums}_$") ident = ge_urn | variable plus, minus, mult, div = map(Literal, "+-*/") lpar, rpar = map(Suppress, "()") addop = plus | minus multop = mult | div expop = Literal("^") expr = Forward() expr_list = delimitedList(Group(expr)) # We will allow functions either to accept *only* keyword # expressions or *only* non-keyword expressions # define function keyword arguments key = Word(f"{alphas}_") + Suppress("=") # value = (fnumber | Word(alphanums)) value = expr keyval = dictOf(key.setParseAction(self.push_first), value) kwarglist = delimitedList(keyval) # add parse action that replaces the function identifier with a (name, number of args, has_fn_kwargs) tuple # 20211009 - JPC - Note that it's important that we consider kwarglist # first as part of disabling backtracking for the function's arguments fn_call = (ident + lpar + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), 0, False)) ) | ( (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), False)) ) ^ (ident + lpar - Group(kwarglist) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), True)) ) ) atom = ( addop[...] + ( (fn_call | pi | e | fnumber | ident).setParseAction(self.push_first) | Group(lpar + expr + rpar) ) ).setParseAction(self.push_unary_minus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left # exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom + (expop + factor).setParseAction(self.push_first)[...] term = factor + (multop + factor).setParseAction(self.push_first)[...] expr <<= term + (addop + term).setParseAction(self.push_first)[...] self._parser = expr return self._parser def evaluate_stack(self, s): op, num_args, has_fn_kwargs = s.pop(), 0, False if isinstance(op, tuple): op, num_args, has_fn_kwargs = op if op == "unary -": return -self.evaluate_stack(s) if op in "+-*/^": # note: operands are pushed onto the stack in reverse order op2 = self.evaluate_stack(s) op1 = self.evaluate_stack(s) return self.opn[op](op1, op2) elif op == "PI": return math.pi # 3.1415926535 elif op == "E": return math.e # 2.718281828 elif op in self.fn: # note: args are pushed onto the stack in reverse order if has_fn_kwargs: kwargs = dict() for _ in range(num_args): v = self.evaluate_stack(s) k = s.pop() kwargs.update({k: v}) return self.fn[op](**kwargs) else: args = reversed([self.evaluate_stack(s) for _ in range(num_args)]) return self.fn[op](*args) else: # try to evaluate as int first, then as float if int fails # NOTE: JPC - 20200403 - Originally I considered returning the raw op here if parsing as float also # fails, but I decided against it to instead require that the *entire* expression evaluates # numerically UNLESS there is *exactly one* expression to substitute (see cases where len(L) == 1 in the # parse_evaluation_parameter method. try: return int(op) except ValueError: return float(op) def build_evaluation_parameters( expectation_args: dict, evaluation_parameters: Optional[dict] = None, interactive_evaluation: bool = True, data_context=None, ) -> Tuple[dict, dict]: """Build a dictionary of parameters to evaluate, using the provided evaluation_parameters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work. """ evaluation_args = copy.deepcopy(expectation_args) substituted_parameters = {} # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and "$PARAMETER" in value: # We do not even need to search for a value if we are not going to do interactive evaluation if not interactive_evaluation: continue # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config param_key = f"$PARAMETER.{value['$PARAMETER']}" if param_key in value: evaluation_args[key] = evaluation_args[key][param_key] del expectation_args[key][param_key] # If not, try to parse the evaluation parameter and substitute, which will raise # an exception if we do not have a value else: raw_value = value["$PARAMETER"] parameter_value = parse_evaluation_parameter( raw_value, evaluation_parameters=evaluation_parameters, data_context=data_context, ) evaluation_args[key] = parameter_value # Once we've substituted, we also track that we did so substituted_parameters[key] = parameter_value return evaluation_args, substituted_parameters expr = EvaluationParameterParser() def find_evaluation_parameter_dependencies(parameter_expression): """Parse a parameter expression to identify dependencies including GE URNs. Args: parameter_expression: the parameter to parse Returns: a dictionary including: - "urns": set of strings that are valid GE URN objects - "other": set of non-GE URN strings that are required to evaluate the parameter expression """ expr = EvaluationParameterParser() dependencies = {"urns": set(), "other": set()} # Calling get_parser clears the stack parser = expr.get_parser() try: _ = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)} at line {err.line}, column {err.column}" ) except AttributeError as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)}" ) for word in expr.exprStack: if isinstance(word, (int, float)): continue if not isinstance(word, str): # If we have a function that itself is a tuple (e.g. (trunc, 1)) continue if word in expr.opn or word in expr.fn or word == "unary -": # operations and functions continue # if this is parseable as a number, then we do not include it try: _ = float(word) continue except ValueError: pass try: _ = ge_urn.parseString(word) dependencies["urns"].add(word) continue except ParseException: # This particular evaluation_parameter or operator is not a valid URN pass # If we got this far, it's a legitimate "other" evaluation parameter dependencies["other"].add(word) return dependencies def parse_evaluation_parameter( parameter_expression: str, evaluation_parameters: Optional[Dict[str, Any]] = None, data_context: Optional[Any] = None, # Cannot type 'DataContext' due to import cycle ) -> Any: """Use the provided evaluation_parameters dict to parse a given parameter expression. Args: parameter_expression (str): A string, potentially containing basic arithmetic operations and functions, and variables to be substituted evaluation_parameters (dict): A dictionary of name-value pairs consisting of values to substitute data_context (DataContext): A data context to use to obtain metrics, if necessary The parser will allow arithmetic operations +, -, /, *, as well as basic functions, including trunc() and round() to obtain integer values when needed for certain expectations (e.g. expect_column_value_length_to_be_between). Valid variables must begin with an alphabetic character and may contain alphanumeric characters plus '_' and '$', EXCEPT if they begin with the string "urn:great_expectations" in which case they may also include additional characters to support inclusion of GE URLs (see :ref:`evaluation_parameters` for more information). """ if evaluation_parameters is None: evaluation_parameters = {} # Calling get_parser clears the stack parser = expr.get_parser() try: L = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: L = ["Parse Failure", parameter_expression, (str(err), err.line, err.column)] # Represents a valid parser result of a single function that has no arguments if len(L) == 1 and isinstance(L[0], tuple) and L[0][2] is False: # Necessary to catch `now()` (which only needs to be evaluated with `expr.exprStack`) # NOTE: 20211122 - Chetan - Any future built-ins that are zero arity functions will match this behavior pass elif len(L) == 1 and L[0] not in evaluation_parameters: # In this special case there were no operations to find, so only one value, but we don't have something to # substitute for that value try: res = ge_urn.parseString(L[0]) if res["urn_type"] == "stores": store = data_context.stores.get(res["store_name"]) return store.get_query_result( res["metric_name"], res.get("metric_kwargs", {}) ) else: logger.error( "Unrecognized urn_type in ge_urn: must be 'stores' to use a metric store." ) raise EvaluationParameterError( f"No value found for $PARAMETER {str(L[0])}" ) except ParseException as e: logger.debug( f"Parse exception while parsing evaluation parameter: {str(e)}" ) raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") except AttributeError: logger.warning("Unable to get store for store-type valuation parameter.") raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") elif len(L) == 1: # In this case, we *do* have a substitution for a single type. We treat this specially because in this # case, we allow complex type substitutions (i.e. do not coerce to string as part of parsing) # NOTE: 20201023 - JPC - to support MetricDefinition as an evaluation parameter type, we need to handle that # case here; is the evaluation parameter provided here in fact a metric definition? return evaluation_parameters[L[0]] elif len(L) == 0 or L[0] != "Parse Failure": for i, ob in enumerate(expr.exprStack): if isinstance(ob, str) and ob in evaluation_parameters: expr.exprStack[i] = str(evaluation_parameters[ob]) else: err_str, err_line, err_col = L[-1] raise EvaluationParameterError( f"Parse Failure: {err_str}\nStatement: {err_line}\nColumn: {err_col}" ) try: result = expr.evaluate_stack(expr.exprStack)
exception_traceback = traceback.format_exc() exception_message = ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.debug(exception_message, e, exc_info=True) raise EvaluationParameterError( f"Error while evaluating evaluation parameter expression: {str(e)}" ) return result def _deduplicate_evaluation_parameter_dependencies(dependencies: dict) -> dict: deduplicated = {} for suite_name, required_metrics in dependencies.items(): deduplicated[suite_name] = [] metrics = set() metric_kwargs = {} for metric in required_metrics: if isinstance(metric, str): metrics.add(metric) elif isinstance(metric, dict): # There is a single metric_kwargs_id object in this construction for kwargs_id, metric_list in metric["metric_kwargs_id"].items(): if kwargs_id not in metric_kwargs: metric_kwargs[kwargs_id] = set() for metric_name in metric_list: metric_kwargs[kwargs_id].add(metric_name) deduplicated[suite_name] = list(metrics) if len(metric_kwargs) > 0: deduplicated[suite_name] = deduplicated[suite_name] + [ { "metric_kwargs_id": { metric_kwargs: list(metrics_set) for (metric_kwargs, metrics_set) in metric_kwargs.items() } } ] return deduplicated EvaluationParameterIdentifier = namedtuple( "EvaluationParameterIdentifier", ["expectation_suite_name", "metric_name", "metric_kwargs_id"], )
result = convert_to_json_serializable(result) except Exception as e:
random_line_split
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, alphanums, alphas, delimitedList, dictOf, ) from great_expectations.core.urn import ge_urn from great_expectations.core.util import convert_to_json_serializable from great_expectations.exceptions import EvaluationParameterError logger = logging.getLogger(__name__) _epsilon = 1e-12 class EvaluationParameterParser: """ This Evaluation Parameter Parser uses pyparsing to provide a basic expression language capable of evaluating parameters using values available only at run time. expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* The parser is modified from: https://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py """ # map operator symbols to corresponding arithmetic operations opn = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow, } fn = { "sin": math.sin, "cos": math.cos, "tan": math.tan, "exp": math.exp, "abs": abs, "trunc": lambda a: int(a), "round": round, "sgn": lambda a: -1 if a < -_epsilon else 1 if a > _epsilon else 0, "now": datetime.datetime.now, "datetime": datetime.datetime, "timedelta": datetime.timedelta, } def __init__(self): self.exprStack = [] self._parser = None def push_first(self, toks): self.exprStack.append(toks[0]) def push_unary_minus(self, toks): for t in toks: if t == "-": self.exprStack.append("unary -") else: break def clear_stack(self): del self.exprStack[:] def
(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only match whole words e = CaselessKeyword("E") pi = CaselessKeyword("PI") # fnumber = Combine(Word("+-"+nums, nums) + # Optional("." + Optional(Word(nums))) + # Optional(e + Word("+-"+nums, nums))) # or use provided pyparsing_common.number, but convert back to str: # fnumber = ppc.number().addParseAction(lambda t: str(t[0])) fnumber = Regex(r"[+-]?(?:\d+|\.\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?") ge_urn = Combine( Literal("urn:great_expectations:") + Word(alphas, f"{alphanums}_$:?=%.&") ) variable = Word(alphas, f"{alphanums}_$") ident = ge_urn | variable plus, minus, mult, div = map(Literal, "+-*/") lpar, rpar = map(Suppress, "()") addop = plus | minus multop = mult | div expop = Literal("^") expr = Forward() expr_list = delimitedList(Group(expr)) # We will allow functions either to accept *only* keyword # expressions or *only* non-keyword expressions # define function keyword arguments key = Word(f"{alphas}_") + Suppress("=") # value = (fnumber | Word(alphanums)) value = expr keyval = dictOf(key.setParseAction(self.push_first), value) kwarglist = delimitedList(keyval) # add parse action that replaces the function identifier with a (name, number of args, has_fn_kwargs) tuple # 20211009 - JPC - Note that it's important that we consider kwarglist # first as part of disabling backtracking for the function's arguments fn_call = (ident + lpar + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), 0, False)) ) | ( (ident + lpar - Group(expr_list) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), False)) ) ^ (ident + lpar - Group(kwarglist) + rpar).setParseAction( lambda t: t.insert(0, (t.pop(0), len(t[0]), True)) ) ) atom = ( addop[...] + ( (fn_call | pi | e | fnumber | ident).setParseAction(self.push_first) | Group(lpar + expr + rpar) ) ).setParseAction(self.push_unary_minus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left # exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor <<= atom + (expop + factor).setParseAction(self.push_first)[...] term = factor + (multop + factor).setParseAction(self.push_first)[...] expr <<= term + (addop + term).setParseAction(self.push_first)[...] self._parser = expr return self._parser def evaluate_stack(self, s): op, num_args, has_fn_kwargs = s.pop(), 0, False if isinstance(op, tuple): op, num_args, has_fn_kwargs = op if op == "unary -": return -self.evaluate_stack(s) if op in "+-*/^": # note: operands are pushed onto the stack in reverse order op2 = self.evaluate_stack(s) op1 = self.evaluate_stack(s) return self.opn[op](op1, op2) elif op == "PI": return math.pi # 3.1415926535 elif op == "E": return math.e # 2.718281828 elif op in self.fn: # note: args are pushed onto the stack in reverse order if has_fn_kwargs: kwargs = dict() for _ in range(num_args): v = self.evaluate_stack(s) k = s.pop() kwargs.update({k: v}) return self.fn[op](**kwargs) else: args = reversed([self.evaluate_stack(s) for _ in range(num_args)]) return self.fn[op](*args) else: # try to evaluate as int first, then as float if int fails # NOTE: JPC - 20200403 - Originally I considered returning the raw op here if parsing as float also # fails, but I decided against it to instead require that the *entire* expression evaluates # numerically UNLESS there is *exactly one* expression to substitute (see cases where len(L) == 1 in the # parse_evaluation_parameter method. try: return int(op) except ValueError: return float(op) def build_evaluation_parameters( expectation_args: dict, evaluation_parameters: Optional[dict] = None, interactive_evaluation: bool = True, data_context=None, ) -> Tuple[dict, dict]: """Build a dictionary of parameters to evaluate, using the provided evaluation_parameters, AND mutate expectation_args by removing any parameter values passed in as temporary values during exploratory work. """ evaluation_args = copy.deepcopy(expectation_args) substituted_parameters = {} # Iterate over arguments, and replace $PARAMETER-defined args with their # specified parameters. for key, value in evaluation_args.items(): if isinstance(value, dict) and "$PARAMETER" in value: # We do not even need to search for a value if we are not going to do interactive evaluation if not interactive_evaluation: continue # First, check to see whether an argument was supplied at runtime # If it was, use that one, but remove it from the stored config param_key = f"$PARAMETER.{value['$PARAMETER']}" if param_key in value: evaluation_args[key] = evaluation_args[key][param_key] del expectation_args[key][param_key] # If not, try to parse the evaluation parameter and substitute, which will raise # an exception if we do not have a value else: raw_value = value["$PARAMETER"] parameter_value = parse_evaluation_parameter( raw_value, evaluation_parameters=evaluation_parameters, data_context=data_context, ) evaluation_args[key] = parameter_value # Once we've substituted, we also track that we did so substituted_parameters[key] = parameter_value return evaluation_args, substituted_parameters expr = EvaluationParameterParser() def find_evaluation_parameter_dependencies(parameter_expression): """Parse a parameter expression to identify dependencies including GE URNs. Args: parameter_expression: the parameter to parse Returns: a dictionary including: - "urns": set of strings that are valid GE URN objects - "other": set of non-GE URN strings that are required to evaluate the parameter expression """ expr = EvaluationParameterParser() dependencies = {"urns": set(), "other": set()} # Calling get_parser clears the stack parser = expr.get_parser() try: _ = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)} at line {err.line}, column {err.column}" ) except AttributeError as err: raise EvaluationParameterError( f"Unable to parse evaluation parameter: {str(err)}" ) for word in expr.exprStack: if isinstance(word, (int, float)): continue if not isinstance(word, str): # If we have a function that itself is a tuple (e.g. (trunc, 1)) continue if word in expr.opn or word in expr.fn or word == "unary -": # operations and functions continue # if this is parseable as a number, then we do not include it try: _ = float(word) continue except ValueError: pass try: _ = ge_urn.parseString(word) dependencies["urns"].add(word) continue except ParseException: # This particular evaluation_parameter or operator is not a valid URN pass # If we got this far, it's a legitimate "other" evaluation parameter dependencies["other"].add(word) return dependencies def parse_evaluation_parameter( parameter_expression: str, evaluation_parameters: Optional[Dict[str, Any]] = None, data_context: Optional[Any] = None, # Cannot type 'DataContext' due to import cycle ) -> Any: """Use the provided evaluation_parameters dict to parse a given parameter expression. Args: parameter_expression (str): A string, potentially containing basic arithmetic operations and functions, and variables to be substituted evaluation_parameters (dict): A dictionary of name-value pairs consisting of values to substitute data_context (DataContext): A data context to use to obtain metrics, if necessary The parser will allow arithmetic operations +, -, /, *, as well as basic functions, including trunc() and round() to obtain integer values when needed for certain expectations (e.g. expect_column_value_length_to_be_between). Valid variables must begin with an alphabetic character and may contain alphanumeric characters plus '_' and '$', EXCEPT if they begin with the string "urn:great_expectations" in which case they may also include additional characters to support inclusion of GE URLs (see :ref:`evaluation_parameters` for more information). """ if evaluation_parameters is None: evaluation_parameters = {} # Calling get_parser clears the stack parser = expr.get_parser() try: L = parser.parseString(parameter_expression, parseAll=True) except ParseException as err: L = ["Parse Failure", parameter_expression, (str(err), err.line, err.column)] # Represents a valid parser result of a single function that has no arguments if len(L) == 1 and isinstance(L[0], tuple) and L[0][2] is False: # Necessary to catch `now()` (which only needs to be evaluated with `expr.exprStack`) # NOTE: 20211122 - Chetan - Any future built-ins that are zero arity functions will match this behavior pass elif len(L) == 1 and L[0] not in evaluation_parameters: # In this special case there were no operations to find, so only one value, but we don't have something to # substitute for that value try: res = ge_urn.parseString(L[0]) if res["urn_type"] == "stores": store = data_context.stores.get(res["store_name"]) return store.get_query_result( res["metric_name"], res.get("metric_kwargs", {}) ) else: logger.error( "Unrecognized urn_type in ge_urn: must be 'stores' to use a metric store." ) raise EvaluationParameterError( f"No value found for $PARAMETER {str(L[0])}" ) except ParseException as e: logger.debug( f"Parse exception while parsing evaluation parameter: {str(e)}" ) raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") except AttributeError: logger.warning("Unable to get store for store-type valuation parameter.") raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") elif len(L) == 1: # In this case, we *do* have a substitution for a single type. We treat this specially because in this # case, we allow complex type substitutions (i.e. do not coerce to string as part of parsing) # NOTE: 20201023 - JPC - to support MetricDefinition as an evaluation parameter type, we need to handle that # case here; is the evaluation parameter provided here in fact a metric definition? return evaluation_parameters[L[0]] elif len(L) == 0 or L[0] != "Parse Failure": for i, ob in enumerate(expr.exprStack): if isinstance(ob, str) and ob in evaluation_parameters: expr.exprStack[i] = str(evaluation_parameters[ob]) else: err_str, err_line, err_col = L[-1] raise EvaluationParameterError( f"Parse Failure: {err_str}\nStatement: {err_line}\nColumn: {err_col}" ) try: result = expr.evaluate_stack(expr.exprStack) result = convert_to_json_serializable(result) except Exception as e: exception_traceback = traceback.format_exc() exception_message = ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.debug(exception_message, e, exc_info=True) raise EvaluationParameterError( f"Error while evaluating evaluation parameter expression: {str(e)}" ) return result def _deduplicate_evaluation_parameter_dependencies(dependencies: dict) -> dict: deduplicated = {} for suite_name, required_metrics in dependencies.items(): deduplicated[suite_name] = [] metrics = set() metric_kwargs = {} for metric in required_metrics: if isinstance(metric, str): metrics.add(metric) elif isinstance(metric, dict): # There is a single metric_kwargs_id object in this construction for kwargs_id, metric_list in metric["metric_kwargs_id"].items(): if kwargs_id not in metric_kwargs: metric_kwargs[kwargs_id] = set() for metric_name in metric_list: metric_kwargs[kwargs_id].add(metric_name) deduplicated[suite_name] = list(metrics) if len(metric_kwargs) > 0: deduplicated[suite_name] = deduplicated[suite_name] + [ { "metric_kwargs_id": { metric_kwargs: list(metrics_set) for (metric_kwargs, metrics_set) in metric_kwargs.items() } } ] return deduplicated EvaluationParameterIdentifier = namedtuple( "EvaluationParameterIdentifier", ["expectation_suite_name", "metric_name", "metric_kwargs_id"], )
get_parser
identifier_name
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('clSysPage', function ($http, $location, clToast, clSocketSvc) { return { restrict: 'E', templateUrl: 'optional/sysPage/sysPage.html', link: link } function link (scope) { scope.properties = [] scope.deleteRow = function (propertyToDelete) { scope.properties = scope.properties.cl_filter(function (property) { return property !== propertyToDelete }) } scope.addRow = function () { scope.properties.push({}) } scope.update = function () { var properties = {} if (Object.keys(scope.properties).length > 255) { return clToast('Too many properties.') } if ( scope.properties.cl_some(function (property) { if (!property.key && !property.value) { return } if (!property.key) { clToast("Property can't be empty.") return true } if (property.key.length > 255) { clToast('Property key is too long.') return true } if (!property.value) { clToast("Property can't be empty.") return true } if (property.value.length > 512) { clToast('Property value is too long.') return true } if (properties.hasOwnProperty(property.key)) { clToast('Duplicate property: ' + property.key + '.') return true } properties[property.key] = property.value }) ) { return } $http.post('/api/v1/config/app', properties, { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function () { clToast('App config updated.') }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } function
() { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = Object.keys(res).sort().cl_map(function (key) { return { key: key, value: res[key] } }) }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } retrieveConfig() } })
retrieveConfig
identifier_name
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('clSysPage', function ($http, $location, clToast, clSocketSvc) { return { restrict: 'E', templateUrl: 'optional/sysPage/sysPage.html', link: link } function link (scope) { scope.properties = [] scope.deleteRow = function (propertyToDelete) { scope.properties = scope.properties.cl_filter(function (property) { return property !== propertyToDelete }) } scope.addRow = function () { scope.properties.push({}) } scope.update = function () { var properties = {} if (Object.keys(scope.properties).length > 255) { return clToast('Too many properties.') } if ( scope.properties.cl_some(function (property) { if (!property.key && !property.value) { return } if (!property.key) { clToast("Property can't be empty.") return true } if (property.key.length > 255) { clToast('Property key is too long.') return true } if (!property.value) { clToast("Property can't be empty.") return true } if (property.value.length > 512) { clToast('Property value is too long.') return true } if (properties.hasOwnProperty(property.key))
properties[property.key] = property.value }) ) { return } $http.post('/api/v1/config/app', properties, { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function () { clToast('App config updated.') }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } function retrieveConfig () { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = Object.keys(res).sort().cl_map(function (key) { return { key: key, value: res[key] } }) }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } retrieveConfig() } })
{ clToast('Duplicate property: ' + property.key + '.') return true }
conditional_block
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('clSysPage', function ($http, $location, clToast, clSocketSvc) { return { restrict: 'E', templateUrl: 'optional/sysPage/sysPage.html', link: link } function link (scope) { scope.properties = [] scope.deleteRow = function (propertyToDelete) { scope.properties = scope.properties.cl_filter(function (property) { return property !== propertyToDelete }) } scope.addRow = function () { scope.properties.push({}) } scope.update = function () { var properties = {} if (Object.keys(scope.properties).length > 255) { return clToast('Too many properties.') } if ( scope.properties.cl_some(function (property) { if (!property.key && !property.value) { return } if (!property.key) { clToast("Property can't be empty.") return true } if (property.key.length > 255) { clToast('Property key is too long.') return true } if (!property.value) { clToast("Property can't be empty.") return true } if (property.value.length > 512) { clToast('Property value is too long.') return true } if (properties.hasOwnProperty(property.key)) { clToast('Duplicate property: ' + property.key + '.') return true } properties[property.key] = property.value }) ) { return } $http.post('/api/v1/config/app', properties, { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function () { clToast('App config updated.')
clToast('Error: ' + (err && err.message) || 'unknown') }) } function retrieveConfig () { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = Object.keys(res).sort().cl_map(function (key) { return { key: key, value: res[key] } }) }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } retrieveConfig() } })
}) .error(function (err) {
random_line_split
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('clSysPage', function ($http, $location, clToast, clSocketSvc) { return { restrict: 'E', templateUrl: 'optional/sysPage/sysPage.html', link: link } function link (scope)
})
{ scope.properties = [] scope.deleteRow = function (propertyToDelete) { scope.properties = scope.properties.cl_filter(function (property) { return property !== propertyToDelete }) } scope.addRow = function () { scope.properties.push({}) } scope.update = function () { var properties = {} if (Object.keys(scope.properties).length > 255) { return clToast('Too many properties.') } if ( scope.properties.cl_some(function (property) { if (!property.key && !property.value) { return } if (!property.key) { clToast("Property can't be empty.") return true } if (property.key.length > 255) { clToast('Property key is too long.') return true } if (!property.value) { clToast("Property can't be empty.") return true } if (property.value.length > 512) { clToast('Property value is too long.') return true } if (properties.hasOwnProperty(property.key)) { clToast('Duplicate property: ' + property.key + '.') return true } properties[property.key] = property.value }) ) { return } $http.post('/api/v1/config/app', properties, { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function () { clToast('App config updated.') }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } function retrieveConfig () { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = Object.keys(res).sort().cl_map(function (key) { return { key: key, value: res[key] } }) }) .error(function (err) { clToast('Error: ' + (err && err.message) || 'unknown') }) } retrieveConfig() }
identifier_body
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy import math import datetime import requests import json import re from operator import itemgetter from bson.objectid import ObjectId from pyspark import SparkContext, SparkConf from pymongo import MongoClient from pyspark.mllib.clustering import KMeans, KMeansModel from numpy import array from math import sqrt from geopy.distance import vincenty # Weights W_1 = 1.2 W_2 = .8 DISTANCE_THRESHOLD = 0.3 NUM_OF_IT = 8 MIN_LATITUDE = 59.78 MAX_LATITUDE = 59.92 MIN_LONGITUDE = 17.53 MAX_LONGITUDE = 17.75 MIN_COORDINATE = -13750 MAX_COORDINATE = 13750 CIRCLE_CONVERTER = math.pi / 43200 NUMBER_OF_RECOMMENDATIONS = 5 client2 = MongoClient('130.238.15.114') db2 = client2.monad1 client3 = MongoClient('130.238.15.114') db3 = client3.monad1 start = datetime.datetime.now() dontGoBehind = 0 def time_approximation(lat1, lon1, lat2, lon2): point1 = (lat1, lon1) point2 = (lat2, lon2) distance = vincenty(point1, point2).kilometers return int(round(distance / 10 * 60)) def retrieve_requests(): TravelRequest = db2.TravelRequest return TravelRequest def populate_requests(TravelRequest): results = db2.TravelRequest.find() for res in results: dist = time_approximation(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude']) if res['startTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['endTime'] - datetime.timedelta(minutes = dist)).time(), (res['endTime']).time()))) elif res['endTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['startTime'] + datetime.timedelta(minutes = dist)).time()))) else: users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['endTime']).time()))) def get_today_timetable(): TimeTable = db2.TimeTable first = datetime.datetime.today() first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0) route = TimeTable.find({'date': {'$gte': first}}) return route def populate_timetable(): route = get_today_timetable() waypoints = [] for res in route: for res1 in res['timetable']: for res2 in db2.BusTrip.find({'_id': res1}): for res3 in res2['trajectory']: for res4 in db2.BusStop.find({'_id':res3['busStop']}): waypoints.append((res3['time'],res4['latitude'], res4['longitude'], res4['name'])) routes.append((res1, waypoints)) waypoints = [] def iterator(waypoints): Waypoints = [] for res in waypoints: Waypoints.append((lat_normalizer(res[1]), lon_normalizer(res[2]), time_normalizer(to_coordinates(to_seconds(res[0]))[0]), time_normalizer(to_coordinates(to_seconds(res[0]))[1]), res[3])) return Waypoints # Converting time object to seconds def to_seconds(dt): total_time = dt.hour * 3600 + dt.minute * 60 + dt.second return total_time # Mapping seconds value to (x, y) coordinates def to_coordinates(secs): angle = float(secs) * CIRCLE_CONVERTER x = 13750 * math.cos(angle) y = 13750 * math.sin(angle) return x, y # Normalization functions def time_normalizer(value):
(MAX_COORDINATE - MIN_COORDINATE)) return new_value /2 def lat_normalizer(value): new_value = float((float(value) - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE)) return new_value def lon_normalizer(value): new_value = float((float(value) - MIN_LONGITUDE) / (MAX_LONGITUDE - MIN_LONGITUDE)) return new_value # Function that implements the kmeans algorithm to group users requests def kmeans(iterations, theRdd): def error(point): center = clusters.centers[clusters.predict(point)] return sqrt(sum([x**2 for x in (point - center)])) clusters = KMeans.train(theRdd, iterations, maxIterations=10, runs=10, initializationMode="random") WSSSE = theRdd.map(lambda point: error(point)).reduce(lambda x, y: x + y) return WSSSE, clusters # Function that runs iteratively the kmeans algorithm to find the best number # of clusters to group the user's request def optimalk(theRdd): results = [] for i in range(NUM_OF_IT): results.append(kmeans(i+1, theRdd)[0]) optimal = [] for i in range(NUM_OF_IT-1): optimal.append(results[i] - results[i+1]) optimal1 = [] for i in range(NUM_OF_IT-2): optimal1.append(optimal[i] - optimal[i+1]) return (optimal1.index(max(optimal1)) + 2) def back_to_coordinates(lat, lon): new_lat = (lat * (MAX_LATITUDE - MIN_LATITUDE)) + MIN_LATITUDE new_lon = (lon * (MAX_LONGITUDE - MIN_LONGITUDE)) + MIN_LONGITUDE return new_lat, new_lon def nearest_stops(lat, lon, dist): stops = [] url = "http://130.238.15.114:9998/get_nearest_stops_from_coordinates" data = {'lon': lon, 'lat': lat, 'distance': dist} headers = {'Content-type': 'application/x-www-form-urlencoded'} answer = requests.post(url, data = data, headers = headers) p = re.compile("(u'\w*')") answer = p.findall(answer.text) answer = [x.encode('UTF8') for x in answer] answer = [x[2:-1] for x in answer] answer = list(set(answer)) return answer # The function that calculate the distance from the given tuple to all the # cluster centroids and returns the minimum disstance def calculate_distance_departure(tup1): dist_departure = [] pos_departure = [] cent_num = 0 for i in selected_centroids: position = -1 min_value = 1000 min_position = 0 centroid_departure = (i[0]*W_1, i[1]*W_1,i[4]*W_2, i[5]*W_2) centroid_departure = numpy.array(centroid_departure) trajectory = [] for l in range(len(tup1)-1): position = position + 1 if(tup1[l][4] in nearest_stops_dep[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_departure - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_departure.append(result) pos_departure.append(min_position) cent_num += 1 return {"dist_departure":dist_departure,"pos_departure":pos_departure} def calculate_distance_arrival(tup1,pos_departure): dist_arrival = [] pos_arrival = [] counter=-1 cent_num = 0 for i in selected_centroids: min_value = 1000 min_position = 0 centroid_arrival = (i[2]*W_1, i[3]*W_1, i[6]*W_2, i[7]*W_2) centroid_arrival = numpy.array(centroid_arrival) counter = counter + 1 position = pos_departure[counter] for l in range(pos_departure[counter]+1, len(tup1)): position = position + 1 if(tup1[l][4] in nearest_stops_arr[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_arrival - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_arrival.append(result) pos_arrival.append(min_position) cent_num += 1 return {"dist_arrival":dist_arrival,"pos_arrival":pos_arrival} def remove_duplicates(alist): return list(set(map(lambda (w, x, y, z): (w, y, z), alist))) def recommendations_to_return(alist): for rec in alist: trip = db2.BusTrip.find_one({'_id': rec[0]}) traj = trip['trajectory'][rec[2]:rec[3]+1] trajectory = [] names_only = [] for stop in traj: name_and_time = (db2.BusStop.find_one({"_id": stop['busStop']}) ['name']), stop['time'] trajectory.append(name_and_time) names_only.append(name_and_time[0]) busid = 1.0 line = trip['line'] result = (int(line), int(busid), names_only[0], names_only[-1], names_only, trajectory[0][1], trajectory[-1][1], rec[0]) to_return.append(result) def recommendations_to_db(user, alist): rec_list = [] for item in to_return: o_id = ObjectId() line = item[0] bus_id = item[1] start_place = item[2] end_place = item[3] start_time = item[5] end_time = item[6] bus_trip_id = item[7] request_time = "null" feedback = -1 request_id = "null" next_trip = "null" booked = False trajectory = item[4] new_user_trip = { "_id":o_id, "userID" : user, "line" : line, "busID" : bus_id, "startBusStop" : start_place, "endBusStop" : end_place, "startTime" : start_time, "busTripID" : bus_trip_id, "endTime" : end_time, "feedback" : feedback, "trajectory" : trajectory, "booked" : booked } new_recommendation = { "userID": user, "userTrip": o_id } db3.UserTrip.insert(new_user_trip) db3.TravelRecommendation.insert(new_recommendation) def empty_past_recommendations(): db3.TravelRecommendation.drop() if __name__ == "__main__": user_ids = [] users = [] routes = [] user_ids = [] sc = SparkContext() populate_timetable() my_routes = sc.parallelize(routes, 8) my_routes = my_routes.map(lambda (x,y): (x, iterator(y))).cache() req = retrieve_requests() populate_requests(req) start = datetime.datetime.now() initial_rdd = sc.parallelize(users, 4).cache() user_ids_rdd = (initial_rdd.map(lambda (x,y): (x,1)) .reduceByKey(lambda a, b: a + b) .collect()) ''' for user in user_ids_rdd: user_ids.append(user[0]) ''' empty_past_recommendations() user_ids = [] user_ids.append(1) for userId in user_ids: userId = 1 recommendations = [] transition = [] final_recommendation = [] selected_centroids = [] routes_distances = [] to_return = [] nearest_stops_dep = [] nearest_stops_arr = [] my_rdd = (initial_rdd.filter(lambda (x,y): x == userId) .map(lambda (x,y): y)).cache() my_rdd = (my_rdd.map(lambda x: (x[0], x[1], x[2], x[3], to_coordinates(to_seconds(x[4])), to_coordinates(to_seconds(x[5])))) .map(lambda (x1, x2, x3, x4, (x5, x6), (x7, x8)): (lat_normalizer(x1), lon_normalizer(x2), lat_normalizer(x3), lon_normalizer(x4), time_normalizer(x5), time_normalizer(x6), time_normalizer(x7), time_normalizer(x8)))) selected_centroids = kmeans(4, my_rdd)[1].centers for i in range(len(selected_centroids)): cent_lat, cent_long = back_to_coordinates(selected_centroids[i][0], selected_centroids[i][1]) nearest_stops_dep.append(nearest_stops(cent_lat, cent_long, 200)) cent_lat, cent_long = back_to_coordinates(selected_centroids[i][2], selected_centroids[i][3]) nearest_stops_arr.append(nearest_stops(cent_lat, cent_long, 200)) routes_distances = my_routes.map(lambda x: (x[0], calculate_distance_departure(x[1])['dist_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['dist_arrival'], calculate_distance_departure(x[1])['pos_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['pos_arrival'])) for i in range(len(selected_centroids)): sort_route = (routes_distances.map(lambda (v, w, x, y, z): (v, w[i] + x[i], y[i], z[i])) .sortBy(lambda x:x[1])) final_recommendation.append((sort_route .take(NUMBER_OF_RECOMMENDATIONS))) for sug in final_recommendation: for i in range(len(sug)): temp = [] for j in range(len(sug[i])): temp.append(sug[i][j]) recommendations.append(temp) recommendations.sort(key=lambda x: x[1]) recommendations_final = [] for rec in recommendations: if abs(rec[2] - rec[3]) > 1 and rec[1] < DISTANCE_THRESHOLD: recommendations_final.append(rec) recommendations = recommendations_final[:10] recommendations_to_return(recommendations) recommendations_to_db(userId, to_return)
new_value = float((float(value) - MIN_COORDINATE) /
random_line_split
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy import math import datetime import requests import json import re from operator import itemgetter from bson.objectid import ObjectId from pyspark import SparkContext, SparkConf from pymongo import MongoClient from pyspark.mllib.clustering import KMeans, KMeansModel from numpy import array from math import sqrt from geopy.distance import vincenty # Weights W_1 = 1.2 W_2 = .8 DISTANCE_THRESHOLD = 0.3 NUM_OF_IT = 8 MIN_LATITUDE = 59.78 MAX_LATITUDE = 59.92 MIN_LONGITUDE = 17.53 MAX_LONGITUDE = 17.75 MIN_COORDINATE = -13750 MAX_COORDINATE = 13750 CIRCLE_CONVERTER = math.pi / 43200 NUMBER_OF_RECOMMENDATIONS = 5 client2 = MongoClient('130.238.15.114') db2 = client2.monad1 client3 = MongoClient('130.238.15.114') db3 = client3.monad1 start = datetime.datetime.now() dontGoBehind = 0 def time_approximation(lat1, lon1, lat2, lon2): point1 = (lat1, lon1) point2 = (lat2, lon2) distance = vincenty(point1, point2).kilometers return int(round(distance / 10 * 60)) def retrieve_requests(): TravelRequest = db2.TravelRequest return TravelRequest def populate_requests(TravelRequest): results = db2.TravelRequest.find() for res in results: dist = time_approximation(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude']) if res['startTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['endTime'] - datetime.timedelta(minutes = dist)).time(), (res['endTime']).time()))) elif res['endTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['startTime'] + datetime.timedelta(minutes = dist)).time()))) else: users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['endTime']).time()))) def get_today_timetable(): TimeTable = db2.TimeTable first = datetime.datetime.today() first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0) route = TimeTable.find({'date': {'$gte': first}}) return route def
(): route = get_today_timetable() waypoints = [] for res in route: for res1 in res['timetable']: for res2 in db2.BusTrip.find({'_id': res1}): for res3 in res2['trajectory']: for res4 in db2.BusStop.find({'_id':res3['busStop']}): waypoints.append((res3['time'],res4['latitude'], res4['longitude'], res4['name'])) routes.append((res1, waypoints)) waypoints = [] def iterator(waypoints): Waypoints = [] for res in waypoints: Waypoints.append((lat_normalizer(res[1]), lon_normalizer(res[2]), time_normalizer(to_coordinates(to_seconds(res[0]))[0]), time_normalizer(to_coordinates(to_seconds(res[0]))[1]), res[3])) return Waypoints # Converting time object to seconds def to_seconds(dt): total_time = dt.hour * 3600 + dt.minute * 60 + dt.second return total_time # Mapping seconds value to (x, y) coordinates def to_coordinates(secs): angle = float(secs) * CIRCLE_CONVERTER x = 13750 * math.cos(angle) y = 13750 * math.sin(angle) return x, y # Normalization functions def time_normalizer(value): new_value = float((float(value) - MIN_COORDINATE) / (MAX_COORDINATE - MIN_COORDINATE)) return new_value /2 def lat_normalizer(value): new_value = float((float(value) - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE)) return new_value def lon_normalizer(value): new_value = float((float(value) - MIN_LONGITUDE) / (MAX_LONGITUDE - MIN_LONGITUDE)) return new_value # Function that implements the kmeans algorithm to group users requests def kmeans(iterations, theRdd): def error(point): center = clusters.centers[clusters.predict(point)] return sqrt(sum([x**2 for x in (point - center)])) clusters = KMeans.train(theRdd, iterations, maxIterations=10, runs=10, initializationMode="random") WSSSE = theRdd.map(lambda point: error(point)).reduce(lambda x, y: x + y) return WSSSE, clusters # Function that runs iteratively the kmeans algorithm to find the best number # of clusters to group the user's request def optimalk(theRdd): results = [] for i in range(NUM_OF_IT): results.append(kmeans(i+1, theRdd)[0]) optimal = [] for i in range(NUM_OF_IT-1): optimal.append(results[i] - results[i+1]) optimal1 = [] for i in range(NUM_OF_IT-2): optimal1.append(optimal[i] - optimal[i+1]) return (optimal1.index(max(optimal1)) + 2) def back_to_coordinates(lat, lon): new_lat = (lat * (MAX_LATITUDE - MIN_LATITUDE)) + MIN_LATITUDE new_lon = (lon * (MAX_LONGITUDE - MIN_LONGITUDE)) + MIN_LONGITUDE return new_lat, new_lon def nearest_stops(lat, lon, dist): stops = [] url = "http://130.238.15.114:9998/get_nearest_stops_from_coordinates" data = {'lon': lon, 'lat': lat, 'distance': dist} headers = {'Content-type': 'application/x-www-form-urlencoded'} answer = requests.post(url, data = data, headers = headers) p = re.compile("(u'\w*')") answer = p.findall(answer.text) answer = [x.encode('UTF8') for x in answer] answer = [x[2:-1] for x in answer] answer = list(set(answer)) return answer # The function that calculate the distance from the given tuple to all the # cluster centroids and returns the minimum disstance def calculate_distance_departure(tup1): dist_departure = [] pos_departure = [] cent_num = 0 for i in selected_centroids: position = -1 min_value = 1000 min_position = 0 centroid_departure = (i[0]*W_1, i[1]*W_1,i[4]*W_2, i[5]*W_2) centroid_departure = numpy.array(centroid_departure) trajectory = [] for l in range(len(tup1)-1): position = position + 1 if(tup1[l][4] in nearest_stops_dep[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_departure - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_departure.append(result) pos_departure.append(min_position) cent_num += 1 return {"dist_departure":dist_departure,"pos_departure":pos_departure} def calculate_distance_arrival(tup1,pos_departure): dist_arrival = [] pos_arrival = [] counter=-1 cent_num = 0 for i in selected_centroids: min_value = 1000 min_position = 0 centroid_arrival = (i[2]*W_1, i[3]*W_1, i[6]*W_2, i[7]*W_2) centroid_arrival = numpy.array(centroid_arrival) counter = counter + 1 position = pos_departure[counter] for l in range(pos_departure[counter]+1, len(tup1)): position = position + 1 if(tup1[l][4] in nearest_stops_arr[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_arrival - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_arrival.append(result) pos_arrival.append(min_position) cent_num += 1 return {"dist_arrival":dist_arrival,"pos_arrival":pos_arrival} def remove_duplicates(alist): return list(set(map(lambda (w, x, y, z): (w, y, z), alist))) def recommendations_to_return(alist): for rec in alist: trip = db2.BusTrip.find_one({'_id': rec[0]}) traj = trip['trajectory'][rec[2]:rec[3]+1] trajectory = [] names_only = [] for stop in traj: name_and_time = (db2.BusStop.find_one({"_id": stop['busStop']}) ['name']), stop['time'] trajectory.append(name_and_time) names_only.append(name_and_time[0]) busid = 1.0 line = trip['line'] result = (int(line), int(busid), names_only[0], names_only[-1], names_only, trajectory[0][1], trajectory[-1][1], rec[0]) to_return.append(result) def recommendations_to_db(user, alist): rec_list = [] for item in to_return: o_id = ObjectId() line = item[0] bus_id = item[1] start_place = item[2] end_place = item[3] start_time = item[5] end_time = item[6] bus_trip_id = item[7] request_time = "null" feedback = -1 request_id = "null" next_trip = "null" booked = False trajectory = item[4] new_user_trip = { "_id":o_id, "userID" : user, "line" : line, "busID" : bus_id, "startBusStop" : start_place, "endBusStop" : end_place, "startTime" : start_time, "busTripID" : bus_trip_id, "endTime" : end_time, "feedback" : feedback, "trajectory" : trajectory, "booked" : booked } new_recommendation = { "userID": user, "userTrip": o_id } db3.UserTrip.insert(new_user_trip) db3.TravelRecommendation.insert(new_recommendation) def empty_past_recommendations(): db3.TravelRecommendation.drop() if __name__ == "__main__": user_ids = [] users = [] routes = [] user_ids = [] sc = SparkContext() populate_timetable() my_routes = sc.parallelize(routes, 8) my_routes = my_routes.map(lambda (x,y): (x, iterator(y))).cache() req = retrieve_requests() populate_requests(req) start = datetime.datetime.now() initial_rdd = sc.parallelize(users, 4).cache() user_ids_rdd = (initial_rdd.map(lambda (x,y): (x,1)) .reduceByKey(lambda a, b: a + b) .collect()) ''' for user in user_ids_rdd: user_ids.append(user[0]) ''' empty_past_recommendations() user_ids = [] user_ids.append(1) for userId in user_ids: userId = 1 recommendations = [] transition = [] final_recommendation = [] selected_centroids = [] routes_distances = [] to_return = [] nearest_stops_dep = [] nearest_stops_arr = [] my_rdd = (initial_rdd.filter(lambda (x,y): x == userId) .map(lambda (x,y): y)).cache() my_rdd = (my_rdd.map(lambda x: (x[0], x[1], x[2], x[3], to_coordinates(to_seconds(x[4])), to_coordinates(to_seconds(x[5])))) .map(lambda (x1, x2, x3, x4, (x5, x6), (x7, x8)): (lat_normalizer(x1), lon_normalizer(x2), lat_normalizer(x3), lon_normalizer(x4), time_normalizer(x5), time_normalizer(x6), time_normalizer(x7), time_normalizer(x8)))) selected_centroids = kmeans(4, my_rdd)[1].centers for i in range(len(selected_centroids)): cent_lat, cent_long = back_to_coordinates(selected_centroids[i][0], selected_centroids[i][1]) nearest_stops_dep.append(nearest_stops(cent_lat, cent_long, 200)) cent_lat, cent_long = back_to_coordinates(selected_centroids[i][2], selected_centroids[i][3]) nearest_stops_arr.append(nearest_stops(cent_lat, cent_long, 200)) routes_distances = my_routes.map(lambda x: (x[0], calculate_distance_departure(x[1])['dist_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['dist_arrival'], calculate_distance_departure(x[1])['pos_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['pos_arrival'])) for i in range(len(selected_centroids)): sort_route = (routes_distances.map(lambda (v, w, x, y, z): (v, w[i] + x[i], y[i], z[i])) .sortBy(lambda x:x[1])) final_recommendation.append((sort_route .take(NUMBER_OF_RECOMMENDATIONS))) for sug in final_recommendation: for i in range(len(sug)): temp = [] for j in range(len(sug[i])): temp.append(sug[i][j]) recommendations.append(temp) recommendations.sort(key=lambda x: x[1]) recommendations_final = [] for rec in recommendations: if abs(rec[2] - rec[3]) > 1 and rec[1] < DISTANCE_THRESHOLD: recommendations_final.append(rec) recommendations = recommendations_final[:10] recommendations_to_return(recommendations) recommendations_to_db(userId, to_return)
populate_timetable
identifier_name
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy import math import datetime import requests import json import re from operator import itemgetter from bson.objectid import ObjectId from pyspark import SparkContext, SparkConf from pymongo import MongoClient from pyspark.mllib.clustering import KMeans, KMeansModel from numpy import array from math import sqrt from geopy.distance import vincenty # Weights W_1 = 1.2 W_2 = .8 DISTANCE_THRESHOLD = 0.3 NUM_OF_IT = 8 MIN_LATITUDE = 59.78 MAX_LATITUDE = 59.92 MIN_LONGITUDE = 17.53 MAX_LONGITUDE = 17.75 MIN_COORDINATE = -13750 MAX_COORDINATE = 13750 CIRCLE_CONVERTER = math.pi / 43200 NUMBER_OF_RECOMMENDATIONS = 5 client2 = MongoClient('130.238.15.114') db2 = client2.monad1 client3 = MongoClient('130.238.15.114') db3 = client3.monad1 start = datetime.datetime.now() dontGoBehind = 0 def time_approximation(lat1, lon1, lat2, lon2): point1 = (lat1, lon1) point2 = (lat2, lon2) distance = vincenty(point1, point2).kilometers return int(round(distance / 10 * 60)) def retrieve_requests(): TravelRequest = db2.TravelRequest return TravelRequest def populate_requests(TravelRequest): results = db2.TravelRequest.find() for res in results: dist = time_approximation(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude']) if res['startTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['endTime'] - datetime.timedelta(minutes = dist)).time(), (res['endTime']).time()))) elif res['endTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['startTime'] + datetime.timedelta(minutes = dist)).time()))) else: users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['endTime']).time()))) def get_today_timetable(): TimeTable = db2.TimeTable first = datetime.datetime.today() first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0) route = TimeTable.find({'date': {'$gte': first}}) return route def populate_timetable(): route = get_today_timetable() waypoints = [] for res in route: for res1 in res['timetable']: for res2 in db2.BusTrip.find({'_id': res1}): for res3 in res2['trajectory']: for res4 in db2.BusStop.find({'_id':res3['busStop']}): waypoints.append((res3['time'],res4['latitude'], res4['longitude'], res4['name'])) routes.append((res1, waypoints)) waypoints = [] def iterator(waypoints): Waypoints = [] for res in waypoints: Waypoints.append((lat_normalizer(res[1]), lon_normalizer(res[2]), time_normalizer(to_coordinates(to_seconds(res[0]))[0]), time_normalizer(to_coordinates(to_seconds(res[0]))[1]), res[3])) return Waypoints # Converting time object to seconds def to_seconds(dt): total_time = dt.hour * 3600 + dt.minute * 60 + dt.second return total_time # Mapping seconds value to (x, y) coordinates def to_coordinates(secs): angle = float(secs) * CIRCLE_CONVERTER x = 13750 * math.cos(angle) y = 13750 * math.sin(angle) return x, y # Normalization functions def time_normalizer(value): new_value = float((float(value) - MIN_COORDINATE) / (MAX_COORDINATE - MIN_COORDINATE)) return new_value /2 def lat_normalizer(value): new_value = float((float(value) - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE)) return new_value def lon_normalizer(value): new_value = float((float(value) - MIN_LONGITUDE) / (MAX_LONGITUDE - MIN_LONGITUDE)) return new_value # Function that implements the kmeans algorithm to group users requests def kmeans(iterations, theRdd): def error(point): center = clusters.centers[clusters.predict(point)] return sqrt(sum([x**2 for x in (point - center)])) clusters = KMeans.train(theRdd, iterations, maxIterations=10, runs=10, initializationMode="random") WSSSE = theRdd.map(lambda point: error(point)).reduce(lambda x, y: x + y) return WSSSE, clusters # Function that runs iteratively the kmeans algorithm to find the best number # of clusters to group the user's request def optimalk(theRdd): results = [] for i in range(NUM_OF_IT): results.append(kmeans(i+1, theRdd)[0]) optimal = [] for i in range(NUM_OF_IT-1): optimal.append(results[i] - results[i+1]) optimal1 = [] for i in range(NUM_OF_IT-2): optimal1.append(optimal[i] - optimal[i+1]) return (optimal1.index(max(optimal1)) + 2) def back_to_coordinates(lat, lon): new_lat = (lat * (MAX_LATITUDE - MIN_LATITUDE)) + MIN_LATITUDE new_lon = (lon * (MAX_LONGITUDE - MIN_LONGITUDE)) + MIN_LONGITUDE return new_lat, new_lon def nearest_stops(lat, lon, dist): stops = [] url = "http://130.238.15.114:9998/get_nearest_stops_from_coordinates" data = {'lon': lon, 'lat': lat, 'distance': dist} headers = {'Content-type': 'application/x-www-form-urlencoded'} answer = requests.post(url, data = data, headers = headers) p = re.compile("(u'\w*')") answer = p.findall(answer.text) answer = [x.encode('UTF8') for x in answer] answer = [x[2:-1] for x in answer] answer = list(set(answer)) return answer # The function that calculate the distance from the given tuple to all the # cluster centroids and returns the minimum disstance def calculate_distance_departure(tup1): dist_departure = [] pos_departure = [] cent_num = 0 for i in selected_centroids: position = -1 min_value = 1000 min_position = 0 centroid_departure = (i[0]*W_1, i[1]*W_1,i[4]*W_2, i[5]*W_2) centroid_departure = numpy.array(centroid_departure) trajectory = [] for l in range(len(tup1)-1): position = position + 1 if(tup1[l][4] in nearest_stops_dep[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_departure - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_departure.append(result) pos_departure.append(min_position) cent_num += 1 return {"dist_departure":dist_departure,"pos_departure":pos_departure} def calculate_distance_arrival(tup1,pos_departure): dist_arrival = [] pos_arrival = [] counter=-1 cent_num = 0 for i in selected_centroids: min_value = 1000 min_position = 0 centroid_arrival = (i[2]*W_1, i[3]*W_1, i[6]*W_2, i[7]*W_2) centroid_arrival = numpy.array(centroid_arrival) counter = counter + 1 position = pos_departure[counter] for l in range(pos_departure[counter]+1, len(tup1)): position = position + 1 if(tup1[l][4] in nearest_stops_arr[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_arrival - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_arrival.append(result) pos_arrival.append(min_position) cent_num += 1 return {"dist_arrival":dist_arrival,"pos_arrival":pos_arrival} def remove_duplicates(alist): return list(set(map(lambda (w, x, y, z): (w, y, z), alist))) def recommendations_to_return(alist): for rec in alist: trip = db2.BusTrip.find_one({'_id': rec[0]}) traj = trip['trajectory'][rec[2]:rec[3]+1] trajectory = [] names_only = [] for stop in traj: name_and_time = (db2.BusStop.find_one({"_id": stop['busStop']}) ['name']), stop['time'] trajectory.append(name_and_time) names_only.append(name_and_time[0]) busid = 1.0 line = trip['line'] result = (int(line), int(busid), names_only[0], names_only[-1], names_only, trajectory[0][1], trajectory[-1][1], rec[0]) to_return.append(result) def recommendations_to_db(user, alist): rec_list = [] for item in to_return:
def empty_past_recommendations(): db3.TravelRecommendation.drop() if __name__ == "__main__": user_ids = [] users = [] routes = [] user_ids = [] sc = SparkContext() populate_timetable() my_routes = sc.parallelize(routes, 8) my_routes = my_routes.map(lambda (x,y): (x, iterator(y))).cache() req = retrieve_requests() populate_requests(req) start = datetime.datetime.now() initial_rdd = sc.parallelize(users, 4).cache() user_ids_rdd = (initial_rdd.map(lambda (x,y): (x,1)) .reduceByKey(lambda a, b: a + b) .collect()) ''' for user in user_ids_rdd: user_ids.append(user[0]) ''' empty_past_recommendations() user_ids = [] user_ids.append(1) for userId in user_ids: userId = 1 recommendations = [] transition = [] final_recommendation = [] selected_centroids = [] routes_distances = [] to_return = [] nearest_stops_dep = [] nearest_stops_arr = [] my_rdd = (initial_rdd.filter(lambda (x,y): x == userId) .map(lambda (x,y): y)).cache() my_rdd = (my_rdd.map(lambda x: (x[0], x[1], x[2], x[3], to_coordinates(to_seconds(x[4])), to_coordinates(to_seconds(x[5])))) .map(lambda (x1, x2, x3, x4, (x5, x6), (x7, x8)): (lat_normalizer(x1), lon_normalizer(x2), lat_normalizer(x3), lon_normalizer(x4), time_normalizer(x5), time_normalizer(x6), time_normalizer(x7), time_normalizer(x8)))) selected_centroids = kmeans(4, my_rdd)[1].centers for i in range(len(selected_centroids)): cent_lat, cent_long = back_to_coordinates(selected_centroids[i][0], selected_centroids[i][1]) nearest_stops_dep.append(nearest_stops(cent_lat, cent_long, 200)) cent_lat, cent_long = back_to_coordinates(selected_centroids[i][2], selected_centroids[i][3]) nearest_stops_arr.append(nearest_stops(cent_lat, cent_long, 200)) routes_distances = my_routes.map(lambda x: (x[0], calculate_distance_departure(x[1])['dist_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['dist_arrival'], calculate_distance_departure(x[1])['pos_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['pos_arrival'])) for i in range(len(selected_centroids)): sort_route = (routes_distances.map(lambda (v, w, x, y, z): (v, w[i] + x[i], y[i], z[i])) .sortBy(lambda x:x[1])) final_recommendation.append((sort_route .take(NUMBER_OF_RECOMMENDATIONS))) for sug in final_recommendation: for i in range(len(sug)): temp = [] for j in range(len(sug[i])): temp.append(sug[i][j]) recommendations.append(temp) recommendations.sort(key=lambda x: x[1]) recommendations_final = [] for rec in recommendations: if abs(rec[2] - rec[3]) > 1 and rec[1] < DISTANCE_THRESHOLD: recommendations_final.append(rec) recommendations = recommendations_final[:10] recommendations_to_return(recommendations) recommendations_to_db(userId, to_return)
o_id = ObjectId() line = item[0] bus_id = item[1] start_place = item[2] end_place = item[3] start_time = item[5] end_time = item[6] bus_trip_id = item[7] request_time = "null" feedback = -1 request_id = "null" next_trip = "null" booked = False trajectory = item[4] new_user_trip = { "_id":o_id, "userID" : user, "line" : line, "busID" : bus_id, "startBusStop" : start_place, "endBusStop" : end_place, "startTime" : start_time, "busTripID" : bus_trip_id, "endTime" : end_time, "feedback" : feedback, "trajectory" : trajectory, "booked" : booked } new_recommendation = { "userID": user, "userTrip": o_id } db3.UserTrip.insert(new_user_trip) db3.TravelRecommendation.insert(new_recommendation)
conditional_block
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy import math import datetime import requests import json import re from operator import itemgetter from bson.objectid import ObjectId from pyspark import SparkContext, SparkConf from pymongo import MongoClient from pyspark.mllib.clustering import KMeans, KMeansModel from numpy import array from math import sqrt from geopy.distance import vincenty # Weights W_1 = 1.2 W_2 = .8 DISTANCE_THRESHOLD = 0.3 NUM_OF_IT = 8 MIN_LATITUDE = 59.78 MAX_LATITUDE = 59.92 MIN_LONGITUDE = 17.53 MAX_LONGITUDE = 17.75 MIN_COORDINATE = -13750 MAX_COORDINATE = 13750 CIRCLE_CONVERTER = math.pi / 43200 NUMBER_OF_RECOMMENDATIONS = 5 client2 = MongoClient('130.238.15.114') db2 = client2.monad1 client3 = MongoClient('130.238.15.114') db3 = client3.monad1 start = datetime.datetime.now() dontGoBehind = 0 def time_approximation(lat1, lon1, lat2, lon2): point1 = (lat1, lon1) point2 = (lat2, lon2) distance = vincenty(point1, point2).kilometers return int(round(distance / 10 * 60)) def retrieve_requests(): TravelRequest = db2.TravelRequest return TravelRequest def populate_requests(TravelRequest):
def get_today_timetable(): TimeTable = db2.TimeTable first = datetime.datetime.today() first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0) route = TimeTable.find({'date': {'$gte': first}}) return route def populate_timetable(): route = get_today_timetable() waypoints = [] for res in route: for res1 in res['timetable']: for res2 in db2.BusTrip.find({'_id': res1}): for res3 in res2['trajectory']: for res4 in db2.BusStop.find({'_id':res3['busStop']}): waypoints.append((res3['time'],res4['latitude'], res4['longitude'], res4['name'])) routes.append((res1, waypoints)) waypoints = [] def iterator(waypoints): Waypoints = [] for res in waypoints: Waypoints.append((lat_normalizer(res[1]), lon_normalizer(res[2]), time_normalizer(to_coordinates(to_seconds(res[0]))[0]), time_normalizer(to_coordinates(to_seconds(res[0]))[1]), res[3])) return Waypoints # Converting time object to seconds def to_seconds(dt): total_time = dt.hour * 3600 + dt.minute * 60 + dt.second return total_time # Mapping seconds value to (x, y) coordinates def to_coordinates(secs): angle = float(secs) * CIRCLE_CONVERTER x = 13750 * math.cos(angle) y = 13750 * math.sin(angle) return x, y # Normalization functions def time_normalizer(value): new_value = float((float(value) - MIN_COORDINATE) / (MAX_COORDINATE - MIN_COORDINATE)) return new_value /2 def lat_normalizer(value): new_value = float((float(value) - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE)) return new_value def lon_normalizer(value): new_value = float((float(value) - MIN_LONGITUDE) / (MAX_LONGITUDE - MIN_LONGITUDE)) return new_value # Function that implements the kmeans algorithm to group users requests def kmeans(iterations, theRdd): def error(point): center = clusters.centers[clusters.predict(point)] return sqrt(sum([x**2 for x in (point - center)])) clusters = KMeans.train(theRdd, iterations, maxIterations=10, runs=10, initializationMode="random") WSSSE = theRdd.map(lambda point: error(point)).reduce(lambda x, y: x + y) return WSSSE, clusters # Function that runs iteratively the kmeans algorithm to find the best number # of clusters to group the user's request def optimalk(theRdd): results = [] for i in range(NUM_OF_IT): results.append(kmeans(i+1, theRdd)[0]) optimal = [] for i in range(NUM_OF_IT-1): optimal.append(results[i] - results[i+1]) optimal1 = [] for i in range(NUM_OF_IT-2): optimal1.append(optimal[i] - optimal[i+1]) return (optimal1.index(max(optimal1)) + 2) def back_to_coordinates(lat, lon): new_lat = (lat * (MAX_LATITUDE - MIN_LATITUDE)) + MIN_LATITUDE new_lon = (lon * (MAX_LONGITUDE - MIN_LONGITUDE)) + MIN_LONGITUDE return new_lat, new_lon def nearest_stops(lat, lon, dist): stops = [] url = "http://130.238.15.114:9998/get_nearest_stops_from_coordinates" data = {'lon': lon, 'lat': lat, 'distance': dist} headers = {'Content-type': 'application/x-www-form-urlencoded'} answer = requests.post(url, data = data, headers = headers) p = re.compile("(u'\w*')") answer = p.findall(answer.text) answer = [x.encode('UTF8') for x in answer] answer = [x[2:-1] for x in answer] answer = list(set(answer)) return answer # The function that calculate the distance from the given tuple to all the # cluster centroids and returns the minimum disstance def calculate_distance_departure(tup1): dist_departure = [] pos_departure = [] cent_num = 0 for i in selected_centroids: position = -1 min_value = 1000 min_position = 0 centroid_departure = (i[0]*W_1, i[1]*W_1,i[4]*W_2, i[5]*W_2) centroid_departure = numpy.array(centroid_departure) trajectory = [] for l in range(len(tup1)-1): position = position + 1 if(tup1[l][4] in nearest_stops_dep[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_departure - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_departure.append(result) pos_departure.append(min_position) cent_num += 1 return {"dist_departure":dist_departure,"pos_departure":pos_departure} def calculate_distance_arrival(tup1,pos_departure): dist_arrival = [] pos_arrival = [] counter=-1 cent_num = 0 for i in selected_centroids: min_value = 1000 min_position = 0 centroid_arrival = (i[2]*W_1, i[3]*W_1, i[6]*W_2, i[7]*W_2) centroid_arrival = numpy.array(centroid_arrival) counter = counter + 1 position = pos_departure[counter] for l in range(pos_departure[counter]+1, len(tup1)): position = position + 1 if(tup1[l][4] in nearest_stops_arr[cent_num]): current_stop = (numpy.array(tup1[l][:4]) * numpy.array((W_1,W_1,W_2,W_2))) distance = numpy.linalg.norm(centroid_arrival - current_stop) if (distance < min_value): min_value = distance min_position = position result = min_value dist_arrival.append(result) pos_arrival.append(min_position) cent_num += 1 return {"dist_arrival":dist_arrival,"pos_arrival":pos_arrival} def remove_duplicates(alist): return list(set(map(lambda (w, x, y, z): (w, y, z), alist))) def recommendations_to_return(alist): for rec in alist: trip = db2.BusTrip.find_one({'_id': rec[0]}) traj = trip['trajectory'][rec[2]:rec[3]+1] trajectory = [] names_only = [] for stop in traj: name_and_time = (db2.BusStop.find_one({"_id": stop['busStop']}) ['name']), stop['time'] trajectory.append(name_and_time) names_only.append(name_and_time[0]) busid = 1.0 line = trip['line'] result = (int(line), int(busid), names_only[0], names_only[-1], names_only, trajectory[0][1], trajectory[-1][1], rec[0]) to_return.append(result) def recommendations_to_db(user, alist): rec_list = [] for item in to_return: o_id = ObjectId() line = item[0] bus_id = item[1] start_place = item[2] end_place = item[3] start_time = item[5] end_time = item[6] bus_trip_id = item[7] request_time = "null" feedback = -1 request_id = "null" next_trip = "null" booked = False trajectory = item[4] new_user_trip = { "_id":o_id, "userID" : user, "line" : line, "busID" : bus_id, "startBusStop" : start_place, "endBusStop" : end_place, "startTime" : start_time, "busTripID" : bus_trip_id, "endTime" : end_time, "feedback" : feedback, "trajectory" : trajectory, "booked" : booked } new_recommendation = { "userID": user, "userTrip": o_id } db3.UserTrip.insert(new_user_trip) db3.TravelRecommendation.insert(new_recommendation) def empty_past_recommendations(): db3.TravelRecommendation.drop() if __name__ == "__main__": user_ids = [] users = [] routes = [] user_ids = [] sc = SparkContext() populate_timetable() my_routes = sc.parallelize(routes, 8) my_routes = my_routes.map(lambda (x,y): (x, iterator(y))).cache() req = retrieve_requests() populate_requests(req) start = datetime.datetime.now() initial_rdd = sc.parallelize(users, 4).cache() user_ids_rdd = (initial_rdd.map(lambda (x,y): (x,1)) .reduceByKey(lambda a, b: a + b) .collect()) ''' for user in user_ids_rdd: user_ids.append(user[0]) ''' empty_past_recommendations() user_ids = [] user_ids.append(1) for userId in user_ids: userId = 1 recommendations = [] transition = [] final_recommendation = [] selected_centroids = [] routes_distances = [] to_return = [] nearest_stops_dep = [] nearest_stops_arr = [] my_rdd = (initial_rdd.filter(lambda (x,y): x == userId) .map(lambda (x,y): y)).cache() my_rdd = (my_rdd.map(lambda x: (x[0], x[1], x[2], x[3], to_coordinates(to_seconds(x[4])), to_coordinates(to_seconds(x[5])))) .map(lambda (x1, x2, x3, x4, (x5, x6), (x7, x8)): (lat_normalizer(x1), lon_normalizer(x2), lat_normalizer(x3), lon_normalizer(x4), time_normalizer(x5), time_normalizer(x6), time_normalizer(x7), time_normalizer(x8)))) selected_centroids = kmeans(4, my_rdd)[1].centers for i in range(len(selected_centroids)): cent_lat, cent_long = back_to_coordinates(selected_centroids[i][0], selected_centroids[i][1]) nearest_stops_dep.append(nearest_stops(cent_lat, cent_long, 200)) cent_lat, cent_long = back_to_coordinates(selected_centroids[i][2], selected_centroids[i][3]) nearest_stops_arr.append(nearest_stops(cent_lat, cent_long, 200)) routes_distances = my_routes.map(lambda x: (x[0], calculate_distance_departure(x[1])['dist_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['dist_arrival'], calculate_distance_departure(x[1])['pos_departure'], calculate_distance_arrival(x[1], calculate_distance_departure(x[1])['pos_departure'])['pos_arrival'])) for i in range(len(selected_centroids)): sort_route = (routes_distances.map(lambda (v, w, x, y, z): (v, w[i] + x[i], y[i], z[i])) .sortBy(lambda x:x[1])) final_recommendation.append((sort_route .take(NUMBER_OF_RECOMMENDATIONS))) for sug in final_recommendation: for i in range(len(sug)): temp = [] for j in range(len(sug[i])): temp.append(sug[i][j]) recommendations.append(temp) recommendations.sort(key=lambda x: x[1]) recommendations_final = [] for rec in recommendations: if abs(rec[2] - rec[3]) > 1 and rec[1] < DISTANCE_THRESHOLD: recommendations_final.append(rec) recommendations = recommendations_final[:10] recommendations_to_return(recommendations) recommendations_to_db(userId, to_return)
results = db2.TravelRequest.find() for res in results: dist = time_approximation(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude']) if res['startTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['endTime'] - datetime.timedelta(minutes = dist)).time(), (res['endTime']).time()))) elif res['endTime'] == "null": users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['startTime'] + datetime.timedelta(minutes = dist)).time()))) else: users.append((res['userID'],(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude'], (res['startTime']).time(), (res['endTime']).time())))
identifier_body
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb * * The use of operators for querying data is encouraged. * The following operators are defined by NeDB and are widely used: * Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex) * The syntax is { field: { $op: value } } where $op is any comparison operator: * * $lt, $lte: less than, less than or equal * $gt, $gte: greater than, greater than or equal * $in: member of. value must be an array of values * $ne, $nin: not equal, not a member of * $exists: checks whether the document posses the property field. value should be true or false * $regex: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of $options with $regex is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the $regex operator when you need to use another operator with it. */ export default class ModelRepository implements IModelRepository { private db; constructor() { this.db = new DataStore({ filename: './build/database/nedb/storage.db', autoload: true }); } /** * Return the number of records that match the optional "where" filter. * * @param: modelName string * The database table/record to be queried. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} */ count(modelName: string, where?: IWhereFilter) { let filter; if (typeof where !== 'undefined') { filter = {}; // count all } else { filter = where; } this.db.count(filter, (err, count) => { // TODO: turn this into promise //callback(err, count); }); }; /** * Create new instance of Model, and save to database. * * @param: model Object * data Optional data argument. Can be either a single model instance or an array of instances. */ create(model) { if (typeof model !== 'undefined') { this.db.insert(model, (err, newModel) => { // TODO: turn this into promise //callback(err, newModel); }); } else { let err = new Error('Please provide a valid model!'); // TODO: turn this into promise //callback(err, null); } }; /** * Destroy all model instances that match the optional where specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyAll(modelName: string, where?: IWhereFilter) { // if (typeof where !== 'undefined' && where !== {}) { // this.db.remove(where, { multi: true}, (err, numRemoved) => { // // TODO: turn this into promise // //callback(err, numRemoved); // }); // } let err = new Error('Removing all documents not supported!'); // TODO: turn this into promise //callback(err, null); }; /** * Destroy model instance with the specified ID. * * @param: id * The ID value of model instance to delete. * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyById(id, modelName: string, where?: IWhereFilter) { if (typeof id !== 'undefined') { this.db.remove({ _id: id }, {}, (err, numRemoved) => { // TODO: turn this into promise //callback(err, numRemoved); }); } let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); }; /** * Check whether a model instance exists in database. * * @param: id * Identifier of object (primary key value). * @param: modelName string * the name of the table/record to be deleted. */ exists(id, modelName: string) {}; /** * Find all model instances that match filter specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Model instances matching the filter, or null if none found. */ find(modelName: string, where?: IWhereFilter) { let filter; // if (typeof where == 'undefined' || where === {}) { // filter = {}; // find all // } else { // filter = where; // } this.db.find(filter, (err, models) => { // TODO: turn this into promise //callback(err, models); }); }; /** * Find object by ID with an optional filter for include/fields. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional Filter JSON object */ findById(id, where?: IWhereFilter) { if (typeof id !== 'undefined') { let merge = { _id: id }; if (typeof where !== 'undefined') { // merge the two objects and pass them to db for (var key in where) { if (where.hasOwnProperty(key)) { merge[key] = where[key]; } } } this.db.findOne(merge, (err, model) => { // TODO: turn this into promise //callback(err, model); }); } else { let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); } }; /** * Update single model instance that match the where clause. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional where filter, like {} */ updateById(id, where?: IWhereFilter)
; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} * see Where filter. */ updateAll(models, where?: IWhereFilter) { this.db.update({}, {}, { multi: true }, (err, numReplaced) => { }); }; }
{}
identifier_body
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb * * The use of operators for querying data is encouraged. * The following operators are defined by NeDB and are widely used: * Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex) * The syntax is { field: { $op: value } } where $op is any comparison operator: * * $lt, $lte: less than, less than or equal * $gt, $gte: greater than, greater than or equal * $in: member of. value must be an array of values * $ne, $nin: not equal, not a member of * $exists: checks whether the document posses the property field. value should be true or false * $regex: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of $options with $regex is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the $regex operator when you need to use another operator with it. */ export default class ModelRepository implements IModelRepository { private db; constructor() { this.db = new DataStore({ filename: './build/database/nedb/storage.db', autoload: true }); } /** * Return the number of records that match the optional "where" filter. * * @param: modelName string * The database table/record to be queried. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} */ count(modelName: string, where?: IWhereFilter) { let filter; if (typeof where !== 'undefined') { filter = {}; // count all } else { filter = where; } this.db.count(filter, (err, count) => { // TODO: turn this into promise //callback(err, count); }); }; /** * Create new instance of Model, and save to database. * * @param: model Object * data Optional data argument. Can be either a single model instance or an array of instances. */ create(model) { if (typeof model !== 'undefined') { this.db.insert(model, (err, newModel) => { // TODO: turn this into promise //callback(err, newModel); }); } else { let err = new Error('Please provide a valid model!'); // TODO: turn this into promise //callback(err, null); } }; /** * Destroy all model instances that match the optional where specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyAll(modelName: string, where?: IWhereFilter) { // if (typeof where !== 'undefined' && where !== {}) { // this.db.remove(where, { multi: true}, (err, numRemoved) => { // // TODO: turn this into promise // //callback(err, numRemoved); // }); // } let err = new Error('Removing all documents not supported!'); // TODO: turn this into promise //callback(err, null); }; /** * Destroy model instance with the specified ID. * * @param: id * The ID value of model instance to delete. * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyById(id, modelName: string, where?: IWhereFilter) { if (typeof id !== 'undefined') { this.db.remove({ _id: id }, {}, (err, numRemoved) => { // TODO: turn this into promise //callback(err, numRemoved); }); } let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); }; /** * Check whether a model instance exists in database. * * @param: id * Identifier of object (primary key value). * @param: modelName string * the name of the table/record to be deleted. */ exists(id, modelName: string) {}; /** * Find all model instances that match filter specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Model instances matching the filter, or null if none found. */ find(modelName: string, where?: IWhereFilter) { let filter; // if (typeof where == 'undefined' || where === {}) { // filter = {}; // find all // } else { // filter = where; // } this.db.find(filter, (err, models) => { // TODO: turn this into promise //callback(err, models); }); }; /** * Find object by ID with an optional filter for include/fields. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional Filter JSON object */ findById(id, where?: IWhereFilter) { if (typeof id !== 'undefined') { let merge = { _id: id }; if (typeof where !== 'undefined') { // merge the two objects and pass them to db for (var key in where) { if (where.hasOwnProperty(key)) { merge[key] = where[key]; } } } this.db.findOne(merge, (err, model) => { // TODO: turn this into promise //callback(err, model); }); } else { let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); } }; /** * Update single model instance that match the where clause. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional where filter, like {} */
(id, where?: IWhereFilter) {}; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} * see Where filter. */ updateAll(models, where?: IWhereFilter) { this.db.update({}, {}, { multi: true }, (err, numReplaced) => { }); }; }
updateById
identifier_name
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb * * The use of operators for querying data is encouraged. * The following operators are defined by NeDB and are widely used: * Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex) * The syntax is { field: { $op: value } } where $op is any comparison operator: * * $lt, $lte: less than, less than or equal * $gt, $gte: greater than, greater than or equal * $in: member of. value must be an array of values * $ne, $nin: not equal, not a member of * $exists: checks whether the document posses the property field. value should be true or false * $regex: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of $options with $regex is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the $regex operator when you need to use another operator with it. */ export default class ModelRepository implements IModelRepository { private db; constructor() { this.db = new DataStore({ filename: './build/database/nedb/storage.db', autoload: true }); } /** * Return the number of records that match the optional "where" filter. * * @param: modelName string * The database table/record to be queried. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} */ count(modelName: string, where?: IWhereFilter) { let filter; if (typeof where !== 'undefined') { filter = {}; // count all } else { filter = where; } this.db.count(filter, (err, count) => { // TODO: turn this into promise //callback(err, count); }); }; /** * Create new instance of Model, and save to database. * * @param: model Object * data Optional data argument. Can be either a single model instance or an array of instances. */ create(model) { if (typeof model !== 'undefined') { this.db.insert(model, (err, newModel) => { // TODO: turn this into promise //callback(err, newModel); }); } else { let err = new Error('Please provide a valid model!'); // TODO: turn this into promise //callback(err, null); } }; /** * Destroy all model instances that match the optional where specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyAll(modelName: string, where?: IWhereFilter) { // if (typeof where !== 'undefined' && where !== {}) { // this.db.remove(where, { multi: true}, (err, numRemoved) => { // // TODO: turn this into promise // //callback(err, numRemoved); // }); // } let err = new Error('Removing all documents not supported!'); // TODO: turn this into promise //callback(err, null); }; /** * Destroy model instance with the specified ID. * * @param: id * The ID value of model instance to delete. * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyById(id, modelName: string, where?: IWhereFilter) { if (typeof id !== 'undefined')
let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); }; /** * Check whether a model instance exists in database. * * @param: id * Identifier of object (primary key value). * @param: modelName string * the name of the table/record to be deleted. */ exists(id, modelName: string) {}; /** * Find all model instances that match filter specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Model instances matching the filter, or null if none found. */ find(modelName: string, where?: IWhereFilter) { let filter; // if (typeof where == 'undefined' || where === {}) { // filter = {}; // find all // } else { // filter = where; // } this.db.find(filter, (err, models) => { // TODO: turn this into promise //callback(err, models); }); }; /** * Find object by ID with an optional filter for include/fields. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional Filter JSON object */ findById(id, where?: IWhereFilter) { if (typeof id !== 'undefined') { let merge = { _id: id }; if (typeof where !== 'undefined') { // merge the two objects and pass them to db for (var key in where) { if (where.hasOwnProperty(key)) { merge[key] = where[key]; } } } this.db.findOne(merge, (err, model) => { // TODO: turn this into promise //callback(err, model); }); } else { let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); } }; /** * Update single model instance that match the where clause. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional where filter, like {} */ updateById(id, where?: IWhereFilter) {}; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} * see Where filter. */ updateAll(models, where?: IWhereFilter) { this.db.update({}, {}, { multi: true }, (err, numReplaced) => { }); }; }
{ this.db.remove({ _id: id }, {}, (err, numRemoved) => { // TODO: turn this into promise //callback(err, numRemoved); }); }
conditional_block
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb * * The use of operators for querying data is encouraged. * The following operators are defined by NeDB and are widely used: * Operators ($lt, $lte, $gt, $gte, $in, $nin, $ne, $exists, $regex) * The syntax is { field: { $op: value } } where $op is any comparison operator: * * $lt, $lte: less than, less than or equal * $gt, $gte: greater than, greater than or equal * $in: member of. value must be an array of values * $ne, $nin: not equal, not a member of * $exists: checks whether the document posses the property field. value should be true or false * $regex: checks whether a string is matched by the regular expression. Contrary to MongoDB, the use of $options with $regex is not supported, because it doesn't give you more power than regex flags. Basic queries are more readable so only use the $regex operator when you need to use another operator with it. */ export default class ModelRepository implements IModelRepository { private db; constructor() { this.db = new DataStore({ filename: './build/database/nedb/storage.db', autoload: true }); } /** * Return the number of records that match the optional "where" filter. * * @param: modelName string * The database table/record to be queried. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} */ count(modelName: string, where?: IWhereFilter) { let filter; if (typeof where !== 'undefined') { filter = {}; // count all } else { filter = where; } this.db.count(filter, (err, count) => { // TODO: turn this into promise //callback(err, count); }); }; /** * Create new instance of Model, and save to database. * * @param: model Object * data Optional data argument. Can be either a single model instance or an array of instances. */ create(model) { if (typeof model !== 'undefined') { this.db.insert(model, (err, newModel) => { // TODO: turn this into promise //callback(err, newModel); }); } else { let err = new Error('Please provide a valid model!'); // TODO: turn this into promise //callback(err, null); } }; /** * Destroy all model instances that match the optional where specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyAll(modelName: string, where?: IWhereFilter) { // if (typeof where !== 'undefined' && where !== {}) { // this.db.remove(where, { multi: true}, (err, numRemoved) => { // // TODO: turn this into promise // //callback(err, numRemoved); // }); // } let err = new Error('Removing all documents not supported!'); // TODO: turn this into promise //callback(err, null); }; /** * Destroy model instance with the specified ID. * * @param: id * The ID value of model instance to delete. * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Optional where filter, like: {key: val, key2: {gt: 'val2'}, ...} */ destroyById(id, modelName: string, where?: IWhereFilter) { if (typeof id !== 'undefined') { this.db.remove({ _id: id }, {}, (err, numRemoved) => { // TODO: turn this into promise //callback(err, numRemoved); }); } let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); }; /** * Check whether a model instance exists in database. * * @param: id * Identifier of object (primary key value). * @param: modelName string * the name of the table/record to be deleted. */ exists(id, modelName: string) {}; /** * Find all model instances that match filter specification. * * @param: modelName string * the name of the table/record to be deleted. * @param: [where] IWhereFilter * Model instances matching the filter, or null if none found. */ find(modelName: string, where?: IWhereFilter) { let filter; // if (typeof where == 'undefined' || where === {}) { // filter = {}; // find all // } else { // filter = where; // } this.db.find(filter, (err, models) => { // TODO: turn this into promise //callback(err, models); }); }; /** * Find object by ID with an optional filter for include/fields. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional Filter JSON object */ findById(id, where?: IWhereFilter) { if (typeof id !== 'undefined') { let merge = { _id: id }; if (typeof where !== 'undefined') { // merge the two objects and pass them to db for (var key in where) { if (where.hasOwnProperty(key)) { merge[key] = where[key]; } } } this.db.findOne(merge, (err, model) => { // TODO: turn this into promise
// TODO: turn this into promise //callback(err, null); } }; /** * Update single model instance that match the where clause. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional where filter, like {} */ updateById(id, where?: IWhereFilter) {}; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} * see Where filter. */ updateAll(models, where?: IWhereFilter) { this.db.update({}, {}, { multi: true }, (err, numReplaced) => { }); }; }
//callback(err, model); }); } else { let err = new Error('Please provide an id!');
random_line_split
lmcons.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! This file contains constants used throughout the LAN Manager API header files. pub const CNLEN: ::DWORD = 15; pub const LM20_CNLEN: ::DWORD = 15; pub const DNLEN: ::DWORD = CNLEN; pub const LM20_DNLEN: ::DWORD = LM20_CNLEN; pub const UNCLEN: ::DWORD = CNLEN + 2; pub const LM20_UNCLEN: ::DWORD = LM20_CNLEN + 2; pub const NNLEN: ::DWORD = 80; pub const LM20_NNLEN: ::DWORD = 12; pub const RMLEN: ::DWORD = UNCLEN + 1 + NNLEN; pub const LM20_RMLEN: ::DWORD = LM20_UNCLEN + 1 + LM20_NNLEN; pub const SNLEN: ::DWORD = 80; pub const LM20_SNLEN: ::DWORD = 15; pub const STXTLEN: ::DWORD = 256; pub const LM20_STXTLEN: ::DWORD = 63; pub const PATHLEN: ::DWORD = 256; pub const LM20_PATHLEN: ::DWORD = 256; pub const DEVLEN: ::DWORD = 80; pub const LM20_DEVLEN: ::DWORD = 8; pub const EVLEN: ::DWORD = 16; pub const UNLEN: ::DWORD = 256; pub const LM20_UNLEN: ::DWORD = 20; pub const GNLEN: ::DWORD = UNLEN; pub const LM20_GNLEN: ::DWORD = LM20_UNLEN; pub const PWLEN: ::DWORD = 256; pub const LM20_PWLEN: ::DWORD = 14; pub const SHPWLEN: ::DWORD = 8; pub const CLTYPE_LEN: ::DWORD = 12; pub const MAXCOMMENTSZ: ::DWORD = 256; pub const LM20_MAXCOMMENTSZ: ::DWORD = 48; pub const QNLEN: ::DWORD = NNLEN; pub const LM20_QNLEN: ::DWORD = LM20_NNLEN; pub const ALERTSZ: ::DWORD = 128; pub const MAXDEVENTRIES: ::DWORD = 4 * 8; // FIXME: sizeof(int) instead of 4 pub const NETBIOS_NAME_LEN: ::DWORD = 16; pub const MAX_PREFERRED_LENGTH: ::DWORD = -1i32 as ::DWORD; pub const CRYPT_KEY_LEN: ::DWORD = 7; pub const CRYPT_TXT_LEN: ::DWORD = 8; pub const ENCRYPTED_PWLEN: usize = 16; pub const SESSION_PWLEN: ::DWORD = 24; pub const SESSION_CRYPT_KLEN: ::DWORD = 21; pub const PARM_ERROR_UNKNOWN: ::DWORD = -1i32 as ::DWORD; pub const PARM_ERROR_NONE: ::DWORD = 0; pub const PARMNUM_BASE_INFOLEVEL: ::DWORD = 1000; pub type LMSTR = ::LPWSTR; pub type LMCSTR = ::LPCWSTR; pub type NET_API_STATUS = ::DWORD;
pub const PLATFORM_ID_NT: ::DWORD = 500; pub const PLATFORM_ID_OSF: ::DWORD = 600; pub const PLATFORM_ID_VMS: ::DWORD = 700;
pub type API_RET_TYPE = NET_API_STATUS; pub const PLATFORM_ID_DOS: ::DWORD = 300; pub const PLATFORM_ID_OS2: ::DWORD = 400;
random_line_split
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tset(a,b) from table1") tset(a,b) ----------- t1 t2 t3 t1 t2 t3 t4 """ return ' '.join(sorted(set(' '.join(args).split(' ')))) tset.registered = True
Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ------------- t1 t1 t2 """ if len(args) < 2: raise functions.OperatorError("tsetdiff", "tsetdiff operator: at least two termsets should be provided") return ' '.join(sorted(set(args[0].split(' ')) - set(args[1].split(' ')))) tsetdiff.registered = True def tsetcombinations(*args): """ .. function:: tsetcombinations(termset, r) -> termset Returns all the termset combinations of length r. It is a multiset operator that returns one column but many rows. .. seealso:: * :ref:`tutmultiset` functions >>> sql("select tsetcombinations('t1 t2 t3 t4',2)") C1 ----- t1 t2 t1 t3 t1 t4 t2 t3 t2 t4 t3 t4 """ if len(args) < 1: raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: no input") tset = args[0] if not isinstance(args[1], int): raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: second argument should be integer") yield ("C1",) for p in itertools.combinations(sorted(tset.split(' ')), args[1]): first = False yield [' '.join(p)] if first: yield [''] tsetcombinations.registered = True tsetcombinations.multiset = True if not ('.' in __name__): """ This is needed to be able to test the function, put it at the end of every new function you create """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod()
def tsetdiff(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset
random_line_split
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tset(a,b) from table1") tset(a,b) ----------- t1 t2 t3 t1 t2 t3 t4 """ return ' '.join(sorted(set(' '.join(args).split(' ')))) tset.registered = True def
(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ------------- t1 t1 t2 """ if len(args) < 2: raise functions.OperatorError("tsetdiff", "tsetdiff operator: at least two termsets should be provided") return ' '.join(sorted(set(args[0].split(' ')) - set(args[1].split(' ')))) tsetdiff.registered = True def tsetcombinations(*args): """ .. function:: tsetcombinations(termset, r) -> termset Returns all the termset combinations of length r. It is a multiset operator that returns one column but many rows. .. seealso:: * :ref:`tutmultiset` functions >>> sql("select tsetcombinations('t1 t2 t3 t4',2)") C1 ----- t1 t2 t1 t3 t1 t4 t2 t3 t2 t4 t3 t4 """ if len(args) < 1: raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: no input") tset = args[0] if not isinstance(args[1], int): raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: second argument should be integer") yield ("C1",) for p in itertools.combinations(sorted(tset.split(' ')), args[1]): first = False yield [' '.join(p)] if first: yield [''] tsetcombinations.registered = True tsetcombinations.multiset = True if not ('.' in __name__): """ This is needed to be able to test the function, put it at the end of every new function you create """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod()
tsetdiff
identifier_name
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tset(a,b) from table1") tset(a,b) ----------- t1 t2 t3 t1 t2 t3 t4 """ return ' '.join(sorted(set(' '.join(args).split(' ')))) tset.registered = True def tsetdiff(*args):
tsetdiff.registered = True def tsetcombinations(*args): """ .. function:: tsetcombinations(termset, r) -> termset Returns all the termset combinations of length r. It is a multiset operator that returns one column but many rows. .. seealso:: * :ref:`tutmultiset` functions >>> sql("select tsetcombinations('t1 t2 t3 t4',2)") C1 ----- t1 t2 t1 t3 t1 t4 t2 t3 t2 t4 t3 t4 """ if len(args) < 1: raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: no input") tset = args[0] if not isinstance(args[1], int): raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: second argument should be integer") yield ("C1",) for p in itertools.combinations(sorted(tset.split(' ')), args[1]): first = False yield [' '.join(p)] if first: yield [''] tsetcombinations.registered = True tsetcombinations.multiset = True if not ('.' in __name__): """ This is needed to be able to test the function, put it at the end of every new function you create """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod()
""" .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ------------- t1 t1 t2 """ if len(args) < 2: raise functions.OperatorError("tsetdiff", "tsetdiff operator: at least two termsets should be provided") return ' '.join(sorted(set(args[0].split(' ')) - set(args[1].split(' '))))
identifier_body
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tset(a,b) from table1") tset(a,b) ----------- t1 t2 t3 t1 t2 t3 t4 """ return ' '.join(sorted(set(' '.join(args).split(' ')))) tset.registered = True def tsetdiff(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ------------- t1 t1 t2 """ if len(args) < 2: raise functions.OperatorError("tsetdiff", "tsetdiff operator: at least two termsets should be provided") return ' '.join(sorted(set(args[0].split(' ')) - set(args[1].split(' ')))) tsetdiff.registered = True def tsetcombinations(*args): """ .. function:: tsetcombinations(termset, r) -> termset Returns all the termset combinations of length r. It is a multiset operator that returns one column but many rows. .. seealso:: * :ref:`tutmultiset` functions >>> sql("select tsetcombinations('t1 t2 t3 t4',2)") C1 ----- t1 t2 t1 t3 t1 t4 t2 t3 t2 t4 t3 t4 """ if len(args) < 1: raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: no input") tset = args[0] if not isinstance(args[1], int): raise functions.OperatorError("tsetcombinations", "tsetcombinations operator: second argument should be integer") yield ("C1",) for p in itertools.combinations(sorted(tset.split(' ')), args[1]): first = False yield [' '.join(p)] if first: yield [''] tsetcombinations.registered = True tsetcombinations.multiset = True if not ('.' in __name__):
""" This is needed to be able to test the function, put it at the end of every new function you create """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod()
conditional_block
home.ts
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServiceProvider} from "../../providers/service/service"; import { ControlUserApp } from '../../control/ControlUserApp'; import { UserApp } from '../../model/UserApp'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers: [ ServiceProvider, ControlUserApp ] }) export class HomePage { constructor( public navCtrl: NavController, public movProvides: ServiceProvider, public controlUser: ControlUserApp, public userApp : UserApp ) {} gravarTeste(){ console.log('GRAVANDO DADOS'); //this.userApp = new UserApp(); //this.userApp.dsLogin = "OLA MUNDO"; //this.userApp.dsSenha = "OLA MUNDO"; //this.controlUser.save(this.userApp); console.log('DADOS GRAVADOR'); } consultaTeste(){ this.controlUser.findAll(); console.log('CONSULTOU DADOS'); } testeService(){ console.log('EFETUANDO CONSULTA'); this.movProvides.getTest().subscribe( data=>{ const response = (data as any);
console.log('RETORNO DO SERVIDOR : ' +objeto_retorno); }, error=>{ console.log('Erro executado : '+error); }) } }
console.log('RETORNO DO SERVIDOR : ' +response); console.log('RETORNO DO SERVIDOR : ' +response._body); const objeto_retorno = JSON.parse(response._body);
random_line_split
home.ts
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServiceProvider} from "../../providers/service/service"; import { ControlUserApp } from '../../control/ControlUserApp'; import { UserApp } from '../../model/UserApp'; @Component({ selector: 'page-home', templateUrl: 'home.html', providers: [ ServiceProvider, ControlUserApp ] }) export class
{ constructor( public navCtrl: NavController, public movProvides: ServiceProvider, public controlUser: ControlUserApp, public userApp : UserApp ) {} gravarTeste(){ console.log('GRAVANDO DADOS'); //this.userApp = new UserApp(); //this.userApp.dsLogin = "OLA MUNDO"; //this.userApp.dsSenha = "OLA MUNDO"; //this.controlUser.save(this.userApp); console.log('DADOS GRAVADOR'); } consultaTeste(){ this.controlUser.findAll(); console.log('CONSULTOU DADOS'); } testeService(){ console.log('EFETUANDO CONSULTA'); this.movProvides.getTest().subscribe( data=>{ const response = (data as any); console.log('RETORNO DO SERVIDOR : ' +response); console.log('RETORNO DO SERVIDOR : ' +response._body); const objeto_retorno = JSON.parse(response._body); console.log('RETORNO DO SERVIDOR : ' +objeto_retorno); }, error=>{ console.log('Erro executado : '+error); }) } }
HomePage
identifier_name
translate_smt.py
#! /usr/bin/env python import os import sys from barf.barf import BARF if __name__ == "__main__": # # Open file # try: filename = os.path.abspath("../../samples/toy/arm/branch4") barf = BARF(filename) except Exception as err: print err print "[-] Error opening file : %s" % filename sys.exit(1) # # Translate to REIL # print("[+] Translating: x86 -> REIL -> SMT...") for addr, asm_instr, reil_instrs in barf.translate(): print("0x{0:08x} : {1}".format(addr, asm_instr)) for reil_instr in reil_instrs: print("{0:14}{1}".format("", reil_instr))
# Some instructions cannot be translate to SMT, i.e, # UNKN, UNDEF, JCC. In those cases, an exception is # raised. smt_exprs = barf.smt_translator.translate(reil_instr) for smt_expr in smt_exprs: print("{0:16}{1}".format("", smt_expr)) except: pass
try:
random_line_split
translate_smt.py
#! /usr/bin/env python import os import sys from barf.barf import BARF if __name__ == "__main__": # # Open file # try: filename = os.path.abspath("../../samples/toy/arm/branch4") barf = BARF(filename) except Exception as err: print err print "[-] Error opening file : %s" % filename sys.exit(1) # # Translate to REIL # print("[+] Translating: x86 -> REIL -> SMT...") for addr, asm_instr, reil_instrs in barf.translate(): print("0x{0:08x} : {1}".format(addr, asm_instr)) for reil_instr in reil_instrs: print("{0:14}{1}".format("", reil_instr)) try: # Some instructions cannot be translate to SMT, i.e, # UNKN, UNDEF, JCC. In those cases, an exception is # raised. smt_exprs = barf.smt_translator.translate(reil_instr) for smt_expr in smt_exprs:
except: pass
print("{0:16}{1}".format("", smt_expr))
conditional_block
lint-unused-imports.rs
// Copyright 2012 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. #![feature(globs)] #![deny(unused_imports)] #![allow(dead_code)] #![allow(deprecated_owned_vector)] use cal = bar::c::cc; use std::mem::*; // shouldn't get errors for not using // everything imported // Should get errors for both 'Some' and 'None' use std::option::{Some, None}; //~ ERROR unused import //~^ ERROR unused import use test::A; //~ ERROR unused import // Be sure that if we just bring some methods into scope that they're also // counted as being used. use test::B; // Make sure this import is warned about when at least one of its imported names // is unused use std::slice::{from_fn, from_elem}; //~ ERROR unused import mod test { pub trait A { fn a(&self) {} } pub trait B { fn b(&self) {} } pub struct C; impl A for C {} impl B for C {} } mod foo { pub struct Point{x: int, y: int} pub struct Square{p: Point, h: uint, w: uint} } mod bar { // Don't ignore on 'pub use' because we're not sure if it's used or not pub use std::cmp::Eq; pub mod c { use foo::Point; use foo::Square; //~ ERROR unused import pub fn
(p: Point) -> int { return 2 * (p.x + p.y); } } #[allow(unused_imports)] mod foo { use std::cmp::Eq; } } fn main() { cal(foo::Point{x:3, y:9}); let mut a = 3; let mut b = 4; swap(&mut a, &mut b); test::C.b(); let _a = from_elem(0, 0); }
cc
identifier_name
lint-unused-imports.rs
// Copyright 2012 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. #![feature(globs)] #![deny(unused_imports)] #![allow(dead_code)] #![allow(deprecated_owned_vector)] use cal = bar::c::cc; use std::mem::*; // shouldn't get errors for not using // everything imported // Should get errors for both 'Some' and 'None' use std::option::{Some, None}; //~ ERROR unused import //~^ ERROR unused import use test::A; //~ ERROR unused import // Be sure that if we just bring some methods into scope that they're also
// Make sure this import is warned about when at least one of its imported names // is unused use std::slice::{from_fn, from_elem}; //~ ERROR unused import mod test { pub trait A { fn a(&self) {} } pub trait B { fn b(&self) {} } pub struct C; impl A for C {} impl B for C {} } mod foo { pub struct Point{x: int, y: int} pub struct Square{p: Point, h: uint, w: uint} } mod bar { // Don't ignore on 'pub use' because we're not sure if it's used or not pub use std::cmp::Eq; pub mod c { use foo::Point; use foo::Square; //~ ERROR unused import pub fn cc(p: Point) -> int { return 2 * (p.x + p.y); } } #[allow(unused_imports)] mod foo { use std::cmp::Eq; } } fn main() { cal(foo::Point{x:3, y:9}); let mut a = 3; let mut b = 4; swap(&mut a, &mut b); test::C.b(); let _a = from_elem(0, 0); }
// counted as being used. use test::B;
random_line_split
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os import http.client DIR_DATA = "data/omaps" POINTER = DIR_DATA+"/pointer.png" MAP = DIR_DATA+"/map.png" class OpenStreetMaps: """The openstreetmap.org cog""" def __init__(self,bot): self.bot = bot @commands.command(pass_context=True, no_pm=False) async def prevmap(self, ctx): """Resend the last openstreetmap.org result""" user = ctx.message.author channel = ctx.message.channel if not fileIO(MAP, "check"): await self.bot.say("` No previous map available.`") else: await self.bot.send_file(channel, MAP) @commands.command(pass_context=True, no_pm=False) async def maps(self, ctx, zoom, *country): """Search at openstreetmap.org\n zoom: upclose, street, city, country, world Type: 'none' to skip""" user = ctx.message.author channel = ctx.message.channel country = "+".join(country) longitude = 0.0 latitude = 0.0 adressNum = 1 limitResult = 0 # Set tile zoom if zoom == 'upclose': zoomMap = 18 elif zoom == 'street': zoomMap = 16 elif zoom == 'city': zoomMap = 11 elif zoom == 'country': zoomMap = 8 elif zoom == 'world': zoomMap = 2 else: zoomMap = 16 # Get input data search = country await self.bot.say("` What city?`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #http://wiki.openstreetmap.org/wiki/Nominatim await self.bot.say("` Enter your search term for the given location (building, company, address...) or type: none`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #print (search) # Get xml result from openstreetmap.org try: domain = "nominatim.openstreetmap.org" search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search) #print(domain+search) conn = http.client.HTTPConnection(domain) conn.request("GET", search) r1 = conn.getresponse() data = r1.read() conn.close() except Exception as e: await self.bot.say("` Error getting GPS data.`") print("Error getting GPS data.") print(e) return try: display_name = "-" soup = BeautifulSoup(data, 'html.parser') links = soup.findAll('place', lon=True) results = len(links) if results == 0: await self.bot.say("`No results, try to rephrase`") return #print("results:\n"+str(results)) #print("display_name:\n"+display_name) #print("longitude/latitude:\n"+str(longitude)+","+str(latitude)) except Exception as e: await self.bot.say("`Something went wrong while parsing xml data...`") print('parse XML failed') print(e) return await self.bot.send_typing(channel) if results > 1: list = "```erlang\nResults\n-\n" index = 0 for link in links: index += 1 list = list + "(" +str(index) + "): "+ link["display_name"] + "\n" list = list +"```` Enter result number...`" await self.bot.say(list) response = await self.bot.wait_for_message(author=ctx.message.author) input = response.content.lower().strip() # Set values for geotiler try: input = int(input)-1 except: input = 0 place_id = (links[input]["place_id"]) display_name = (links[input]["display_name"]) longitude = (links[input]['lon']) latitude = (links[input]['lat']) else: # Set values for geotiler place_id = (links[0]["place_id"]) display_name = (links[0]["display_name"]) longitude = (links[0]['lon']) latitude = (links[0]['lat']) await self.bot.send_typing(channel) #print([latitude, longitude, zoomMap]) map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720)) map.extent image = await geotiler.render_map_async(map) image.save(MAP) await self.bot.send_typing(channel) # Add pointer and text. savedMap = Image(filename=MAP) pointer = Image(filename=POINTER) for o in COMPOSITE_OPERATORS: w = savedMap.clone() r = pointer.clone() with Drawing() as draw: draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720 draw(w) # Text draw.fill_color = Color("#7289DA") draw.stroke_color = Color("#5370D7") draw.stroke_width = 0.3 draw.fill_opacity = 0.7 draw.stroke_opacity = 0.7 draw.font_style = 'oblique' draw.font_size = 32 splitDisplayName = display_name.split(',') # Object name/number draw.text(x=20, y=35, body=splitDisplayName[0]) draw(w) del splitDisplayName[0] # Print location info on map. line0 = "" line1 = "" draw.font_size = 18 for i in splitDisplayName: if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + "," # line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map draw.fill_color = Color("#000000") draw.stroke_color = Color("#333333") draw.fill_opacity = 0.3 draw.stroke_opacity = 0.3 draw.font_style = 'normal' draw.font_size = 14 draw.text(x=550, y=700, body="© OpenStreetMap.org") #720 draw(w) w.save(filename=MAP) await self.bot.send_file(channel, MAP) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Set-up #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def check_folders(): if not os.path.exists(DIR_DATA): print("Creating {} folder...".format(DIR_DATA)) os.makedirs(DIR_DATA) def check_files(): i
class ModuleNotFound(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.") try: from bs4 import BeautifulSoup except: raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.") try: from wand.image import Image, COMPOSITE_OPERATORS from wand.drawing import Drawing from wand.display import display from wand.image import Image from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))
f not os.path.isfile(POINTER): print("pointer.png is missing!")
identifier_body
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os import http.client DIR_DATA = "data/omaps" POINTER = DIR_DATA+"/pointer.png" MAP = DIR_DATA+"/map.png" class OpenStreetMaps: """The openstreetmap.org cog""" def __init__(self,bot): self.bot = bot @commands.command(pass_context=True, no_pm=False) async def prevmap(self, ctx): """Resend the last openstreetmap.org result""" user = ctx.message.author channel = ctx.message.channel if not fileIO(MAP, "check"): await self.bot.say("` No previous map available.`") else: await self.bot.send_file(channel, MAP) @commands.command(pass_context=True, no_pm=False) async def maps(self, ctx, zoom, *country): """Search at openstreetmap.org\n zoom: upclose, street, city, country, world Type: 'none' to skip""" user = ctx.message.author channel = ctx.message.channel country = "+".join(country) longitude = 0.0 latitude = 0.0 adressNum = 1 limitResult = 0 # Set tile zoom if zoom == 'upclose': zoomMap = 18 elif zoom == 'street': zoomMap = 16 elif zoom == 'city': zoomMap = 11 elif zoom == 'country': zoomMap = 8 elif zoom == 'world': zoomMap = 2 else: zoomMap = 16 # Get input data search = country await self.bot.say("` What city?`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #http://wiki.openstreetmap.org/wiki/Nominatim await self.bot.say("` Enter your search term for the given location (building, company, address...) or type: none`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #print (search) # Get xml result from openstreetmap.org try: domain = "nominatim.openstreetmap.org" search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search) #print(domain+search) conn = http.client.HTTPConnection(domain) conn.request("GET", search) r1 = conn.getresponse() data = r1.read() conn.close() except Exception as e: await self.bot.say("` Error getting GPS data.`") print("Error getting GPS data.") print(e) return try: display_name = "-" soup = BeautifulSoup(data, 'html.parser') links = soup.findAll('place', lon=True) results = len(links) if results == 0: await self.bot.say("`No results, try to rephrase`") return #print("results:\n"+str(results)) #print("display_name:\n"+display_name) #print("longitude/latitude:\n"+str(longitude)+","+str(latitude)) except Exception as e: await self.bot.say("`Something went wrong while parsing xml data...`") print('parse XML failed') print(e) return await self.bot.send_typing(channel) if results > 1: list = "```erlang\nResults\n-\n" index = 0 for link in links: index += 1 list = list + "(" +str(index) + "): "+ link["display_name"] + "\n" list = list +"```` Enter result number...`" await self.bot.say(list) response = await self.bot.wait_for_message(author=ctx.message.author) input = response.content.lower().strip() # Set values for geotiler try: input = int(input)-1 except: input = 0 place_id = (links[input]["place_id"]) display_name = (links[input]["display_name"]) longitude = (links[input]['lon']) latitude = (links[input]['lat']) else: # Set values for geotiler place_id = (links[0]["place_id"]) display_name = (links[0]["display_name"]) longitude = (links[0]['lon']) latitude = (links[0]['lat']) await self.bot.send_typing(channel) #print([latitude, longitude, zoomMap]) map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720)) map.extent image = await geotiler.render_map_async(map) image.save(MAP) await self.bot.send_typing(channel) # Add pointer and text. savedMap = Image(filename=MAP) pointer = Image(filename=POINTER) for o in COMPOSITE_OPERATORS: w = savedMap.clone() r = pointer.clone() with Drawing() as draw: draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720 draw(w) # Text draw.fill_color = Color("#7289DA") draw.stroke_color = Color("#5370D7") draw.stroke_width = 0.3 draw.fill_opacity = 0.7 draw.stroke_opacity = 0.7 draw.font_style = 'oblique' draw.font_size = 32 splitDisplayName = display_name.split(',') # Object name/number draw.text(x=20, y=35, body=splitDisplayName[0]) draw(w) del splitDisplayName[0] # Print location info on map. line0 = "" line1 = "" draw.font_size = 18 for i in splitDisplayName: if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + "," # line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map draw.fill_color = Color("#000000") draw.stroke_color = Color("#333333") draw.fill_opacity = 0.3 draw.stroke_opacity = 0.3 draw.font_style = 'normal' draw.font_size = 14 draw.text(x=550, y=700, body="© OpenStreetMap.org") #720 draw(w) w.save(filename=MAP) await self.bot.send_file(channel, MAP) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Set-up #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def check_folders(): if not os.path.exists(DIR_DATA): print("Creating {} folder...".format(DIR_DATA)) os.makedirs(DIR_DATA) def check_files(): if not os.path.isfile(POINTER): print("pointer.png is missing!") class ModuleNotFound(Exception): def __init__(self, m): self.message = m def _
self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.") try: from bs4 import BeautifulSoup except: raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.") try: from wand.image import Image, COMPOSITE_OPERATORS from wand.drawing import Drawing from wand.display import display from wand.image import Image from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))
_str__(
identifier_name
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os import http.client DIR_DATA = "data/omaps" POINTER = DIR_DATA+"/pointer.png" MAP = DIR_DATA+"/map.png" class OpenStreetMaps: """The openstreetmap.org cog""" def __init__(self,bot): self.bot = bot @commands.command(pass_context=True, no_pm=False) async def prevmap(self, ctx): """Resend the last openstreetmap.org result""" user = ctx.message.author channel = ctx.message.channel if not fileIO(MAP, "check"): await self.bot.say("` No previous map available.`") else: await self.bot.send_file(channel, MAP) @commands.command(pass_context=True, no_pm=False) async def maps(self, ctx, zoom, *country): """Search at openstreetmap.org\n zoom: upclose, street, city, country, world Type: 'none' to skip""" user = ctx.message.author channel = ctx.message.channel country = "+".join(country) longitude = 0.0 latitude = 0.0 adressNum = 1 limitResult = 0 # Set tile zoom if zoom == 'upclose': zoomMap = 18 elif zoom == 'street': zoomMap = 16 elif zoom == 'city': zoomMap = 11 elif zoom == 'country': zoomMap = 8 elif zoom == 'world': zoomMap = 2 else: zoomMap = 16 # Get input data search = country await self.bot.say("` What city?`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #http://wiki.openstreetmap.org/wiki/Nominatim await self.bot.say("` Enter your search term for the given location (building, company, address...) or type: none`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #print (search) # Get xml result from openstreetmap.org try: domain = "nominatim.openstreetmap.org" search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search) #print(domain+search) conn = http.client.HTTPConnection(domain) conn.request("GET", search) r1 = conn.getresponse() data = r1.read() conn.close() except Exception as e: await self.bot.say("` Error getting GPS data.`") print("Error getting GPS data.") print(e) return try: display_name = "-" soup = BeautifulSoup(data, 'html.parser') links = soup.findAll('place', lon=True) results = len(links) if results == 0: await self.bot.say("`No results, try to rephrase`") return #print("results:\n"+str(results)) #print("display_name:\n"+display_name) #print("longitude/latitude:\n"+str(longitude)+","+str(latitude)) except Exception as e: await self.bot.say("`Something went wrong while parsing xml data...`") print('parse XML failed') print(e) return await self.bot.send_typing(channel) if results > 1: list = "```erlang\nResults\n-\n" index = 0 for link in links: index += 1 list = list + "(" +str(index) + "): "+ link["display_name"] + "\n" list = list +"```` Enter result number...`" await self.bot.say(list) response = await self.bot.wait_for_message(author=ctx.message.author) input = response.content.lower().strip() # Set values for geotiler try: input = int(input)-1 except: input = 0 place_id = (links[input]["place_id"]) display_name = (links[input]["display_name"]) longitude = (links[input]['lon']) latitude = (links[input]['lat']) else: # Set values for geotiler place_id = (links[0]["place_id"]) display_name = (links[0]["display_name"]) longitude = (links[0]['lon']) latitude = (links[0]['lat']) await self.bot.send_typing(channel) #print([latitude, longitude, zoomMap]) map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720)) map.extent image = await geotiler.render_map_async(map) image.save(MAP) await self.bot.send_typing(channel) # Add pointer and text. savedMap = Image(filename=MAP) pointer = Image(filename=POINTER) for o in COMPOSITE_OPERATORS: w = savedMap.clone() r = pointer.clone() with Drawing() as draw: draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720 draw(w) # Text draw.fill_color = Color("#7289DA") draw.stroke_color = Color("#5370D7") draw.stroke_width = 0.3 draw.fill_opacity = 0.7 draw.stroke_opacity = 0.7 draw.font_style = 'oblique' draw.font_size = 32 splitDisplayName = display_name.split(',') # Object name/number draw.text(x=20, y=35, body=splitDisplayName[0]) draw(w) del splitDisplayName[0] # Print location info on map. line0 = "" line1 = "" draw.font_size = 18 for i in splitDisplayName: if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + "," # line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map draw.fill_color = Color("#000000") draw.stroke_color = Color("#333333") draw.fill_opacity = 0.3 draw.stroke_opacity = 0.3 draw.font_style = 'normal' draw.font_size = 14 draw.text(x=550, y=700, body="© OpenStreetMap.org") #720 draw(w) w.save(filename=MAP) await self.bot.send_file(channel, MAP) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Set-up #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def check_folders(): if not os.path.exists(DIR_DATA): print("Creating {} folder...".format(DIR_DATA)) os.makedirs(DIR_DATA) def check_files(): if not os.path.isfile(POINTER): print("pointer.png is missing!") class ModuleNotFound(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.") try: from bs4 import BeautifulSoup except: raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.") try: from wand.image import Image, COMPOSITE_OPERATORS from wand.drawing import Drawing from wand.display import display from wand.image import Image
from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))
random_line_split
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os import http.client DIR_DATA = "data/omaps" POINTER = DIR_DATA+"/pointer.png" MAP = DIR_DATA+"/map.png" class OpenStreetMaps: """The openstreetmap.org cog""" def __init__(self,bot): self.bot = bot @commands.command(pass_context=True, no_pm=False) async def prevmap(self, ctx): """Resend the last openstreetmap.org result""" user = ctx.message.author channel = ctx.message.channel if not fileIO(MAP, "check"): await self.bot.say("` No previous map available.`") else: await self.bot.send_file(channel, MAP) @commands.command(pass_context=True, no_pm=False) async def maps(self, ctx, zoom, *country): """Search at openstreetmap.org\n zoom: upclose, street, city, country, world Type: 'none' to skip""" user = ctx.message.author channel = ctx.message.channel country = "+".join(country) longitude = 0.0 latitude = 0.0 adressNum = 1 limitResult = 0 # Set tile zoom if zoom == 'upclose': zoomMap = 18 elif zoom == 'street': zoomMap = 16 elif zoom == 'city': zoomMap = 11 elif zoom == 'country': zoomMap = 8 elif zoom == 'world': zoomMap = 2 else: zoomMap = 16 # Get input data search = country await self.bot.say("` What city?`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #http://wiki.openstreetmap.org/wiki/Nominatim await self.bot.say("` Enter your search term for the given location (building, company, address...) or type: none`") response = await self.bot.wait_for_message(author=ctx.message.author) response = response.content.lower().strip().replace(" ", "+") if response == "none": pass else: search = search+","+response #print (search) # Get xml result from openstreetmap.org try: domain = "nominatim.openstreetmap.org" search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search) #print(domain+search) conn = http.client.HTTPConnection(domain) conn.request("GET", search) r1 = conn.getresponse() data = r1.read() conn.close() except Exception as e: await self.bot.say("` Error getting GPS data.`") print("Error getting GPS data.") print(e) return try: display_name = "-" soup = BeautifulSoup(data, 'html.parser') links = soup.findAll('place', lon=True) results = len(links) if results == 0: await self.bot.say("`No results, try to rephrase`") return #print("results:\n"+str(results)) #print("display_name:\n"+display_name) #print("longitude/latitude:\n"+str(longitude)+","+str(latitude)) except Exception as e: await self.bot.say("`Something went wrong while parsing xml data...`") print('parse XML failed') print(e) return await self.bot.send_typing(channel) if results > 1: list = "```erlang\nResults\n-\n" index = 0 for link in links: index += 1 list = list + "(" +str(index) + "): "+ link["display_name"] + "\n" list = list +"```` Enter result number...`" await self.bot.say(list) response = await self.bot.wait_for_message(author=ctx.message.author) input = response.content.lower().strip() # Set values for geotiler try: input = int(input)-1 except: input = 0 place_id = (links[input]["place_id"]) display_name = (links[input]["display_name"]) longitude = (links[input]['lon']) latitude = (links[input]['lat']) else: # Set values for geotiler place_id = (links[0]["place_id"]) display_name = (links[0]["display_name"]) longitude = (links[0]['lon']) latitude = (links[0]['lat']) await self.bot.send_typing(channel) #print([latitude, longitude, zoomMap]) map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720)) map.extent image = await geotiler.render_map_async(map) image.save(MAP) await self.bot.send_typing(channel) # Add pointer and text. savedMap = Image(filename=MAP) pointer = Image(filename=POINTER) for o in COMPOSITE_OPERATORS: w = savedMap.clone() r = pointer.clone() with Drawing() as draw: draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720 draw(w) # Text draw.fill_color = Color("#7289DA") draw.stroke_color = Color("#5370D7") draw.stroke_width = 0.3 draw.fill_opacity = 0.7 draw.stroke_opacity = 0.7 draw.font_style = 'oblique' draw.font_size = 32 splitDisplayName = display_name.split(',') # Object name/number draw.text(x=20, y=35, body=splitDisplayName[0]) draw(w) del splitDisplayName[0] # Print location info on map. line0 = "" line1 = "" draw.font_size = 18 for i in splitDisplayName:
# line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map draw.fill_color = Color("#000000") draw.stroke_color = Color("#333333") draw.fill_opacity = 0.3 draw.stroke_opacity = 0.3 draw.font_style = 'normal' draw.font_size = 14 draw.text(x=550, y=700, body="© OpenStreetMap.org") #720 draw(w) w.save(filename=MAP) await self.bot.send_file(channel, MAP) #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Set-up #-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def check_folders(): if not os.path.exists(DIR_DATA): print("Creating {} folder...".format(DIR_DATA)) os.makedirs(DIR_DATA) def check_files(): if not os.path.isfile(POINTER): print("pointer.png is missing!") class ModuleNotFound(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not installed. Do 'pip3 install geotiler --upgrade' to use this cog.") try: from bs4 import BeautifulSoup except: raise ModuleNotFound("BeautifulSoup is not installed. Do 'pip3 install BeautifulSoup --upgrade' to use this cog.") try: from wand.image import Image, COMPOSITE_OPERATORS from wand.drawing import Drawing from wand.display import display from wand.image import Image from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))
if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + ","
conditional_block
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def __init__(self, **kwargs):
def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') if len(items_to_scrape) == 0: self.log("!!! No item to parse found. It may indicate a problem with HTML !!!", level=log.ERROR) raise CloseSpider('no_item_found') for sel in items_to_scrape: girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0] baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0] baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0] date = sel.xpath('./footer/div[2]/time/a/text()').re(r'\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}')[0] text = sel.xpath('string(./div)').extract()[0] nick = sel.css('a.yazarlink').xpath('text()').extract()[0] item = Girdi() item['source'] = self.name item['baslik'] = baslik item['girdi_id'] = girdi_id item['baslik_id'] = baslik_id item['datetime'] = datetime.strptime(date, '%d.%m.%Y %H:%M') item['text'] = text item['nick'] = nick yield item current_url = response.request.url.split('/sayfa')[0] title_re = response.xpath('//title').re(r'sayfa (\d*)') current_page = int(title_re[0]) if title_re else 1 page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0]) next_page = current_page + 1 if page_count >= next_page: # if current_page < 2: yield Request('%s/sayfa/%s' % (current_url, next_page))
super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com']
identifier_body
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def
(self, **kwargs): super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com'] def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') if len(items_to_scrape) == 0: self.log("!!! No item to parse found. It may indicate a problem with HTML !!!", level=log.ERROR) raise CloseSpider('no_item_found') for sel in items_to_scrape: girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0] baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0] baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0] date = sel.xpath('./footer/div[2]/time/a/text()').re(r'\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}')[0] text = sel.xpath('string(./div)').extract()[0] nick = sel.css('a.yazarlink').xpath('text()').extract()[0] item = Girdi() item['source'] = self.name item['baslik'] = baslik item['girdi_id'] = girdi_id item['baslik_id'] = baslik_id item['datetime'] = datetime.strptime(date, '%d.%m.%Y %H:%M') item['text'] = text item['nick'] = nick yield item current_url = response.request.url.split('/sayfa')[0] title_re = response.xpath('//title').re(r'sayfa (\d*)') current_page = int(title_re[0]) if title_re else 1 page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0]) next_page = current_page + 1 if page_count >= next_page: # if current_page < 2: yield Request('%s/sayfa/%s' % (current_url, next_page))
__init__
identifier_name
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi
class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def __init__(self, **kwargs): super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com'] def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') if len(items_to_scrape) == 0: self.log("!!! No item to parse found. It may indicate a problem with HTML !!!", level=log.ERROR) raise CloseSpider('no_item_found') for sel in items_to_scrape: girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0] baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0] baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0] date = sel.xpath('./footer/div[2]/time/a/text()').re(r'\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}')[0] text = sel.xpath('string(./div)').extract()[0] nick = sel.css('a.yazarlink').xpath('text()').extract()[0] item = Girdi() item['source'] = self.name item['baslik'] = baslik item['girdi_id'] = girdi_id item['baslik_id'] = baslik_id item['datetime'] = datetime.strptime(date, '%d.%m.%Y %H:%M') item['text'] = text item['nick'] = nick yield item current_url = response.request.url.split('/sayfa')[0] title_re = response.xpath('//title').re(r'sayfa (\d*)') current_page = int(title_re[0]) if title_re else 1 page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0]) next_page = current_page + 1 if page_count >= next_page: # if current_page < 2: yield Request('%s/sayfa/%s' % (current_url, next_page))
random_line_split
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def __init__(self, **kwargs): super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com'] def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') if len(items_to_scrape) == 0: self.log("!!! No item to parse found. It may indicate a problem with HTML !!!", level=log.ERROR) raise CloseSpider('no_item_found') for sel in items_to_scrape:
current_url = response.request.url.split('/sayfa')[0] title_re = response.xpath('//title').re(r'sayfa (\d*)') current_page = int(title_re[0]) if title_re else 1 page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0]) next_page = current_page + 1 if page_count >= next_page: # if current_page < 2: yield Request('%s/sayfa/%s' % (current_url, next_page))
girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0] baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0] baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0] date = sel.xpath('./footer/div[2]/time/a/text()').re(r'\d{2}[.]\d{2}[.]\d{4} \d{2}[:]\d{2}')[0] text = sel.xpath('string(./div)').extract()[0] nick = sel.css('a.yazarlink').xpath('text()').extract()[0] item = Girdi() item['source'] = self.name item['baslik'] = baslik item['girdi_id'] = girdi_id item['baslik_id'] = baslik_id item['datetime'] = datetime.strptime(date, '%d.%m.%Y %H:%M') item['text'] = text item['nick'] = nick yield item
conditional_block
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """ Tests for error handling """ import unittest import nest import sys class ErrorTestCase(unittest.TestCase): """Tests if errors are handled correctly""" def test_Raise(self): """Error raising""" nest.ResetKernel() try: raise nest.NESTError('test') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "test" in info.__str__(): self.fail('could not pass error message to NEST!') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_StackUnderFlow(self): """Stack underflow""" nest.ResetKernel() try: nest.sr('clear ;') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "StackUnderflow" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_DivisionByZero(self): """Division by zero""" nest.ResetKernel() try: nest.sr('1 0 div') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "DivisionByZero" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownNode(self): """Unknown node""" nest.ResetKernel() try: nest.Connect([99],[99]) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownNode" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownModel(self): """Unknown model name""" nest.ResetKernel() try:
self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def suite(): suite = unittest.makeSuite(ErrorTestCase,'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__():
random_line_split
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """ Tests for error handling """ import unittest import nest import sys class ErrorTestCase(unittest.TestCase): """Tests if errors are handled correctly""" def test_Raise(self): """Error raising""" nest.ResetKernel() try: raise nest.NESTError('test') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "test" in info.__str__(): self.fail('could not pass error message to NEST!') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_StackUnderFlow(self): """Stack underflow""" nest.ResetKernel() try: nest.sr('clear ;') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "StackUnderflow" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_DivisionByZero(self): """Division by zero""" nest.ResetKernel() try: nest.sr('1 0 div') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "DivisionByZero" in info.__str__():
# another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownNode(self): """Unknown node""" nest.ResetKernel() try: nest.Connect([99],[99]) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownNode" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownModel(self): """Unknown model name""" nest.ResetKernel() try: nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def suite(): suite = unittest.makeSuite(ErrorTestCase,'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
self.fail('wrong error message')
conditional_block
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """ Tests for error handling """ import unittest import nest import sys class ErrorTestCase(unittest.TestCase): """Tests if errors are handled correctly""" def test_Raise(self): """Error raising""" nest.ResetKernel() try: raise nest.NESTError('test') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "test" in info.__str__(): self.fail('could not pass error message to NEST!') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_StackUnderFlow(self):
def test_DivisionByZero(self): """Division by zero""" nest.ResetKernel() try: nest.sr('1 0 div') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "DivisionByZero" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownNode(self): """Unknown node""" nest.ResetKernel() try: nest.Connect([99],[99]) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownNode" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownModel(self): """Unknown model name""" nest.ResetKernel() try: nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def suite(): suite = unittest.makeSuite(ErrorTestCase,'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
"""Stack underflow""" nest.ResetKernel() try: nest.sr('clear ;') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "StackUnderflow" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown')
identifier_body
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. """ Tests for error handling """ import unittest import nest import sys class ErrorTestCase(unittest.TestCase): """Tests if errors are handled correctly""" def test_Raise(self): """Error raising""" nest.ResetKernel() try: raise nest.NESTError('test') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "test" in info.__str__(): self.fail('could not pass error message to NEST!') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_StackUnderFlow(self): """Stack underflow""" nest.ResetKernel() try: nest.sr('clear ;') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "StackUnderflow" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_DivisionByZero(self): """Division by zero""" nest.ResetKernel() try: nest.sr('1 0 div') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "DivisionByZero" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownNode(self): """Unknown node""" nest.ResetKernel() try: nest.Connect([99],[99]) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownNode" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def
(self): """Unknown model name""" nest.ResetKernel() try: nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__(): self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def suite(): suite = unittest.makeSuite(ErrorTestCase,'test') return suite if __name__ == "__main__": runner = unittest.TextTestRunner(verbosity=2) runner.run(suite())
test_UnknownModel
identifier_name
svg.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use style_traits::ParseError; /// The fallback of an SVG paint server value. #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintFallback<C> { /// The `none` keyword. None, /// A magic value that represents no fallback specified and serializes to /// the empty string. #[css(skip)] Unset, /// A color. Color(C), } pub use self::GenericSVGPaintFallback as SVGPaintFallback; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(Url))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct GenericSVGPaint<Color, Url> { /// The paint source. pub kind: GenericSVGPaintKind<Color, Url>, /// The fallback color. pub fallback: GenericSVGPaintFallback<Color>, } pub use self::GenericSVGPaint as SVGPaint; impl<C, U> Default for SVGPaint<C, U> { fn default() -> Self { Self { kind: SVGPaintKind::None, fallback: SVGPaintFallback::Unset, } } } /// An SVG paint value without the fallback. /// /// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the /// context properties have a fallback as well. #[animation(no_bound(U))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintKind<C, U> { /// `none` #[animation(error)] None, /// `<color>` Color(C), /// `url(...)` #[animation(error)] PaintServer(U), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } pub use self::GenericSVGPaintKind as SVGPaintKind; impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let kind = SVGPaintKind::parse(context, input)?; if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..)) { return Ok(SVGPaint { kind, fallback: SVGPaintFallback::Unset, }); } let fallback = input .try(|i| SVGPaintFallback::parse(context, i)) .unwrap_or(SVGPaintFallback::Unset); Ok(SVGPaint { kind, fallback }) } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>), /// `context-value` ContextValue, } pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray; /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf,
ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, } pub use self::GenericSVGOpacity as SVGOpacity;
PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero,
random_line_split
svg.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use style_traits::ParseError; /// The fallback of an SVG paint server value. #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintFallback<C> { /// The `none` keyword. None, /// A magic value that represents no fallback specified and serializes to /// the empty string. #[css(skip)] Unset, /// A color. Color(C), } pub use self::GenericSVGPaintFallback as SVGPaintFallback; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(Url))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct GenericSVGPaint<Color, Url> { /// The paint source. pub kind: GenericSVGPaintKind<Color, Url>, /// The fallback color. pub fallback: GenericSVGPaintFallback<Color>, } pub use self::GenericSVGPaint as SVGPaint; impl<C, U> Default for SVGPaint<C, U> { fn
() -> Self { Self { kind: SVGPaintKind::None, fallback: SVGPaintFallback::Unset, } } } /// An SVG paint value without the fallback. /// /// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the /// context properties have a fallback as well. #[animation(no_bound(U))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintKind<C, U> { /// `none` #[animation(error)] None, /// `<color>` Color(C), /// `url(...)` #[animation(error)] PaintServer(U), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } pub use self::GenericSVGPaintKind as SVGPaintKind; impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let kind = SVGPaintKind::parse(context, input)?; if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..)) { return Ok(SVGPaint { kind, fallback: SVGPaintFallback::Unset, }); } let fallback = input .try(|i| SVGPaintFallback::parse(context, i)) .unwrap_or(SVGPaintFallback::Unset); Ok(SVGPaint { kind, fallback }) } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>), /// `context-value` ContextValue, } pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray; /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, } pub use self::GenericSVGOpacity as SVGOpacity;
default
identifier_name
svg.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use style_traits::ParseError; /// The fallback of an SVG paint server value. #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintFallback<C> { /// The `none` keyword. None, /// A magic value that represents no fallback specified and serializes to /// the empty string. #[css(skip)] Unset, /// A color. Color(C), } pub use self::GenericSVGPaintFallback as SVGPaintFallback; /// An SVG paint value /// /// <https://www.w3.org/TR/SVG2/painting.html#SpecifyingPaint> #[animation(no_bound(Url))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C)] pub struct GenericSVGPaint<Color, Url> { /// The paint source. pub kind: GenericSVGPaintKind<Color, Url>, /// The fallback color. pub fallback: GenericSVGPaintFallback<Color>, } pub use self::GenericSVGPaint as SVGPaint; impl<C, U> Default for SVGPaint<C, U> { fn default() -> Self { Self { kind: SVGPaintKind::None, fallback: SVGPaintFallback::Unset, } } } /// An SVG paint value without the fallback. /// /// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the /// context properties have a fallback as well. #[animation(no_bound(U))] #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGPaintKind<C, U> { /// `none` #[animation(error)] None, /// `<color>` Color(C), /// `url(...)` #[animation(error)] PaintServer(U), /// `context-fill` ContextFill, /// `context-stroke` ContextStroke, } pub use self::GenericSVGPaintKind as SVGPaintKind; impl<C: Parse, U: Parse> Parse for SVGPaint<C, U> { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Self, ParseError<'i>> { let kind = SVGPaintKind::parse(context, input)?; if matches!(kind, SVGPaintKind::None | SVGPaintKind::Color(..))
let fallback = input .try(|i| SVGPaintFallback::parse(context, i)) .unwrap_or(SVGPaintFallback::Unset); Ok(SVGPaint { kind, fallback }) } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] pub enum SVGLength<L> { /// `<length> | <percentage> | <number>` LengthPercentage(L), /// `context-value` #[animation(error)] ContextValue, } /// Generic value for stroke-dasharray. #[derive( Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGStrokeDashArray<L> { /// `[ <length> | <percentage> | <number> ]#` #[css(comma)] Values(#[css(if_empty = "none", iterable)] crate::OwnedSlice<L>), /// `context-value` ContextValue, } pub use self::GenericSVGStrokeDashArray as SVGStrokeDashArray; /// An SVG opacity value accepts `context-{fill,stroke}-opacity` in /// addition to opacity value. #[derive( Animate, Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] ContextStrokeOpacity, } pub use self::GenericSVGOpacity as SVGOpacity;
{ return Ok(SVGPaint { kind, fallback: SVGPaintFallback::Unset, }); }
conditional_block
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # - output: 'ello_world_good_morning_see_you_hello_great' # # ### Reference: # - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py # - https://github.com/aymericdamien/TensorFlow-Examples # - https://hunkim.github.io/ml/ # # ### Comment: # - 단어 단위가 아닌 문자 단위로 훈련함 # - 하나의 example만 훈련에 사용함 # : 하나의 example을 windowing하여 여러 샘플을 만들어 냄 (새로운 샘플의 크기는 window_size) # - Cell의 종류는 BasicRNNCell을 사용함 (첫번째 Reference 참조) # - dynamic_rnn방식 사용 (기존 tf.nn.rnn보다 더 시간-계산 효율적이라고 함) # - AdamOptimizer를 사용 # In[1]: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import random # Input/Ouput data char_raw = 'hello_world_good_morning_see_you_hello_great' char_list = sorted(list(set(char_raw))) char_to_idx = {c: i for i, c in enumerate(char_list)} idx_to_char = {i: c for i, c in enumerate(char_list)} char_data = [char_to_idx[c] for c in char_raw] char_data_one_hot = tf.one_hot(char_data, depth=len( char_list), on_value=1., off_value=0., axis=1, dtype=tf.float32) char_input = char_data_one_hot[:-1, :] # 'hello_world_good_morning_see_you_hello_grea' char_output = char_data_one_hot[1:, :] # 'ello_world_good_morning_see_you_hello_great' with tf.Session() as sess: char_input = char_input.eval() char_output = char_output.eval() # In[2]: # Learning parameters learning_rate = 0.001 max_iter = 1000 # Network Parameters n_input_dim = char_input.shape[1] n_input_len = char_input.shape[0] n_output_dim = char_output.shape[1] n_output_len = char_output.shape[0] n_hidden = 100 n_window = 2 # number of characters in one window (like a mini-batch) # TensorFlow graph # (batch_size) x (time_step) x (input_dimension) x_data = tf.placeholder(tf.float32, [None, None, n_input_dim]) # (batch_size) x (time_step) x (output_dimension) y_data = tf.placeholder(tf.float32, [None, None, n_output_dim]) # Parameters weights = { 'out': tf.Variable(tf.truncated_normal([n_hidden, n_output_dim])) } biases = { 'out': tf.Variable(tf.truncated_normal([n_output_dim])) } # In[3]: def make_window_batch(x, y, window_size): ''' This function will generate samples based on window_size from (x, y) Although (x, y) is one example, it will create multiple examples with the length of window_size x: (time_step) x (input_dim) y: (time_step) x (output_dim) x_out: (total_batch) x (batch_size) x (window_size) x (input_dim) y_out: (total_batch) x (batch_size) x (window_size) x (output_dim) total_batch x batch_size <= examples ''' # (batch_size) x (window_size) x (dim) # n_examples is calculated by sliding one character with window_size n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size x_batch = np.empty((n_examples, window_size, x.shape[1])) y_batch = np.empty((n_examples, window_size, y.shape[1])) for i in range(n_examples): x_batch[i, :, :] = x[i:i + window_size, :] y_batch[i, :, :] = y[i:i + window_size, :] z = list(zip(x_batch, y_batch)) random.shuffle(z) x_batch, y_batch = zip(*z) x_batch = np.array(x_batch) y_batch = np.array(y_batch) # (total_batch) x (batch_size) x (window_size) x (dim) # total_batch is set to 1 (no mini-batch) x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2])) y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2])) return x_new, y_new, n_examples # In[4]: def RNN(x, weights, biases): cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # Make RNNCell outputs, states = tf.nn.dynamic_rnn(cell, x, time_major=False, dtype=tf.float32) ''' **Notes on tf.nn.dynamic_rnn** - 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'outputs' can have the same shape as 'x' (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'states' is the final state, determined by batch and hidden_dim ''' # outputs[-1] is outputs for the last example in the mini-batch return tf.matmul(outputs[-1], weights['out']) + biases['out'] def softmax(x): rowmax = np.max(x, axis=1) x -= rowmax.reshape((x.shape[0] ,1)) # for numerical stability x = np.exp(x) sum_x = np.sum(x, axis=1).reshape((x.shape[0],1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(max_iter): loss = 0 x_batch, y_batch, n_examples = make_window_batch(char_input, char_output, n_window) for ibatch in range(x_batch.shape[0]): x_train = x_batch[ibatch, :, :].reshape((1,-1,n_input_dim)) y_train = y_batch[ibatch, :, :].reshape((1,-1,n_output_dim)) x_test = char_input.reshape((1, n_input_len, n_input_dim)) y_test = char_output.reshape((1, n_input_len, n_input_dim)) c, _ = sess.run([cost, optimizer], feed_dict={ x_data: x_train, y_data: y_train}) p = sess.run(pred, feed_dict={x_data: x_test, y_data: y_test}) loss += c mean_mse = loss / n_examples if i == (max_iter-1): pred_act = softmax(p) if (i+1) % 100 == 0: pred_out = np.argmax(p, axis=1) accuracy = np.sum(char_data[1:] == pred_out)/n_output_len*100 print('Epoch:{:>4}/{},'.format(i+1,max_iter), 'Cost:{:.4f},'.format(mean_mse), 'Acc:{:>.1f},'.format(accuracy), 'Predict:', ''.join([idx_to_char[i] for i in pred_out])) # In[6]: # Probability plot
fontsize=20, y=1.5) plt.ylabel('Character List', fontsize=20) plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma')) fig.colorbar(plot, fraction=0.015, pad=0.04) plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15) plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(len(char_list))], fontsize=15) ax.xaxis.tick_top() # Annotate for i, idx in zip(range(len(pred_out)), pred_out): annotation = idx_to_char[idx] ax.annotate(annotation, xy=(i-0.2, idx+0.2), fontsize=12) plt.show() # f.savefig('result_' + idx + '.png')
fig, ax = plt.subplots() fig.set_size_inches(15,20) plt.title('Input Sequence', y=1.08, fontsize=20) plt.xlabel('Probability of Next Character(y) Given Current One(x)'+ '\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy),
random_line_split
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # - output: 'ello_world_good_morning_see_you_hello_great' # # ### Reference: # - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py # - https://github.com/aymericdamien/TensorFlow-Examples # - https://hunkim.github.io/ml/ # # ### Comment: # - 단어 단위가 아닌 문자 단위로 훈련함 # - 하나의 example만 훈련에 사용함 # : 하나의 example을 windowing하여 여러 샘플을 만들어 냄 (새로운 샘플의 크기는 window_size) # - Cell의 종류는 BasicRNNCell을 사용함 (첫번째 Reference 참조) # - dynamic_rnn방식 사용 (기존 tf.nn.rnn보다 더 시간-계산 효율적이라고 함) # - AdamOptimizer를 사용 # In[1]: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import random # Input/Ouput data char_raw = 'hello_world_good_morning_see_you_hello_great' char_list = sorted(list(set(char_raw))) char_to_idx = {c: i for i, c in enumerate(char_list)} idx_to_char = {i: c for i, c in enumerate(char_list)} char_data = [char_to_idx[c] for c in char_raw] char_data_one_hot = tf.one_hot(char_data, depth=len( char_list), on_value=1., off_value=0., axis=1, dtype=tf.float32) char_input = char_data_one_hot[:-1, :] # 'hello_world_good_morning_see_you_hello_grea' char_output = char_data_one_hot[1:, :] # 'ello_world_good_morning_see_you_hello_great' with tf.Session() as sess: char_input = char_input.eval() char_output = char_output.eval() # In[2]: # Learning parameters learning_rate = 0.001 max_iter = 1000 # Network Parameters n_input_dim = char_input.shape[1] n_input_len = char_input.shape[0] n_output_dim = char_output.shape[1] n_output_len = char_output.shape[0] n_hidden = 100 n_window = 2 # number of characters in one window (like a mini-batch) # TensorFlow graph # (batch_size) x (time_step) x (input_dimension) x_data = tf.placeholder(tf.float32, [None, None, n_input_dim]) # (batch_size) x (time_step) x (output_dimension) y_data = tf.placeholder(tf.float32, [None, None, n_output_dim]) # Parameters weights = { 'out': tf.Variable(tf.truncated_normal([n_hidden, n_output_dim])) } biases = { 'out': tf.Variable(tf.truncated_normal([n_output_dim])) } # In[3]: def make_window_batch(x, y, window_size): ''' This function will generate samples based on window_size from (x, y) Although (x, y) is one example, it will create multiple examples with the length of window_size x: (time_step) x (input_dim) y: (time_step) x (output_dim) x_out: (total_batch) x (batch_size) x (window_size) x (input_dim) y_out: (total_batch) x (batch_size) x (window_size) x (output_dim) total_batch x batch_size <= examples ''' # (batch_size) x (window_size) x (dim) # n_examples is calculated by sliding one character with window_size n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size x_batch = np.empty((n_examples, window_size, x.shape[1])) y_batch = np.empty((n_examples, window_size, y.shape[1])) for i in range(n_examples): x_batch[i, :, :] = x[i:i + window_size, :] y_batch[i, :, :] = y[i:i + window_size, :] z = list(zip(x_batch, y_batch)) random.shuffle(z) x_bat
# (total_batch) x (batch_size) x (window_size) x (dim) # total_batch is set to 1 (no mini-batch) x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2])) y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2])) return x_new, y_new, n_examples # In[4]: def RNN(x, weights, biases): cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # Make RNNCell outputs, states = tf.nn.dynamic_rnn(cell, x, time_major=False, dtype=tf.float32) ''' **Notes on tf.nn.dynamic_rnn** - 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'outputs' can have the same shape as 'x' (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'states' is the final state, determined by batch and hidden_dim ''' # outputs[-1] is outputs for the last example in the mini-batch return tf.matmul(outputs[-1], weights['out']) + biases['out'] def softmax(x): rowmax = np.max(x, axis=1) x -= rowmax.reshape((x.shape[0] ,1)) # for numerical stability x = np.exp(x) sum_x = np.sum(x, axis=1).reshape((x.shape[0],1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(max_iter): loss = 0 x_batch, y_batch, n_examples = make_window_batch(char_input, char_output, n_window) for ibatch in range(x_batch.shape[0]): x_train = x_batch[ibatch, :, :].reshape((1,-1,n_input_dim)) y_train = y_batch[ibatch, :, :].reshape((1,-1,n_output_dim)) x_test = char_input.reshape((1, n_input_len, n_input_dim)) y_test = char_output.reshape((1, n_input_len, n_input_dim)) c, _ = sess.run([cost, optimizer], feed_dict={ x_data: x_train, y_data: y_train}) p = sess.run(pred, feed_dict={x_data: x_test, y_data: y_test}) loss += c mean_mse = loss / n_examples if i == (max_iter-1): pred_act = softmax(p) if (i+1) % 100 == 0: pred_out = np.argmax(p, axis=1) accuracy = np.sum(char_data[1:] == pred_out)/n_output_len*100 print('Epoch:{:>4}/{},'.format(i+1,max_iter), 'Cost:{:.4f},'.format(mean_mse), 'Acc:{:>.1f},'.format(accuracy), 'Predict:', ''.join([idx_to_char[i] for i in pred_out])) # In[6]: # Probability plot fig, ax = plt.subplots() fig.set_size_inches(15,20) plt.title('Input Sequence', y=1.08, fontsize=20) plt.xlabel('Probability of Next Character(y) Given Current One(x)'+ '\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy), fontsize=20, y=1.5) plt.ylabel('Character List', fontsize=20) plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma')) fig.colorbar(plot, fraction=0.015, pad=0.04) plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15) plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(len(char_list))], fontsize=15) ax.xaxis.tick_top() # Annotate for i, idx in zip(range(len(pred_out)), pred_out): annotation = idx_to_char[idx] ax.annotate(annotation, xy=(i-0.2, idx+0.2), fontsize=12) plt.show() # f.savefig('result_' + idx + '.png')
ch, y_batch = zip(*z) x_batch = np.array(x_batch) y_batch = np.array(y_batch)
conditional_block
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # - output: 'ello_world_good_morning_see_you_hello_great' # # ### Reference: # - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py # - https://github.com/aymericdamien/TensorFlow-Examples # - https://hunkim.github.io/ml/ # # ### Comment: # - 단어 단위가 아닌 문자 단위로 훈련함 # - 하나의 example만 훈련에 사용함 # : 하나의 example을 windowing하여 여러 샘플을 만들어 냄 (새로운 샘플의 크기는 window_size) # - Cell의 종류는 BasicRNNCell을 사용함 (첫번째 Reference 참조) # - dynamic_rnn방식 사용 (기존 tf.nn.rnn보다 더 시간-계산 효율적이라고 함) # - AdamOptimizer를 사용 # In[1]: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import random # Input/Ouput data char_raw = 'hello_world_good_morning_see_you_hello_great' char_list = sorted(list(set(char_raw))) char_to_idx = {c: i for i, c in enumerate(char_list)} idx_to_char = {i: c for i, c in enumerate(char_list)} char_data = [char_to_idx[c] for c in char_raw] char_data_one_hot = tf.one_hot(char_data, depth=len( char_list), on_value=1., off_value=0., axis=1, dtype=tf.float32) char_input = char_data_one_hot[:-1, :] # 'hello_world_good_morning_see_you_hello_grea' char_output = char_data_one_hot[1:, :] # 'ello_world_good_morning_see_you_hello_great' with tf.Session() as sess: char_input = char_input.eval() char_output = char_output.eval() # In[2]: # Learning parameters learning_rate = 0.001 max_iter = 1000 # Network Parameters n_input_dim = char_input.shape[1] n_input_len = char_input.shape[0] n_output_dim = char_output.shape[1] n_output_len = char_output.shape[0] n_hidden = 100 n_window = 2 # number of characters in one window (like a mini-batch) # TensorFlow graph # (batch_size) x (time_step) x (input_dimension) x_data = tf.placeholder(tf.float32, [None, None, n_input_dim]) # (batch_size) x (time_step) x (output_dimension) y_data = tf.placeholder(tf.float32, [None, None, n_output_dim]) # Parameters weights = { 'out': tf.Variable(tf.truncated_normal([n_hidden, n_output_dim])) } biases = { 'out': tf.Variable(tf.truncated_normal([n_output_dim])) } # In[3]: def make_window_batch(x, y, window_size): ''' This function will generate samples based on window_size from (x, y) Although (x, y) is one example, it will create multiple examples with the length of window_size x: (time_step) x (input_dim) y: (time_step) x (output_dim) x_out: (total_batch) x (batch_size) x (window_size) x (input_dim) y_out: (total_batch) x (batch_size) x (window_size) x (output_dim) total_batch x batch_size <= examples ''' # (batch_size) x (window_size) x (dim) # n_examples is calculated by sliding one character with window_size n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size x_batch = np.empty((n_examples, window_size, x.shape[1])) y_batch = np.empty((n_examples, window_size, y.shape[1])) for i in range(n_examples): x_batch[i, :, :] = x[i:i + window_size, :] y_batch[i, :, :] = y[i:i + window_size, :] z = list(zip(x_batch, y_batch)) random.shuffle(z) x_batch, y_batch = zip(*z) x_batch = np.array(x_batch) y_batch = np.array(y_batch) # (total_batch) x (batch_size) x (window_size) x (dim) # total_batch is set to 1 (no mini-batch) x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2])) y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2])) return x_new, y_new, n_examples # In[4]: def RNN(x, weights, biases): cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # Make RNNCell outputs, states = tf.nn.dynamic_rnn(cell, x, time_major=False, dtype=tf.float32) ''' **Notes on tf
e((x.shape[0],1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(max_iter): loss = 0 x_batch, y_batch, n_examples = make_window_batch(char_input, char_output, n_window) for ibatch in range(x_batch.shape[0]): x_train = x_batch[ibatch, :, :].reshape((1,-1,n_input_dim)) y_train = y_batch[ibatch, :, :].reshape((1,-1,n_output_dim)) x_test = char_input.reshape((1, n_input_len, n_input_dim)) y_test = char_output.reshape((1, n_input_len, n_input_dim)) c, _ = sess.run([cost, optimizer], feed_dict={ x_data: x_train, y_data: y_train}) p = sess.run(pred, feed_dict={x_data: x_test, y_data: y_test}) loss += c mean_mse = loss / n_examples if i == (max_iter-1): pred_act = softmax(p) if (i+1) % 100 == 0: pred_out = np.argmax(p, axis=1) accuracy = np.sum(char_data[1:] == pred_out)/n_output_len*100 print('Epoch:{:>4}/{},'.format(i+1,max_iter), 'Cost:{:.4f},'.format(mean_mse), 'Acc:{:>.1f},'.format(accuracy), 'Predict:', ''.join([idx_to_char[i] for i in pred_out])) # In[6]: # Probability plot fig, ax = plt.subplots() fig.set_size_inches(15,20) plt.title('Input Sequence', y=1.08, fontsize=20) plt.xlabel('Probability of Next Character(y) Given Current One(x)'+ '\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy), fontsize=20, y=1.5) plt.ylabel('Character List', fontsize=20) plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma')) fig.colorbar(plot, fraction=0.015, pad=0.04) plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15) plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(len(char_list))], fontsize=15) ax.xaxis.tick_top() # Annotate for i, idx in zip(range(len(pred_out)), pred_out): annotation = idx_to_char[idx] ax.annotate(annotation, xy=(i-0.2, idx+0.2), fontsize=12) plt.show() # f.savefig('result_' + idx + '.png')
.nn.dynamic_rnn** - 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'outputs' can have the same shape as 'x' (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'states' is the final state, determined by batch and hidden_dim ''' # outputs[-1] is outputs for the last example in the mini-batch return tf.matmul(outputs[-1], weights['out']) + biases['out'] def softmax(x): rowmax = np.max(x, axis=1) x -= rowmax.reshape((x.shape[0] ,1)) # for numerical stability x = np.exp(x) sum_x = np.sum(x, axis=1).reshap
identifier_body
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # - output: 'ello_world_good_morning_see_you_hello_great' # # ### Reference: # - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py # - https://github.com/aymericdamien/TensorFlow-Examples # - https://hunkim.github.io/ml/ # # ### Comment: # - 단어 단위가 아닌 문자 단위로 훈련함 # - 하나의 example만 훈련에 사용함 # : 하나의 example을 windowing하여 여러 샘플을 만들어 냄 (새로운 샘플의 크기는 window_size) # - Cell의 종류는 BasicRNNCell을 사용함 (첫번째 Reference 참조) # - dynamic_rnn방식 사용 (기존 tf.nn.rnn보다 더 시간-계산 효율적이라고 함) # - AdamOptimizer를 사용 # In[1]: import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import random # Input/Ouput data char_raw = 'hello_world_good_morning_see_you_hello_great' char_list = sorted(list(set(char_raw))) char_to_idx = {c: i for i, c in enumerate(char_list)} idx_to_char = {i: c for i, c in enumerate(char_list)} char_data = [char_to_idx[c] for c in char_raw] char_data_one_hot = tf.one_hot(char_data, depth=len( char_list), on_value=1., off_value=0., axis=1, dtype=tf.float32) char_input = char_data_one_hot[:-1, :] # 'hello_world_good_morning_see_you_hello_grea' char_output = char_data_one_hot[1:, :] # 'ello_world_good_morning_see_you_hello_great' with tf.Session() as sess: char_input = char_input.eval() char_output = char_output.eval() # In[2]: # Learning parameters learning_rate = 0.001 max_iter = 1000 # Network Parameters n_input_dim = char_input.shape[1] n_input_len = char_input.shape[0] n_output_dim = char_output.shape[1] n_output_len = char_output.shape[0] n_hidden = 100 n_window = 2 # number of characters in one window (like a mini-batch) # TensorFlow graph # (batch_size) x (time_step) x (input_dimension) x_data = tf.placeholder(tf.float32, [None, None, n_input_dim]) # (batch_size) x (time_step) x (output_dimension) y_data = tf.placeholder(tf.float32, [None, None, n_output_dim]) # Parameters weights = { 'out': tf.Variable(tf.truncated_normal([n_hidden, n_output_dim])) } biases = { 'out': tf.Variable(tf.truncated_normal([n_output_dim])) } # In[3]: def make_window_batch(x, y, window_size): ''' This function will generate samples based on window_size from (x, y) Although (x, y) is one example, it will create multiple examples with the length of window_size x: (time_step) x (input_dim) y: (time_step) x (output_dim) x_out: (total_batch) x (batch_size) x (window_size) x (input_dim) y_out: (total_batch) x (batch_size) x (window_size) x (output_dim) total_batch x batch_size <= examples ''' # (batch_size) x (window_size) x (dim) # n_examples is calculated by sliding one character with window_size n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size x_batch = np.empty((n_examples, window_size, x.shape[1])) y_batch = np.empty((n_examples, window_size, y.shape[1])) for i in range(n_examples): x_batch[i, :, :] = x[i:i + window_size, :] y_batch[i, :, :] = y[i:i + window_size, :] z = list(zip(x_batch, y_batch)) random.shuffle(z) x_batch, y_batch = zip(*z) x_batch = np.array(x_batch) y_batch = np.array(y_batch) # (total_batch) x (batch_size) x (window_size) x (dim) # total_batch is set to 1 (no mini-batch) x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2])) y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2])) return x_new, y_new, n_examples # In[4]: def RNN(x, weights, biases): cell = tf.contrib.rnn.BasicRNNCell(n_hidden) # Make RNNCell outputs, states = tf.nn.dynamic_rnn(cell, x, time_major=False, dtype=tf.float32) ''' **Notes on tf.nn.dynamic_rnn** - 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'outputs' can have the same shape as 'x' (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'states' is the final state, determined by batch and hidden_dim ''' # outputs[-1] is outputs for the last example in the mini-batch return tf.matmul(outputs[-1], weights['out']) + biases['out'] def softmax(x): rowmax = np.max(x, axis=1) x -= rowmax.reshape((x.shape[0] ,1)) # for numerical stability x = np.exp(x) sum_x = np.sum(x, axis=1).reshape((x.s
,1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(max_iter): loss = 0 x_batch, y_batch, n_examples = make_window_batch(char_input, char_output, n_window) for ibatch in range(x_batch.shape[0]): x_train = x_batch[ibatch, :, :].reshape((1,-1,n_input_dim)) y_train = y_batch[ibatch, :, :].reshape((1,-1,n_output_dim)) x_test = char_input.reshape((1, n_input_len, n_input_dim)) y_test = char_output.reshape((1, n_input_len, n_input_dim)) c, _ = sess.run([cost, optimizer], feed_dict={ x_data: x_train, y_data: y_train}) p = sess.run(pred, feed_dict={x_data: x_test, y_data: y_test}) loss += c mean_mse = loss / n_examples if i == (max_iter-1): pred_act = softmax(p) if (i+1) % 100 == 0: pred_out = np.argmax(p, axis=1) accuracy = np.sum(char_data[1:] == pred_out)/n_output_len*100 print('Epoch:{:>4}/{},'.format(i+1,max_iter), 'Cost:{:.4f},'.format(mean_mse), 'Acc:{:>.1f},'.format(accuracy), 'Predict:', ''.join([idx_to_char[i] for i in pred_out])) # In[6]: # Probability plot fig, ax = plt.subplots() fig.set_size_inches(15,20) plt.title('Input Sequence', y=1.08, fontsize=20) plt.xlabel('Probability of Next Character(y) Given Current One(x)'+ '\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy), fontsize=20, y=1.5) plt.ylabel('Character List', fontsize=20) plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma')) fig.colorbar(plot, fraction=0.015, pad=0.04) plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15) plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(len(char_list))], fontsize=15) ax.xaxis.tick_top() # Annotate for i, idx in zip(range(len(pred_out)), pred_out): annotation = idx_to_char[idx] ax.annotate(annotation, xy=(i-0.2, idx+0.2), fontsize=12) plt.show() # f.savefig('result_' + idx + '.png')
hape[0]
identifier_name
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); repl } /// Defines the command, timeout, and prompt settings. /// Wraps a rexpect::session::PtySession. expecting the prompt after launch. fn new_() -> Result<REPL> { let timeout: u64 = 30_000; let prompt: &'static str = "REXPECT> "; let mut command = Command::new("../target/debug/gluon"); command .args(&["-i", "--color", "never", "--prompt", prompt]) .env("GLUON_PATH", ".."); let mut session = spawn_command(command, Some(timeout))?; session.exp_string(prompt)?; Ok(REPL { session, prompt }) } fn test(&mut self, send: &str, expect: Option<&str>) { self.test_(send, expect) .unwrap_or_else(|err| panic!("{}", err)); } /// Ensures certain lines are expected to reduce race conditions. /// If no ouput is expected or desired to be tested, pass it an Option::None, /// causing rexpect to wait for the next prompt. fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> { self.session.send_line(send)?; self.session.exp_string(send)?; if let Some(string) = expect { self.session.exp_string(string)?; } self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?; self.session.exp_eof()?; Ok(()) } } #[test] fn prompt() { let _repl = REPL::new(); } #[test] fn quit() { let mut repl = REPL::new(); repl.quit(); } #[test] fn hello_world() { let mut repl = REPL::new(); repl.test("let io = import! std.io", None); repl.test("io.println \"Hello world\"", Some("Hello world")); } #[test] fn expression_types() { let mut repl = REPL::new(); repl.test(":t 5", Some("Int")); repl.test(":t 5 + 5", Some("Int")); repl.test(":t \"gluon\"", Some("String")); } #[test] fn names() { let mut repl = REPL::new(); repl.test( ":i std.prelude.show", Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"), ); } #[test] fn comments() { let mut repl = REPL::new(); repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3")); repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3")); } #[test] fn
() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.test("let record_2 = {x = 1 .. record }", None); repl.test("record_2.x", Some("1")); repl.test("record_2.pi", Some("3.14")); } #[test] fn arrays() { let mut repl = REPL::new(); repl.test("let array = import! std.array", None); repl.test("array.len [1, 2, 3]", Some("3")); } #[test] fn comment() { let mut repl = REPL::new(); repl.test("// test", None); } #[test] fn error_reports_correct_line() { let mut repl = REPL::new(); repl.test("let { x } = {}", Some("let { x } = {}")); } #[test] fn import() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); } #[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
if_expressions
identifier_name
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); repl } /// Defines the command, timeout, and prompt settings. /// Wraps a rexpect::session::PtySession. expecting the prompt after launch. fn new_() -> Result<REPL> { let timeout: u64 = 30_000; let prompt: &'static str = "REXPECT> "; let mut command = Command::new("../target/debug/gluon"); command .args(&["-i", "--color", "never", "--prompt", prompt]) .env("GLUON_PATH", ".."); let mut session = spawn_command(command, Some(timeout))?; session.exp_string(prompt)?; Ok(REPL { session, prompt }) } fn test(&mut self, send: &str, expect: Option<&str>) { self.test_(send, expect) .unwrap_or_else(|err| panic!("{}", err)); } /// Ensures certain lines are expected to reduce race conditions. /// If no ouput is expected or desired to be tested, pass it an Option::None, /// causing rexpect to wait for the next prompt. fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> { self.session.send_line(send)?; self.session.exp_string(send)?; if let Some(string) = expect { self.session.exp_string(string)?; } self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?; self.session.exp_eof()?; Ok(()) } } #[test] fn prompt() { let _repl = REPL::new(); } #[test] fn quit() { let mut repl = REPL::new(); repl.quit(); } #[test] fn hello_world() { let mut repl = REPL::new(); repl.test("let io = import! std.io", None); repl.test("io.println \"Hello world\"", Some("Hello world")); } #[test] fn expression_types() { let mut repl = REPL::new(); repl.test(":t 5", Some("Int")); repl.test(":t 5 + 5", Some("Int")); repl.test(":t \"gluon\"", Some("String")); } #[test] fn names() { let mut repl = REPL::new(); repl.test( ":i std.prelude.show", Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"), ); } #[test] fn comments() { let mut repl = REPL::new(); repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3")); repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3")); } #[test] fn if_expressions() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.test("let record_2 = {x = 1 .. record }", None); repl.test("record_2.x", Some("1")); repl.test("record_2.pi", Some("3.14")); } #[test] fn arrays() { let mut repl = REPL::new(); repl.test("let array = import! std.array", None); repl.test("array.len [1, 2, 3]", Some("3")); } #[test] fn comment() { let mut repl = REPL::new(); repl.test("// test", None); } #[test] fn error_reports_correct_line() { let mut repl = REPL::new(); repl.test("let { x } = {}", Some("let { x } = {}")); } #[test] fn import()
#[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
{ let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); }
identifier_body
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); repl } /// Defines the command, timeout, and prompt settings. /// Wraps a rexpect::session::PtySession. expecting the prompt after launch. fn new_() -> Result<REPL> { let timeout: u64 = 30_000; let prompt: &'static str = "REXPECT> "; let mut command = Command::new("../target/debug/gluon"); command .args(&["-i", "--color", "never", "--prompt", prompt]) .env("GLUON_PATH", ".."); let mut session = spawn_command(command, Some(timeout))?; session.exp_string(prompt)?; Ok(REPL { session, prompt }) } fn test(&mut self, send: &str, expect: Option<&str>) { self.test_(send, expect) .unwrap_or_else(|err| panic!("{}", err)); } /// Ensures certain lines are expected to reduce race conditions. /// If no ouput is expected or desired to be tested, pass it an Option::None, /// causing rexpect to wait for the next prompt. fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> { self.session.send_line(send)?; self.session.exp_string(send)?; if let Some(string) = expect {
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?; self.session.exp_eof()?; Ok(()) } } #[test] fn prompt() { let _repl = REPL::new(); } #[test] fn quit() { let mut repl = REPL::new(); repl.quit(); } #[test] fn hello_world() { let mut repl = REPL::new(); repl.test("let io = import! std.io", None); repl.test("io.println \"Hello world\"", Some("Hello world")); } #[test] fn expression_types() { let mut repl = REPL::new(); repl.test(":t 5", Some("Int")); repl.test(":t 5 + 5", Some("Int")); repl.test(":t \"gluon\"", Some("String")); } #[test] fn names() { let mut repl = REPL::new(); repl.test( ":i std.prelude.show", Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"), ); } #[test] fn comments() { let mut repl = REPL::new(); repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3")); repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3")); } #[test] fn if_expressions() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.test("let record_2 = {x = 1 .. record }", None); repl.test("record_2.x", Some("1")); repl.test("record_2.pi", Some("3.14")); } #[test] fn arrays() { let mut repl = REPL::new(); repl.test("let array = import! std.array", None); repl.test("array.len [1, 2, 3]", Some("3")); } #[test] fn comment() { let mut repl = REPL::new(); repl.test("// test", None); } #[test] fn error_reports_correct_line() { let mut repl = REPL::new(); repl.test("let { x } = {}", Some("let { x } = {}")); } #[test] fn import() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); } #[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
self.session.exp_string(string)?; }
random_line_split
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); repl } /// Defines the command, timeout, and prompt settings. /// Wraps a rexpect::session::PtySession. expecting the prompt after launch. fn new_() -> Result<REPL> { let timeout: u64 = 30_000; let prompt: &'static str = "REXPECT> "; let mut command = Command::new("../target/debug/gluon"); command .args(&["-i", "--color", "never", "--prompt", prompt]) .env("GLUON_PATH", ".."); let mut session = spawn_command(command, Some(timeout))?; session.exp_string(prompt)?; Ok(REPL { session, prompt }) } fn test(&mut self, send: &str, expect: Option<&str>) { self.test_(send, expect) .unwrap_or_else(|err| panic!("{}", err)); } /// Ensures certain lines are expected to reduce race conditions. /// If no ouput is expected or desired to be tested, pass it an Option::None, /// causing rexpect to wait for the next prompt. fn test_(&mut self, send: &str, expect: Option<&str>) -> Result<()> { self.session.send_line(send)?; self.session.exp_string(send)?; if let Some(string) = expect
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?; self.session.exp_eof()?; Ok(()) } } #[test] fn prompt() { let _repl = REPL::new(); } #[test] fn quit() { let mut repl = REPL::new(); repl.quit(); } #[test] fn hello_world() { let mut repl = REPL::new(); repl.test("let io = import! std.io", None); repl.test("io.println \"Hello world\"", Some("Hello world")); } #[test] fn expression_types() { let mut repl = REPL::new(); repl.test(":t 5", Some("Int")); repl.test(":t 5 + 5", Some("Int")); repl.test(":t \"gluon\"", Some("String")); } #[test] fn names() { let mut repl = REPL::new(); repl.test( ":i std.prelude.show", Some("std.prelude.show: forall a . [std.show.Show a] -> a -> String"), ); } #[test] fn comments() { let mut repl = REPL::new(); repl.test("1 + 2 // Calls the + function on 1 and 2", Some("3")); repl.test("1 + 2 /* Calls the + function on 1 and 2 */", Some("3")); } #[test] fn if_expressions() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.test("let record_2 = {x = 1 .. record }", None); repl.test("record_2.x", Some("1")); repl.test("record_2.pi", Some("3.14")); } #[test] fn arrays() { let mut repl = REPL::new(); repl.test("let array = import! std.array", None); repl.test("array.len [1, 2, 3]", Some("3")); } #[test] fn comment() { let mut repl = REPL::new(); repl.test("// test", None); } #[test] fn error_reports_correct_line() { let mut repl = REPL::new(); repl.test("let { x } = {}", Some("let { x } = {}")); } #[test] fn import() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); } #[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
{ self.session.exp_string(string)?; }
conditional_block
variables_a.js
var searchData= [ ['page_5flinks',['PAGE_LINKS',['../classtemplates_1_1_settings_temp.html#a813be5a9356d17a9165b65f97b40aadc',1,'templates::SettingsTemp']]], ['page_5fprofile',['PAGE_PROFILE',['../classtemplates_1_1_settings_temp.html#a6dd91f0c75e530b35b11f4e6f7da5b89',1,'templates::SettingsTemp']]], ['page_5fsend_5fbadge',['PAGE_SEND_BADGE',['../class_inc_1_1_pages_1_1_admin.html#a5c39703d0b0855e56b949bc054f0abcc',1,'Inc::Pages::Admin']]], ['page_5fsettings',['PAGE_SETTINGS',['../class_inc_1_1_pages_1_1_admin.html#a67d53c06cb7326f7c1c96b9531a252d3',1,'Inc::Pages::Admin']]], ['post_5ftype_5fbadges',['POST_TYPE_BADGES',['../class_inc_1_1_pages_1_1_admin.html#ade2910e39b04e32c2380a61fb5da37ed',1,'Inc::Pages::Admin']]],
['preview',['PREVIEW',['../classtemplates_1_1_get_badge_temp.html#a99aa8032b2d02e1841d39b0854e68053',1,'templates::GetBadgeTemp']]] ];
['post_5ftype_5fclass_5fjl',['POST_TYPE_CLASS_JL',['../class_inc_1_1_pages_1_1_admin.html#a6ac1dded84bc08a46965aad4dbf21b12',1,'Inc::Pages::Admin']]],
random_line_split
aspect_frame.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>. //! A frame that constrains its child to a particular aspect ratio
use glib::translate::ToGlibPtr; use gtk::cast::GTK_ASPECTFRAME; use gtk::{self, ffi}; use glib::to_gboolean; /// AspectFrame — A frame that constrains its child to a particular aspect ratio struct_Widget!(AspectFrame); impl AspectFrame { pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> { let tmp_pointer = unsafe { ffi::gtk_aspect_frame_new(label.borrow_to_glib().0, x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)) }; check_pointer!(tmp_pointer, AspectFrame) } pub fn set(&mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)); } } } impl_drop!(AspectFrame); impl_TraitWidget!(AspectFrame); impl gtk::FrameTrait for AspectFrame {} impl gtk::ContainerTrait for AspectFrame {} impl_widget_events!(AspectFrame);
use libc::c_float;
random_line_split
aspect_frame.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>. //! A frame that constrains its child to a particular aspect ratio use libc::c_float; use glib::translate::ToGlibPtr; use gtk::cast::GTK_ASPECTFRAME; use gtk::{self, ffi}; use glib::to_gboolean; /// AspectFrame — A frame that constrains its child to a particular aspect ratio struct_Widget!(AspectFrame); impl AspectFrame { pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> { let tmp_pointer = unsafe { ffi::gtk_aspect_frame_new(label.borrow_to_glib().0, x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)) }; check_pointer!(tmp_pointer, AspectFrame) } pub fn se
mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)); } } } impl_drop!(AspectFrame); impl_TraitWidget!(AspectFrame); impl gtk::FrameTrait for AspectFrame {} impl gtk::ContainerTrait for AspectFrame {} impl_widget_events!(AspectFrame);
t(&
identifier_name
aspect_frame.rs
// This file is part of rgtk. // // rgtk 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 3 of the License, or // (at your option) any later version. // // rgtk 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 rgtk. If not, see <http://www.gnu.org/licenses/>. //! A frame that constrains its child to a particular aspect ratio use libc::c_float; use glib::translate::ToGlibPtr; use gtk::cast::GTK_ASPECTFRAME; use gtk::{self, ffi}; use glib::to_gboolean; /// AspectFrame — A frame that constrains its child to a particular aspect ratio struct_Widget!(AspectFrame); impl AspectFrame { pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> Option<AspectFrame> {
pub fn set(&mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)); } } } impl_drop!(AspectFrame); impl_TraitWidget!(AspectFrame); impl gtk::FrameTrait for AspectFrame {} impl gtk::ContainerTrait for AspectFrame {} impl_widget_events!(AspectFrame);
let tmp_pointer = unsafe { ffi::gtk_aspect_frame_new(label.borrow_to_glib().0, x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)) }; check_pointer!(tmp_pointer, AspectFrame) }
identifier_body
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSpliter { name: s.as_bytes(), pos: 0, } } } impl<'a> Iterator for NameSpliter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { if self.pos == self.name.len() { return None; } // skip all prefix '_' while self.pos < self.name.len() && self.name[self.pos] == b'_' { self.pos += 1; } let mut pos = self.name.len(); let mut upper_len = 0; let mut meet_lower = false; for i in self.pos..self.name.len() { let c = self.name[i]; if (b'A'..=b'Z').contains(&c) { if meet_lower { // So it should be AaA or aaA pos = i; break; } upper_len += 1; } else if c == b'_' { pos = i; break; } else { meet_lower = true; if upper_len > 1 { // So it should be AAa pos = i - 1; break; } } } let s = str::from_utf8(&self.name[self.pos..pos]).unwrap(); self.pos = pos; Some(s) } } /// Adjust method name to follow rust-guidelines. pub fn to_snake_case(name: &str) -> String { let mut snake_method_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { snake_method_name.push_str(&s.to_lowercase()); snake_method_name.push('_'); } snake_method_name.pop(); snake_method_name } #[cfg(feature = "protobuf-codec")] pub fn to_camel_case(name: &str) -> String { let mut camel_case_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { let mut chs = s.chars(); camel_case_name.extend(chs.next().unwrap().to_uppercase()); camel_case_name.push_str(&s[1..].to_lowercase()); } camel_case_name } pub fn fq_grpc(item: &str) -> String { format!("::grpcio::{}", item) } pub enum MethodType { Unary, ClientStreaming, ServerStreaming, Duplex, } impl fmt::Display for MethodType { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { MethodType::Unary => "MethodType::Unary", MethodType::ClientStreaming => "MethodType::ClientStreaming", MethodType::ServerStreaming => "MethodType::ServerStreaming", MethodType::Duplex => "MethodType::Duplex", } ) } } #[cfg(test)] mod test { #[test] fn test_snake_name() { let cases = vec![ ("AsyncRequest", "async_request"), ("asyncRequest", "async_request"), ("async_request", "async_request"), ("createID", "create_id"), ("AsyncRClient", "async_r_client"), ("CreateIDForReq", "create_id_for_req"), ("Create_ID_For_Req", "create_id_for_req"), ("Create_ID_For__Req", "create_id_for_req"), ("ID", "id"), ("id", "id"), ]; for (origin, exp) in cases { let res = super::to_snake_case(&origin); assert_eq!(res, exp); } } #[test] #[cfg(feature = "protobuf-codec")] fn test_camel_name() { let cases = vec![ ("AsyncRequest", "AsyncRequest"), ("asyncRequest", "AsyncRequest"), ("async_request", "AsyncRequest"), ("createID", "CreateId"), ("AsyncRClient", "AsyncRClient"), ("async_r_client", "AsyncRClient"), ("CreateIDForReq", "CreateIdForReq"), ("Create_ID_For_Req", "CreateIdForReq"), ("Create_ID_For__Req", "CreateIdForReq"), ("ID", "Id"), ("id", "Id"), ]; for (origin, exp) in cases { let res = super::to_camel_case(&origin); assert_eq!(res, exp); } } }
fmt
identifier_name
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSpliter { name: s.as_bytes(), pos: 0, } } } impl<'a> Iterator for NameSpliter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { if self.pos == self.name.len() { return None; } // skip all prefix '_' while self.pos < self.name.len() && self.name[self.pos] == b'_' { self.pos += 1; } let mut pos = self.name.len(); let mut upper_len = 0; let mut meet_lower = false; for i in self.pos..self.name.len() { let c = self.name[i]; if (b'A'..=b'Z').contains(&c)
else if c == b'_' { pos = i; break; } else { meet_lower = true; if upper_len > 1 { // So it should be AAa pos = i - 1; break; } } } let s = str::from_utf8(&self.name[self.pos..pos]).unwrap(); self.pos = pos; Some(s) } } /// Adjust method name to follow rust-guidelines. pub fn to_snake_case(name: &str) -> String { let mut snake_method_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { snake_method_name.push_str(&s.to_lowercase()); snake_method_name.push('_'); } snake_method_name.pop(); snake_method_name } #[cfg(feature = "protobuf-codec")] pub fn to_camel_case(name: &str) -> String { let mut camel_case_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { let mut chs = s.chars(); camel_case_name.extend(chs.next().unwrap().to_uppercase()); camel_case_name.push_str(&s[1..].to_lowercase()); } camel_case_name } pub fn fq_grpc(item: &str) -> String { format!("::grpcio::{}", item) } pub enum MethodType { Unary, ClientStreaming, ServerStreaming, Duplex, } impl fmt::Display for MethodType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { MethodType::Unary => "MethodType::Unary", MethodType::ClientStreaming => "MethodType::ClientStreaming", MethodType::ServerStreaming => "MethodType::ServerStreaming", MethodType::Duplex => "MethodType::Duplex", } ) } } #[cfg(test)] mod test { #[test] fn test_snake_name() { let cases = vec![ ("AsyncRequest", "async_request"), ("asyncRequest", "async_request"), ("async_request", "async_request"), ("createID", "create_id"), ("AsyncRClient", "async_r_client"), ("CreateIDForReq", "create_id_for_req"), ("Create_ID_For_Req", "create_id_for_req"), ("Create_ID_For__Req", "create_id_for_req"), ("ID", "id"), ("id", "id"), ]; for (origin, exp) in cases { let res = super::to_snake_case(&origin); assert_eq!(res, exp); } } #[test] #[cfg(feature = "protobuf-codec")] fn test_camel_name() { let cases = vec![ ("AsyncRequest", "AsyncRequest"), ("asyncRequest", "AsyncRequest"), ("async_request", "AsyncRequest"), ("createID", "CreateId"), ("AsyncRClient", "AsyncRClient"), ("async_r_client", "AsyncRClient"), ("CreateIDForReq", "CreateIdForReq"), ("Create_ID_For_Req", "CreateIdForReq"), ("Create_ID_For__Req", "CreateIdForReq"), ("ID", "Id"), ("id", "Id"), ]; for (origin, exp) in cases { let res = super::to_camel_case(&origin); assert_eq!(res, exp); } } }
{ if meet_lower { // So it should be AaA or aaA pos = i; break; } upper_len += 1; }
conditional_block
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSpliter { name: s.as_bytes(), pos: 0, } } } impl<'a> Iterator for NameSpliter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { if self.pos == self.name.len() { return None; } // skip all prefix '_' while self.pos < self.name.len() && self.name[self.pos] == b'_' { self.pos += 1; } let mut pos = self.name.len(); let mut upper_len = 0; let mut meet_lower = false; for i in self.pos..self.name.len() { let c = self.name[i]; if (b'A'..=b'Z').contains(&c) { if meet_lower { // So it should be AaA or aaA pos = i; break; } upper_len += 1; } else if c == b'_' { pos = i; break; } else { meet_lower = true; if upper_len > 1 { // So it should be AAa pos = i - 1; break; } } } let s = str::from_utf8(&self.name[self.pos..pos]).unwrap(); self.pos = pos; Some(s) } } /// Adjust method name to follow rust-guidelines. pub fn to_snake_case(name: &str) -> String { let mut snake_method_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { snake_method_name.push_str(&s.to_lowercase()); snake_method_name.push('_'); } snake_method_name.pop(); snake_method_name } #[cfg(feature = "protobuf-codec")] pub fn to_camel_case(name: &str) -> String { let mut camel_case_name = String::with_capacity(name.len()); for s in NameSpliter::new(name) { let mut chs = s.chars(); camel_case_name.extend(chs.next().unwrap().to_uppercase()); camel_case_name.push_str(&s[1..].to_lowercase()); } camel_case_name } pub fn fq_grpc(item: &str) -> String { format!("::grpcio::{}", item) } pub enum MethodType { Unary, ClientStreaming, ServerStreaming, Duplex, } impl fmt::Display for MethodType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { MethodType::Unary => "MethodType::Unary", MethodType::ClientStreaming => "MethodType::ClientStreaming", MethodType::ServerStreaming => "MethodType::ServerStreaming", MethodType::Duplex => "MethodType::Duplex", } ) } } #[cfg(test)] mod test {
("async_request", "async_request"), ("createID", "create_id"), ("AsyncRClient", "async_r_client"), ("CreateIDForReq", "create_id_for_req"), ("Create_ID_For_Req", "create_id_for_req"), ("Create_ID_For__Req", "create_id_for_req"), ("ID", "id"), ("id", "id"), ]; for (origin, exp) in cases { let res = super::to_snake_case(&origin); assert_eq!(res, exp); } } #[test] #[cfg(feature = "protobuf-codec")] fn test_camel_name() { let cases = vec![ ("AsyncRequest", "AsyncRequest"), ("asyncRequest", "AsyncRequest"), ("async_request", "AsyncRequest"), ("createID", "CreateId"), ("AsyncRClient", "AsyncRClient"), ("async_r_client", "AsyncRClient"), ("CreateIDForReq", "CreateIdForReq"), ("Create_ID_For_Req", "CreateIdForReq"), ("Create_ID_For__Req", "CreateIdForReq"), ("ID", "Id"), ("id", "Id"), ]; for (origin, exp) in cases { let res = super::to_camel_case(&origin); assert_eq!(res, exp); } } }
#[test] fn test_snake_name() { let cases = vec![ ("AsyncRequest", "async_request"), ("asyncRequest", "async_request"),
random_line_split
setup.py
#!/usr/bin/python import os import sys extra_opts = {'test_suite': 'tests'} extra_deps = [] extra_test_deps = [] if sys.version_info[:2] == (2, 6):
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages try: with open('README.rst', 'r') as fd: extra_opts['long_description'] = fd.read() except IOError: pass # Install without README.rst setup( name='mongo-orchestration', version='0.4.dev0', author='MongoDB, Inc.', author_email='mongodb-user@googlegroups.com', description='Restful service for managing MongoDB servers', keywords=['mongo-orchestration', 'mongodb', 'mongo', 'rest', 'testing'], license="http://www.apache.org/licenses/LICENSE-2.0.html", platforms=['any'], url='https://github.com/10gen/mongo-orchestration', install_requires=['pymongo>=3.0.2', 'bottle>=0.12.7', 'CherryPy>=3.5.0'] + extra_deps, tests_require=['coverage>=3.5'] + extra_test_deps, packages=find_packages(exclude=('tests',)), package_data={ 'mongo_orchestration': [ os.path.join('configurations', config_dir, '*.json') for config_dir in ('servers', 'replica_sets', 'sharded_clusters') ] + [os.path.join('lib', 'client.pem')] }, classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython" ], entry_points={ 'console_scripts': [ 'mongo-orchestration = mongo_orchestration.server:main' ] }, **extra_opts )
extra_deps.append('argparse') extra_deps.append('simplejson') extra_test_deps.append('unittest2') extra_opts['test_suite'] = 'unittest2.collector'
conditional_block