text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Store the time of login.
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%', hintText : 'Email', top : 20 }); var passwordField = Ti.UI.createTextField({ width : '80%', hintText : 'Password', passwordMask : true }); var loginButton = Ti.UI.createButton({ width : '60%', title : 'Login' }); self.add(emailField); self.add(passwordField); self.add(loginButton); loginButton.addEventListener('click', function() { NetworkHelper.pingSurveyWebWithoutLoggedInCheck( onSuccess = function() { var email = emailField.getValue().trim(); var password = passwordField.getValue(); var client = Ti.Network.createHTTPClient(); client.autoRedirect = false; client.onload = function() { var cookie = this.getResponseHeader('Set-Cookie'); Ti.App.Properties.setString('auth_cookie', cookie); Ti.App.Properties.setString('auth_cookie_created_at', new Date().toString()); self.fireEvent('login:completed'); } client.onerror = function() { alert("Login failed, sorry!"); } client.open('POST', loginUrl); client.send({ username : email, password : password }); }); }); return self; } module.exports = LoginView;
var TopLevelView = require('ui/common/components/TopLevelView'); var NetworkHelper = require('helpers/NetworkHelper'); function LoginView() { var loginUrl = Ti.App.Properties.getString('server_url') + '/api/login'; var self = new TopLevelView('Login'); var emailField = Ti.UI.createTextField({ width : '80%', hintText : 'Email', top : 20 }); var passwordField = Ti.UI.createTextField({ width : '80%', hintText : 'Password', passwordMask : true }); var loginButton = Ti.UI.createButton({ width : '60%', title : 'Login' }); self.add(emailField); self.add(passwordField); self.add(loginButton); loginButton.addEventListener('click', function() { NetworkHelper.pingSurveyWebWithoutLoggedInCheck( onSuccess = function() { var email = emailField.getValue().trim(); var password = passwordField.getValue(); var client = Ti.Network.createHTTPClient(); client.autoRedirect = false; client.onload = function() { var cookie = this.getResponseHeader('Set-Cookie'); Ti.App.Properties.setString('auth_cookie', cookie); self.fireEvent('login:completed'); } client.onerror = function() { alert("Login failed, sorry!"); } client.open('POST', loginUrl); client.send({ username : email, password : password }); }); }); return self; } module.exports = LoginView;
Enhance GAE compat by removing some realpath()
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Resource; /** * FileResource represents a resource stored on the filesystem. * * The resource can be a file or a directory. * * @author Fabien Potencier <[email protected]> */ class FileResource implements ResourceInterface, \Serializable { /** * @var string|false */ private $resource; /** * Constructor. * * @param string $resource The file path to the resource */ public function __construct($resource) { $this->resource = realpath($resource) ?: (file_exists($resource) ? $resource : false); } /** * {@inheritdoc} */ public function __toString() { return (string) $this->resource; } /** * {@inheritdoc} */ public function getResource() { return $this->resource; } /** * {@inheritdoc} */ public function isFresh($timestamp) { if (false === $this->resource || !file_exists($this->resource)) { return false; } return filemtime($this->resource) <= $timestamp; } public function serialize() { return serialize($this->resource); } public function unserialize($serialized) { $this->resource = unserialize($serialized); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Config\Resource; /** * FileResource represents a resource stored on the filesystem. * * The resource can be a file or a directory. * * @author Fabien Potencier <[email protected]> */ class FileResource implements ResourceInterface, \Serializable { /** * @var string|false */ private $resource; /** * Constructor. * * @param string $resource The file path to the resource */ public function __construct($resource) { $this->resource = realpath($resource); } /** * {@inheritdoc} */ public function __toString() { return (string) $this->resource; } /** * {@inheritdoc} */ public function getResource() { return $this->resource; } /** * {@inheritdoc} */ public function isFresh($timestamp) { if (false === $this->resource || !file_exists($this->resource)) { return false; } return filemtime($this->resource) <= $timestamp; } public function serialize() { return serialize($this->resource); } public function unserialize($serialized) { $this->resource = unserialize($serialized); } }
Use last hour to avoid empty interval
// Delete these three lines once you have your environment variables set // The environment-configured 'keen' variable is set in layout.erb Keen.ready(function(){ // ---------------------------------------- // Pageviews Area Chart // ---------------------------------------- var repos_timeline = new Keen.Query("maximum", { eventCollection: "repository_snapshots", targetProperty: "stargazers_count", interval: "daily", groupBy: "full_name", timeframe: "last_210_hours" }); keenClient.draw(repos_timeline, document.getElementById("chart-01"), { chartType: "areachart", title: false, height: 250, width: "auto", chartOptions: { chartArea: { height: "85%", left: "5%", top: "5%", width: "80%" }, isStacked: false } }); var repos_now = new Keen.Query("maximum", { eventCollection: "repository_snapshots", targetProperty: "stargazers_count", groupBy: "full_name", timeframe: "last_1_hour" }); keenClient.draw(repos_now, document.getElementById("chart-02"), { chartType: "piechart", title: false, height: 250, width: "auto", chartOptions: { chartArea: { height: "85%", left: "5%", top: "5%", width: "100%" } } }); });
// Delete these three lines once you have your environment variables set // The environment-configured 'keen' variable is set in layout.erb Keen.ready(function(){ // ---------------------------------------- // Pageviews Area Chart // ---------------------------------------- var repos_timeline = new Keen.Query("maximum", { eventCollection: "repository_snapshots", targetProperty: "stargazers_count", interval: "daily", groupBy: "full_name", timeframe: "this_210_hours" }); keenClient.draw(repos_timeline, document.getElementById("chart-01"), { chartType: "areachart", title: false, height: 250, width: "auto", chartOptions: { chartArea: { height: "85%", left: "5%", top: "5%", width: "80%" }, isStacked: false } }); var repos_now = new Keen.Query("maximum", { eventCollection: "repository_snapshots", targetProperty: "stargazers_count", groupBy: "full_name", timeframe: "this_1_hour" }); keenClient.draw(repos_now, document.getElementById("chart-02"), { chartType: "piechart", title: false, height: 250, width: "auto", chartOptions: { chartArea: { height: "85%", left: "5%", top: "5%", width: "100%" } } }); });
Refactor simple arrow head to use two lines instead of path
package SW9.model_canvas.arrow_heads; import javafx.scene.shape.Line; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_WIDTH = 15d; public SimpleArrowHead() { super(); addChildren(initializeLeftArrow(), initializeRightArrow()); } private Line initializeLeftArrow() { final Line leftArrow = new Line(); leftArrow.startXProperty().bind(xProperty); leftArrow.startYProperty().bind(yProperty); leftArrow.endXProperty().bind(xProperty.subtract(TRIANGLE_WIDTH / 2)); leftArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH)); return leftArrow; } private Line initializeRightArrow() { final Line rightArrow = new Line(); rightArrow.startXProperty().bind(xProperty); rightArrow.startYProperty().bind(yProperty); rightArrow.endXProperty().bind(xProperty.add(TRIANGLE_WIDTH / 2)); rightArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH)); return rightArrow; } @Override public double getHeadHeight() { return TRIANGLE_LENGTH; } @Override public double getHeadWidth() { return TRIANGLE_WIDTH; } @Override public boolean shouldBindToTip() { return true; } }
package SW9.model_canvas.arrow_heads; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class SimpleArrowHead extends ArrowHead { private static final double TRIANGLE_LENGTH = 20d; private static final double TRIANGLE_WIDTH = 15d; public SimpleArrowHead() { super(); addChild(initializeTriangle()); } private Path initializeTriangle() { final Path simpleArrow = new Path(); MoveTo start = new MoveTo(); LineTo l1 = new LineTo(); MoveTo l2 = new MoveTo(); LineTo l3 = new LineTo(); start.xProperty().bind(xProperty); start.yProperty().bind(yProperty); l1.xProperty().bind(start.xProperty().subtract(TRIANGLE_WIDTH / 2)); l1.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH)); l2.xProperty().bind(start.xProperty().add(TRIANGLE_WIDTH / 2)); l2.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH)); l3.xProperty().bind(start.xProperty()); l3.yProperty().bind(start.yProperty()); simpleArrow.setStroke(Color.BLACK); simpleArrow.getElements().addAll(start, l1, l2, l3); return simpleArrow; } @Override public double getHeadHeight() { return TRIANGLE_LENGTH; } @Override public double getHeadWidth() { return TRIANGLE_WIDTH; } @Override public boolean shouldBindToTip() { return true; } }
Allow fuzzy searches to be combined Ie. v1/jsdelivr/libraries?name=jq*&lastversion=*.0.1 .
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b); }).filter(fp.id).length > 0; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
Add support for observing an SNS topic.
var Rx = require('rx'), _ = require('lodash'); function receiveMessage(sqs, params, callback) { sqs.receiveMessage(params, function (err, data) { callback(err, data); receiveMessage(sqs, params, callback); }); } exports.observerFromTopic = function (sns, params) { return Rx.Observer.create(function (messageParams) { sns.publish(_.defaults(messageParams, params), function (err, data) { }); }); }; exports.observerFromQueue = function (sqs, params) { return Rx.Observer.create(function (messageParams) { sqs.sendMessage(_.defaults(messageParams, params), function (err, data) { }); }); }; exports.observableFromQueue = function (sqs, params) { return Rx.Observable.create(function (observer) { receiveMessage(sqs, params, function (err, data) { if (err) { observer.onError(err); } else if (data && data.Messages) { _.forEach(data.Messages, function (message) { observer.onNext(message); }); } return function () { /* Clean up */ }; }); }); }; exports.subjectFromQueue = function (sqs, sendParams, receiveParams) { return Rx.Subject.create( exports.observerFromQueue(sqs, sendParams), exports.observableFromQueue(sqs, receiveParams) ); };
var Rx = require('rx'), _ = require('lodash'); function receiveMessage(sqs, params, callback) { sqs.receiveMessage(params, function (err, data) { callback(err, data); receiveMessage(sqs, params, callback); }); } exports.observerFromQueue = function (sqs, params) { return Rx.Observer.create(function (messageParams) { sqs.sendMessage(_.defaults(messageParams, params), function (err, data) { }); }); }; exports.observableFromQueue = function (sqs, params) { return Rx.Observable.create(function (observer) { receiveMessage(sqs, params, function (err, data) { if (err) { observer.onError(err); } else if (data && data.Messages) { _.forEach(data.Messages, function (message) { observer.onNext(message); }); } return function () { /* Clean up */ }; }); }); }; exports.subjectFromQueue = function (sqs, sendParams, receiveParams) { return Rx.Subject.create( exports.observerFromQueue(sqs, sendParams), exports.observableFromQueue(sqs, receiveParams) ); };
Disable select2 on mobile devices
$(document).ready(function() { if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) { $('select[multiple]').each(function() { var select = $(this), search = $('<button/>', { 'class': 'btn' }).append( $('<span/>', { 'class': 'icon-search' })); select.removeAttr('required'); select.parent().parent().find('span').remove(); select.wrap($('<div/>', { 'class': 'input-append' })); select.after(search); select.select2({ 'width': '350px' }); search.on('click', function() { select.select2('open'); return false; }); }); } $('form').on('submit', function() { if ($(this).get(0).checkValidity() === false) { return; } $(this).find('a, input[type=submit], button').addClass('disabled'); }); $('.click-disable').on('click', function() { if ($(this).closest('form').length > 0) { if ($(this).closest('form').get(0).checkValidity() === false) { return; } } $(this).addClass('disabled'); $(this).find('span').attr('class', 'icon-spinner icon-spin'); }); $('.datepicker').css('width', '100px').datepicker({ 'format': 'dd-mm-yyyy', 'language': 'nl' }); });
$(document).ready(function() { $('select[multiple]').each(function() { var select = $(this), search = $('<button/>', { 'class': 'btn' }).append( $('<span/>', { 'class': 'icon-search' })); select.removeAttr('required'); select.parent().parent().find('span').remove(); select.wrap($('<div/>', { 'class': 'input-append' })); select.after(search); select.select2({ 'width': '350px' }); search.on('click', function() { select.select2('open'); return false; }); }); $('form').on('submit', function() { if ($(this).get(0).checkValidity() === false) { return; } $(this).find('a, input[type=submit], button').addClass('disabled'); }); $('.click-disable').on('click', function() { if ($(this).closest('form').length > 0) { if ($(this).closest('form').get(0).checkValidity() === false) { return; } } $(this).addClass('disabled'); $(this).find('span').attr('class', 'icon-spinner icon-spin'); }); $('.datepicker').css('width', '100px').datepicker({ 'format': 'dd-mm-yyyy', 'language': 'nl' }); });
Change from map to forEach.
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq) => { if (sq.innerHTML !== "O" && sq.innerHTML !== "X") { drawMark(sq); saveMove(sq); if (isWinner()) { colourWinner(); }; changePlayer(); } }; var drawMark = td => td.innerHTML = player; var saveMove = td => moves[td.id] = player; var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0); var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3); var colourWinner = () => winningCombos.filter(isWinningCombo).forEach(colourCombo); var colourCombo = combo => combo.forEach(sq => document.getElementById(sq + "").style.backgroundColor = "green"); var changePlayer = () => (player === "O") ? player = "X" : player = "O"; })();
(() => { 'use strict'; var player = "O"; var moves = []; var winningCombos = [ ["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["1", "5", "9"], ["3", "5", "7"], ["1", "4", "7"], ["2", "5", "8"], ["3", "6", "9"]]; window.play = (sq) => { if (sq.innerHTML !== "O" && sq.innerHTML !== "X") { drawMark(sq); saveMove(sq); if (isWinner()) { colourWinner(); }; changePlayer(); } }; var drawMark = td => td.innerHTML = player; var saveMove = td => moves[td.id] = player; var isWinner = () => (winningCombos.filter(isWinningCombo).length > 0); var isWinningCombo = combo => (combo.filter(sq => moves[sq] === player).length === 3); var colourWinner = () => winningCombos.filter(isWinningCombo).map(colourCombo); var colourCombo = combo => combo.map(sq => document.getElementById(sq + "").style.backgroundColor = "green"); var changePlayer = () => (player === "O") ? player = "X" : player = "O"; })();
Add test helper for creating users
import ujson import unittest from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from interrogate import Builder class InterrogateTestCase(unittest.TestCase): def valid_builder_args(self): model = self.model query_constraints = { 'breadth': None, 'depth': 32, 'elements': 64 } return [model, query_constraints] def make_builder(self, model=None, query_constraints=None): dm, dt, dq = self.valid_builder_args() return Builder( model or dm, query_constraints or dq ) def setUp(self): Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) age = Column(Integer) height = Column(Integer) engine = create_engine("sqlite://", echo=True) Base.metadata.create_all(engine) self.model = User self.session = sessionmaker(bind=engine)() def tearDown(self): self.session.close() def add_user(self, **kwargs): user = self.model(**kwargs) self.session.add(user) self.session.commit()
import ujson import unittest from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.pool import NullPool from interrogate import Builder class InterrogateTestCase(unittest.TestCase): def valid_builder_args(self): model = self.model type_constraints = { 'string': [ 'name', 'email' ], 'numeric': [ 'age', 'height' ], 'nullable': [ 'email', 'height' ] } query_constraints = { 'breadth': None, 'depth': 32, 'elements': 64 } return [model, type_constraints, query_constraints] def make_builder(self, model=None, type_constraints=None, query_constraints=None): dm, dt, dq = self.valid_builder_args() return Builder( model or dm, type_constraints or dt, query_constraints or dq ) def setUp(self): Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String) age = Column(Integer) height = Column(Integer) engine = create_engine("sqlite://", poolclass=NullPool) Base.metadata.create_all(engine) self.model = User self.session = sessionmaker(bind=engine)() def tearDown(self): self.session.close()
Add bullet to world when it's created
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.util.LinkedList; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health; protected double _baseAim; public Ship() { super(); _gunupgrades = new LinkedList<GunUpgrade>(); _baseDamage = 1; _baseShotSpeed = 1; _health = 10; _baseAim = Math.PI/2; //Aim up by default } public void addUpgrade(GunUpgrade upgrade) { _gunupgrades.add(upgrade); } /* * Create the shots based on the available GunUpgrades */ public void shoot() { GunUpgrade topShot = _gunupgrades.get(0); int damage = _baseDamage; int shotSpeed = _baseShotSpeed; for (GunUpgrade up : _gunupgrades) { if (up.getNumShots() > topShot.getNumShots()) topShot = up; damage = up.getDamage(damage); shotSpeed = up.getShotSpeed(shotSpeed); } // Create new shots, based on dem vars int numShots = topShot.getNumShots(); for (int i = 0; i < numShots; i++) { Bullet b = new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed); b.setWorld(this.getWorld()); } } }
package edu.stuy.starlorn.entities; import edu.stuy.starlorn.upgrades.GunUpgrade; import java.util.LinkedList; public class Ship extends Entity { protected LinkedList<GunUpgrade> _gunupgrades; protected int _baseDamage, _baseShotSpeed, _health; protected double _baseAim; public Ship() { super(); _gunupgrades = new LinkedList<GunUpgrade>(); _baseDamage = 1; _baseShotSpeed = 1; _health = 10; _baseAim = Math.PI/2; //Aim up by default } public void addUpgrade(GunUpgrade upgrade) { _gunupgrades.add(upgrade); } /* * Create the shots based on the available GunUpgrades */ public void shoot() { GunUpgrade topShot = _gunupgrades.get(0); int damage = _baseDamage; int shotSpeed = _baseShotSpeed; for (GunUpgrade up : _gunupgrades) { if (up.getNumShots() > topShot.getNumShots()) topShot = up; damage = up.getDamage(damage); shotSpeed = up.getShotSpeed(shotSpeed); } // Create new shots, based on dem vars int numShots = topShot.getNumShots(); for (int i = 0; i < numShots; i++) { new Bullet(_baseAim + topShot.getAimAngle(), damage, shotSpeed); } } }
Fix filter for Ticket Admin
<?php namespace Stfalcon\Bundle\EventBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Show\ShowMapper; class TicketAdmin extends Admin { protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id') ->addIdentifier('event') ->add('user.fullname', null, array('label' => 'Fullname')) ->add('payment') ->add('createdAt') ->add('updatedAt') ->add('used') ; } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('event') ->add('used') ->add('payment.status', 'doctrine_orm_choice', array( 'field_options' => array( 'choices' => array( 'paid' => 'Paid', 'pending' => 'Pending' ), ), 'field_type' => 'choice' ) ); } public function getExportFields() { return array( 'id', 'event', 'user.fullname', 'payment', 'createdAt', 'updatedAt', 'used' ); } }
<?php namespace Stfalcon\Bundle\EventBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Show\ShowMapper; class TicketAdmin extends Admin { protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id') ->addIdentifier('event') ->add('user.fullname',null, array('label' => 'Fullname')) ->add('payment') ->add('createdAt') ->add('updatedAt') ->add('used') ; } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('event') ->add('used') ->add('payment') ; } public function getExportFields() { return array( 'id', 'event', 'user.fullname', 'payment', 'createdAt', 'updatedAt', 'used' ); } }
Fix import order in tests.
import imp import os import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
import imp import os import sys from django.test import TestCase from kolibri import dist as kolibri_dist dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
Fix style nit, line end for test file
""" SoftLayer.tests.CLI.modules.subnet_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import testing import json class SubnetTests(testing.TestCase): def test_detail(self): result = self.run_command(['subnet', 'detail', '1234']) self.assert_no_fail(result) self.assertEqual( { 'id': 1234, 'identifier': '1.2.3.4/26', 'subnet type': 'ADDITIONAL_PRIMARY', 'network space': 'PUBLIC', 'gateway': '1.2.3.254', 'broadcast': '1.2.3.255', 'datacenter': 'dal10', 'vs': [ { 'hostname': 'hostname0', 'domain': 'sl.test', 'public_ip': '1.2.3.10', 'private_ip': '10.0.1.2' } ], 'hardware': 'none', 'usable ips': 22 }, json.loads(result.output))
""" SoftLayer.tests.CLI.modules.subnet_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import testing import json class SubnetTests(testing.TestCase): def test_detail(self): result = self.run_command(['subnet', 'detail', '1234']) self.assert_no_fail(result) self.assertEqual( { 'id': 1234, 'identifier': '1.2.3.4/26', 'subnet type': 'ADDITIONAL_PRIMARY', 'network space': 'PUBLIC', 'gateway': '1.2.3.254', 'broadcast': '1.2.3.255', 'datacenter': 'dal10', 'vs': [ { 'hostname': 'hostname0', 'domain': 'sl.test', 'public_ip': '1.2.3.10', 'private_ip': '10.0.1.2' } ], 'hardware': 'none', 'usable ips': 22 }, json.loads(result.output))
Use login instead of user's name.
package org.crunchytorch.coddy.snippet.service; import org.crunchytorch.coddy.application.exception.EntityNotFoundException; import org.crunchytorch.coddy.application.service.AbstractService; import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity; import org.crunchytorch.coddy.snippet.elasticsearch.repository.SnippetRepository; import org.crunchytorch.coddy.user.data.security.JWTPrincipal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.ws.rs.core.SecurityContext; import java.util.Date; @Service public class SnippetService extends AbstractService<SnippetEntity> { @Autowired public SnippetService(SnippetRepository repository) { super(repository); } public SnippetEntity getSnippet(String id) { SnippetEntity entity = this.repository.findOne(id); if (entity == null) { throw new EntityNotFoundException("snippet with the id : " + id + " not found"); } return entity; } public SnippetEntity create(SnippetEntity entity, SecurityContext securityContext) { // Set date to now Date now = new Date(); entity.setCreated(now); entity.setLastModified(now); // Set author from token information entity.setAuthor(((JWTPrincipal) securityContext.getUserPrincipal()).getLogin()); // Initiate rate entity.setRate(0); return super.create(entity); } }
package org.crunchytorch.coddy.snippet.service; import org.crunchytorch.coddy.application.exception.EntityNotFoundException; import org.crunchytorch.coddy.application.service.AbstractService; import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity; import org.crunchytorch.coddy.snippet.elasticsearch.repository.SnippetRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.ws.rs.core.SecurityContext; import java.util.Date; @Service public class SnippetService extends AbstractService<SnippetEntity> { @Autowired public SnippetService(SnippetRepository repository) { super(repository); } public SnippetEntity getSnippet(String id) { SnippetEntity entity = this.repository.findOne(id); if (entity == null) { throw new EntityNotFoundException("snippet with the id : " + id + " not found"); } return entity; } public SnippetEntity create(SnippetEntity entity, SecurityContext securityContext) { // Set date to now Date now = new Date(); entity.setCreated(now); entity.setLastModified(now); // Set author from token information entity.setAuthor(securityContext.getUserPrincipal().getName()); // Initiate rate entity.setRate(0); return super.create(entity); } }
Fix the order currency listener spec
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\CoreBundle\EventListener; use PhpSpec\ObjectBehavior; class OrderCurrencyListenerSpec extends ObjectBehavior { /** * @param Sylius\Bundle\MoneyBundle\Context\CurrencyContextInterface $currencyContext */ function let($currencyContext) { $this->beConstructedWith($currencyContext); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\CoreBundle\EventListener\OrderCurrencyListener'); } /** * @param Sylius\Bundle\CartBundle\Event\CartEvent $event * @param \stdClass $invalidSubject */ function it_throws_exception_if_event_has_non_order_subject($event, $invalidSubject) { $event->getCart()->willReturn($invalidSubject); $this ->shouldThrow('InvalidArgumentException') ->duringProcessOrderCurrency($event) ; } /** * @param Sylius\Bundle\CartBundle\Event\CartEvent $event * @param Sylius\Bundle\CoreBundle\Model\OrderInterface $order */ function it_sets_currency_on_order($currencyContext, $event, $order) { $event->getCart()->willReturn($order); $currencyContext->getCurrency()->shouldBeCalled()->willReturn('PLN'); $this->processOrderCurrency($event); } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\CoreBundle\EventListener; use PhpSpec\ObjectBehavior; class OrderCurrencyListenerSpec extends ObjectBehavior { /** * @param Sylius\Bundle\MoneyBundle\Context\CurrencyContextInterface $currencyContext */ function let($currencyContext) { $this->beConstructedWith($currencyContext); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\CoreBundle\EventListener\OrderCurrencyListener'); } /** * @param Symfony\Component\EventDispatcher\GenericEvent $event * @param \stdClass $invalidSubject */ function it_throws_exception_if_event_has_non_order_subject($event, $invalidSubject) { $event->getSubject()->willReturn($invalidSubject); $this ->shouldThrow('InvalidArgumentException') ->duringProcessOrderCurrency($event) ; } /** * @param Symfony\Component\EventDispatcher\GenericEvent $event * @param Sylius\Bundle\CoreBundle\Model\OrderInterface $order */ function it_sets_currency_on_order($currencyContext, $event, $order) { $event->getSubject()->willReturn($order); $currencyContext->getCurrency()->shouldBeCalled()->willReturn('PLN'); $this->processOrderCurrency($event); } }
Update regex to fit DD/MM/YYYY format
package seedu.ezdo.model.todo; import seedu.ezdo.commons.exceptions.IllegalValueException; /** * Represents the due date of a todo. */ public class DueDate { public static final String MESSAGE_DUEDATE_CONSTRAINTS = "Due dates should be in the format DD/MM/YYYY, and it should not be blank"; public static final String DUEDATE_VALIDATION_REGEX = "([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)"; public final String value; /** * Validates given due date. * * @throws IllegalValueException if given due date string is invalid. */ public DueDate(String dueDate) throws IllegalValueException { assert dueDate != null; if (!isValidDueDate(dueDate)) { throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS); } this.value = dueDate; } /** * Returns true if a given string is a valid due date. */ public static boolean isValidDueDate(String test) { return test.matches(DUEDATE_VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DueDate // instanceof handles nulls && this.value.equals(((DueDate) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } }
package seedu.ezdo.model.todo; import seedu.ezdo.commons.exceptions.IllegalValueException; /** * Represents the due date of a todo. */ public class DueDate { public static final String MESSAGE_DUEDATE_CONSTRAINTS = "Due dates should be in the format DD/MM/YYYY, and it should not be blank"; public static final String DUEDATE_VALIDATION_REGEX = ".+"; public final String value; /** * Validates given due date. * * @throws IllegalValueException if given due date string is invalid. */ public DueDate(String dueDate) throws IllegalValueException { assert dueDate != null; if (!isValidDueDate(dueDate)) { throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS); } this.value = dueDate; } /** * Returns true if a given string is a valid due date. */ public static boolean isValidDueDate(String test) { return test.matches(DUEDATE_VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DueDate // instanceof handles nulls && this.value.equals(((DueDate) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } }
Truncate target table before creating division items
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_divisions_config.txt') lines = [l.strip() for l in open(div_src_file).readlines()] with session_scope() as session: session.query(Division).delete(synchronize_session=False) try: for line in lines: if line.startswith("#"): continue division_name, season, teams, conference = line.split(";") season = int(season) team_abbrs = teams[1:-1].split(',') teams = list() for t in team_abbrs: team = Team.find(t) teams.append(team) else: if conference: division = Division( division_name, season, teams, conference) else: division = Division( division_name, season, teams) session.add(division) print(division) session.commit() except Exception as e: session.rollback() traceback.print_exc()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_divisions_config.txt') lines = [l.strip() for l in open(div_src_file).readlines()] with session_scope() as session: try: for line in lines: if line.startswith("#"): continue division_name, season, teams, conference = line.split(";") season = int(season) team_abbrs = teams[1:-1].split(',') teams = list() for t in team_abbrs: team = Team.find(t) teams.append(team) else: if conference: division = Division( division_name, season, teams, conference) else: division = Division( division_name, season, teams) session.add(division) print(division) session.commit() except: session.rollback() traceback.print_exc()
Add info about crop gravity options in config example
module.exports = { variants: { items: { // keepNames: true, resize: { mini : "300x200", preview: "800x600" }, crop: { thumb: "200x200", // Sets the crop position, or "gravity". Default is NorthWest. // See http://www.graphicsmagick.org/GraphicsMagick.html#details-gravity for details thumb_center: "200x200 Center" }, resizeAndCrop: { large: {resize: "1000x1000", crop: "900x900"} } }, gallery: { rename: function (filename) { return 'MyFileManipulationLogic_' + filename; }, crop: { thumb: "100x100" } } }, storage: { Local: { path: "/var/www/" }, Rackspace: { username: "USERNAME", apiKey: "API_KEY", authUrl: "https://lon.auth.api.rackspacecloud.com" container: "CONTAINER_NAME", region: "REGION_NAME" }, S3: { key: 'API_KEY', secret: 'SECRET', bucket: 'BUCKET_NAME', storageClass: 'REDUCED_REDUNDANCY', secure: false, // (optional) if your BUCKET_NAME contains dot(s), set this to false. Default is `true` cdn: 'CDN_URL' // (optional) if you want to use Amazon cloudfront cdn, enter the cdn url here }, uploadDirectory: 'images/uploads/' }, debug: true }
module.exports = { variants: { items: { // keepNames: true, resize: { mini : "300x200", preview: "800x600" }, crop: { thumb: "200x200" }, resizeAndCrop: { large: {resize: "1000x1000", crop: "900x900"} } }, gallery: { rename: function (filename) { return 'MyFileManipulationLogic_' + filename; }, crop: { thumb: "100x100" } } }, storage: { Local: { path: "/var/www/" }, Rackspace: { username: "USERNAME", apiKey: "API_KEY", authUrl: "https://lon.auth.api.rackspacecloud.com" container: "CONTAINER_NAME", region: "REGION_NAME" }, S3: { key: 'API_KEY', secret: 'SECRET', bucket: 'BUCKET_NAME', storageClass: 'REDUCED_REDUNDANCY', secure: false, // (optional) if your BUCKET_NAME contains dot(s), set this to false. Default is `true` cdn: 'CDN_URL' // (optional) if you want to use Amazon cloudfront cdn, enter the cdn url here }, uploadDirectory: 'images/uploads/' }, debug: true }
Use version alias for jasmine-jquery
/* * debugger.io: An interactive web scripting sandbox */ (function() { 'use strict'; var SRC = '../../src'; var TEST = '../../test'; // relative to SRC require([SRC + '/js/require.config'], function() { requirejs.config({ baseUrl: SRC + '/js', urlArgs: ('v=' + (new Date()).getTime()), paths: { jasminejs: '//cdn.jsdelivr.net/jasmine/2.0.0/jasmine', jasmine_html: '//cdn.jsdelivr.net/jasmine/2.0.0/jasmine-html', jasmine_boot: '//cdn.jsdelivr.net/jasmine/2.0.0/boot', jasmine_jquery: '//cdn.jsdelivr.net/jasmine.jquery/2.0/jasmine-jquery.min', jasmine: TEST + '/js/libs/jasmine', matchers: TEST + '/js/matchers' }, shim: { jasminejs: { exports: 'jasmine' }, jasmine_html: { deps: ['jasminejs'] }, jasmine_boot: { deps: ['jasminejs', 'jasmine_html'] }, jasmine_jquery: { deps: ['jquery', 'jasmine'] } } }); require(['jquery', 'underscore', 'jasmine', 'matchers'], function($, _, jasmine, matchers) { var specs = _.map([ 'config', 'utils' ], function(module) { return _.sprintf('%s/spec/%s_spec', TEST, module); }); $(function() { require(specs, function() { matchers.addMatchers(); jasmine.onJasmineLoad(); }); }); }); }); })();
/* * debugger.io: An interactive web scripting sandbox */ (function() { 'use strict'; var SRC = '../../src'; var TEST = '../../test'; // relative to SRC require([SRC + '/js/require.config'], function() { requirejs.config({ baseUrl: SRC + '/js', urlArgs: ('v=' + (new Date()).getTime()), paths: { jasminejs: '//cdn.jsdelivr.net/jasmine/2.0.0/jasmine', jasmine_html: '//cdn.jsdelivr.net/jasmine/2.0.0/jasmine-html', jasmine_boot: '//cdn.jsdelivr.net/jasmine/2.0.0/boot', jasmine_jquery: '//cdn.jsdelivr.net/jasmine.jquery/2.0.3/jasmine-jquery.min', jasmine: TEST + '/js/libs/jasmine', matchers: TEST + '/js/matchers' }, shim: { jasminejs: { exports: 'jasmine' }, jasmine_html: { deps: ['jasminejs'] }, jasmine_boot: { deps: ['jasminejs', 'jasmine_html'] }, jasmine_jquery: { deps: ['jquery', 'jasmine'] } } }); require(['jquery', 'underscore', 'jasmine', 'matchers'], function($, _, jasmine, matchers) { var specs = _.map([ 'config', 'utils' ], function(module) { return _.sprintf('%s/spec/%s_spec', TEST, module); }); $(function() { require(specs, function() { matchers.addMatchers(); jasmine.onJasmineLoad(); }); }); }); }); })();
Remove weird duplication of removal of destroyed entity from updater.
;(function(exports) { function Entities() { this._entities = []; }; Entities.prototype = { all: function(clazz) { if (clazz === undefined) { return this._entities; } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entities[i] instanceof clazz) { entities.push(this._entities[i]); } } return entities; } }, create: function(clazz, settings, callback) { Coquette.get().runner.add(this, function(entities) { var entity = new clazz(Coquette.get().game, settings || {}); Coquette.get().updater.add(entity); entities._entities.push(entity); if (callback !== undefined) { callback(entity); } }); }, destroy: function(entity, callback) { Coquette.get().runner.add(this, function(entities) { Coquette.get().updater.remove(entity); for(var i = 0; i < entities._entities.length; i++) { if(entities._entities[i] === entity) { entities._entities.splice(i, 1); if (callback !== undefined) { callback(); } break; } } }); } }; exports.Entities = Entities; })(typeof exports === 'undefined' ? this.Coquette : exports);
;(function(exports) { function Entities() { this._entities = []; }; Entities.prototype = { all: function(clazz) { if (clazz === undefined) { return this._entities; } else { var entities = []; for (var i = 0; i < this._entities.length; i++) { if (this._entities[i] instanceof clazz) { entities.push(this._entities[i]); } } return entities; } }, create: function(clazz, settings, callback) { Coquette.get().runner.add(this, function(entities) { var entity = new clazz(Coquette.get().game, settings || {}); Coquette.get().updater.add(entity); entities._entities.push(entity); if (callback !== undefined) { callback(entity); } }); }, destroy: function(entity, callback) { Coquette.get().runner.add(this, function(entities) { Coquette.get().updater.remove(entity); Coquette.get().updater.remove(entity); for(var i = 0; i < entities._entities.length; i++) { if(entities._entities[i] === entity) { entities._entities.splice(i, 1); if (callback !== undefined) { callback(); } break; } } }); } }; exports.Entities = Entities; })(typeof exports === 'undefined' ? this.Coquette : exports);
Fix docblock @covers class path
<?php use Illuminate\Http\Response; use Illuminate\Support\Facades\Session; class LanguageSwitchTest extends TestCase { /** * Test switch language to English * @covers \App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToEnglish() { $applocale = 'en_US.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'en'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } /** * Test switch language to Spanish Spain * @covers \App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToSpanishSpain() { $applocale = 'es_ES.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'es'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } /** * Test switch language to Spanish Argentina * @covers \App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToSpanishArgentina() { $applocale = 'es_AR.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'es'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } }
<?php use Illuminate\Http\Response; use Illuminate\Support\Facades\Session; class LanguageSwitchTest extends TestCase { /** * Test switch language to English * @covers App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToEnglish() { $applocale = 'en_US.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'en'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } /** * Test switch language to Spanish Spain * @covers App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToSpanishSpain() { $applocale = 'es_ES.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'es'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } /** * Test switch language to Spanish Argentina * @covers App\Http\Controllers\LanguageController::switchLang */ public function testSwitchLanguageToSpanishArgentina() { $applocale = 'es_AR.utf8'; $this->call('GET', "/lang/$applocale"); $this->assertSessionHas('language', 'es'); $this->assertSessionHas('applocale', $applocale); $this->assertResponseStatus(302); } }
Fix for rethrowing mysql.connector.Error as IOError
import sys class PlayoffDB(object): db_cursor = None DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured' def __init__(self, settings): reload(sys) sys.setdefaultencoding("latin1") import mysql.connector self.database = mysql.connector.connect( user=settings['user'], password=settings['pass'], host=settings['host'], port=settings['port']) self.db_cursor = self.database.cursor(buffered=True) def get_cursor(self): return self.db_cursor def __execute_query(self, db_name, sql, params): self.db_cursor.execute(sql.replace('#db#', db_name), params) def fetch(self, db_name, sql, params): import mysql.connector try: self.__execute_query(db_name, sql, params) row = self.db_cursor.fetchone() return row except mysql.connector.Error as e: raise IOError(e.errno, str(e), db_name) def fetch_all(self, db_name, sql, params): import mysql.connector try: self.__execute_query(db_name, sql, params) results = self.db_cursor.fetchall() return results except mysql.connector.Error as e: raise IOError( message=str(e), filename=db_name, errno=e.errno, strerror=str(e))
import sys class PlayoffDB(object): db_cursor = None DATABASE_NOT_CONFIGURED_WARNING = 'WARNING: database not configured' def __init__(self, settings): reload(sys) sys.setdefaultencoding("latin1") import mysql.connector self.database = mysql.connector.connect( user=settings['user'], password=settings['pass'], host=settings['host'], port=settings['port']) self.db_cursor = self.database.cursor(buffered=True) def get_cursor(self): return self.db_cursor def __execute_query(self, db_name, sql, params): self.db_cursor.execute(sql.replace('#db#', db_name), params) def fetch(self, db_name, sql, params): import mysql.connector try: self.__execute_query(db_name, sql, params) row = self.db_cursor.fetchone() return row except mysql.connector.Error as e: raise IOError( message=str(e), filename=db_name, errno=e.errno, strerror=str(e)) def fetch_all(self, db_name, sql, params): import mysql.connector try: self.__execute_query(db_name, sql, params) results = self.db_cursor.fetchall() return results except mysql.connector.Error as e: raise IOError( message=str(e), filename=db_name, errno=e.errno, strerror=str(e))
Fix serialization of form errors
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) def get_data(error): if isinstance(error, (dict, str)): return error return error.get_json_data() class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: get_data(e) for f, e in self.errors.items()}, 'nonFieldErrors': [get_data(e) for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
import json from django.db import models class DjangoJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, models.Model) and hasattr(obj, 'as_data'): return obj.as_data() return json.JSONEncoder.default(self, obj) class JSONMixin(object): def as_json(self): return json.dumps(self.as_data(), cls=DjangoJSONEncoder) def as_data(self): return { 'fields': { str(name): self.field_to_dict(name, field) for name, field in self.fields.items() }, 'errors': {f: e.get_json_data() for f, e in self.errors.items()}, 'nonFieldErrors': [e.get_json_data() for e in self.non_field_errors()] } def field_to_dict(self, name, field): return { "type": field.__class__.__name__, "widget_type": field.widget.__class__.__name__, "hidden": field.widget.is_hidden, "required": field.widget.is_required, "label": str(field.label), "help_text": str(field.help_text), "initial": self.get_initial_for_field(field, name), "placeholder": str(field.widget.attrs.get('placeholder', '')), "value": self[name].value() if self.is_bound else None }
Use room name as string, instead as object for key value
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room.name] === undefined) { cache[Game.creeps[i].room.name] = [Game.creeps[i]]; } else { cache[Game.creeps[i].room.name].push(Game.creeps[i]); } } all.push(Game.creeps[i]); } } if (room === undefined) { return all; } if (room instanceof Room) { room = room.name; } if (cache[room] === undefined) { return []; } return cache[room]; } function get(room, options) { if (options === undefined) { options = {}; } return getCache(room); } function filter(creep, options) { options = options || {}; return { filter: function(obj) { if (!(obj instanceof Creep)) { return false; } if (obj.my !== true) { return false; } if (options.spawningOnly === true) { return creep.spawning === true; } if (options.spawning !== true) { return creep.spawning === false; } return true; } }; } module.exports = { get: get, filter: filter };
'use strict'; var all = false; var cache = {}; function getCache(room) { if (all === false) { all = []; for (var i in Game.creeps) { if (!Game.creeps.spawning) { if (cache[Game.creeps[i].room] === undefined) { cache[Game.creeps[i].room] = [Game.creeps[i]]; } else { cache[Game.creeps[i].room].push(Game.creeps[i]); } } all.push(Game.creeps[i]); } } if (room === undefined) { return all; } if (cache[room] === undefined) { return []; } return cache[room]; } function get(room, options) { if (options === undefined) { options = {}; } return getCache(room); } function filter(creep, options) { options = options || {}; return { filter: function(obj) { if (!(obj instanceof Creep)) { return false; } if (obj.my !== true) { return false; } if (options.spawningOnly === true) { return creep.spawning === true; } if (options.spawning !== true) { return creep.spawning === false; } return true; } }; } module.exports = { get: get, filter: filter };
Return its argument in validators
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return boxed def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return record def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return union
""":mod:`nirum.validate` ~~~~~~~~~~~~~~~~~~~~~~~~ """ __all__ = 'validate_boxed_type', 'validate_record_type' def validate_boxed_type(boxed, type_hint): if not isinstance(boxed, type_hint): raise TypeError('{0} expected, found: {1}'.format(type_hint, type(boxed))) return True def validate_record_type(record): for attr, type_ in record.__nirum_field_types__.items(): data = getattr(record, attr) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(record, attr, type_, type(data)) ) else: return True def validate_union_type(union): for attr, type_ in union.__nirum_tag_types__.items(): data = getattr(union, attr) print(attr, type_) if not isinstance(data, type_): raise TypeError( 'expect {0.__class__.__name__}.{1} to be {2}' ', but found: {3}'.format(union, attr, type_, type(data)) ) else: return True
Switch from old to current method `$this->app->bindShared()` was deprecated in Laravel 5.1, and removed in 5.2. It has been replaced by the (identical in all but name) `->singleton()` method. This PR addresses this change.
<?php namespace Rokde\LaravelBootstrap\Html; use Collective\Html\HtmlBuilder; use Illuminate\Support\ServiceProvider; /** * Class HtmlServiceProvider * * @package Rokde\LaravelBootstrap\Html */ class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->registerHtmlBuilder(); $this->registerFormBuilder(); $this->app->alias('html', 'Collective\Html\HtmlBuilder'); $this->app->alias('form', 'App\Html\BootstrapFormBuilder'); } /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->singleton('html', function ($app) { return new HtmlBuilder($app['url']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->singleton('form', function ($app) { $form = new BootstrapFormBuilder($app['html'], $app['url'], $app['session.store']->getToken()); return $form->setSessionStore($app['session.store']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['html', 'form', 'Collective\Html\HtmlBuilder', 'App\Html\BootstrapFormBuilder']; } }
<?php namespace Rokde\LaravelBootstrap\Html; use Collective\Html\HtmlBuilder; use Illuminate\Support\ServiceProvider; /** * Class HtmlServiceProvider * * @package Rokde\LaravelBootstrap\Html */ class HtmlServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->registerHtmlBuilder(); $this->registerFormBuilder(); $this->app->alias('html', 'Collective\Html\HtmlBuilder'); $this->app->alias('form', 'App\Html\BootstrapFormBuilder'); } /** * Register the HTML builder instance. * * @return void */ protected function registerHtmlBuilder() { $this->app->bindShared('html', function ($app) { return new HtmlBuilder($app['url']); }); } /** * Register the form builder instance. * * @return void */ protected function registerFormBuilder() { $this->app->bindShared('form', function ($app) { $form = new BootstrapFormBuilder($app['html'], $app['url'], $app['session.store']->getToken()); return $form->setSessionStore($app['session.store']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['html', 'form', 'Collective\Html\HtmlBuilder', 'App\Html\BootstrapFormBuilder']; } }
Add a short alias for bin/openprocurement_tests Alias is: bin/op_tests
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', 'op_tests = op_robot_tests.runner:runner', ], } )
from setuptools import find_packages, setup version = '2.3' setup(name='op_robot_tests', version=version, description="", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='', author_email='', url='', license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'robotframework', 'robotframework-selenium2library', 'robotframework-debuglibrary', 'robotframework-selenium2screenshots', 'Pillow', 'iso8601', 'PyYAML', 'munch', 'fake-factory', 'dpath', 'jsonpath-rw', 'dateutils', 'pytz', 'parse', 'chromedriver', 'barbecue', 'haversine' ], entry_points={ 'console_scripts': [ 'openprocurement_tests = op_robot_tests.runner:runner', ], } )
Replace name, surname concatenation with getFullName
package by.triumgroup.recourse.document.model.provider.impl; import by.triumgroup.recourse.document.model.provider.ContentProvider; import by.triumgroup.recourse.entity.dto.Student; import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark; import java.util.*; import java.util.stream.Collectors; public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> { @Override public String createTitle(Student mainEntity) { return mainEntity.getFullName(); } @Override public String createFilename(Student user) { return String.format("%s_profile", user.getFullName()); } @Override public Map<String, String> createSubtitles(Student mainEntity) { return new HashMap<String, String>(){{ put("Total average mark", mainEntity.getTotalAverageMark().toString()); }}; } @Override public List<String> getHeaders() { return Arrays.asList("Title", "Average mark"); } @Override public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) { return "Courses"; } @Override public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) { return courses.stream() .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString())) .collect(Collectors.toList()); } }
package by.triumgroup.recourse.document.model.provider.impl; import by.triumgroup.recourse.document.model.provider.ContentProvider; import by.triumgroup.recourse.entity.dto.Student; import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark; import java.util.*; import java.util.stream.Collectors; public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> { @Override public String createTitle(Student mainEntity) { return mainEntity.getName() + " " + mainEntity.getSurname(); } @Override public String createFilename(Student user) { return String.format("%s_%s_profile", user.getName(), user.getSurname()); } @Override public Map<String, String> createSubtitles(Student mainEntity) { return new HashMap<String, String>(){{ put("Total average mark", mainEntity.getTotalAverageMark().toString()); }}; } @Override public List<String> getHeaders() { return Arrays.asList("Title", "Average mark"); } @Override public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) { return "Courses"; } @Override public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) { return courses.stream() .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString())) .collect(Collectors.toList()); } }
Remove if that was making the view to behave unexpectedly
'use strict'; angular.module('eMarketApp') .directive('itemView', function(User) { return { templateUrl: 'views/itemView.html', restrict: 'E', scope: { item: '=' }, replace: true, link: function(scope, elem) { var page = $(elem[0]); var popupItemAddedToCart = page.find('#popupItemAddedToCart'); var buyItNowButton = page.find('#buy-it-now-button'); var bidButton = page.find('#place-bid-button'); var placeBidInput = page.find('#placeBid'); page.on('pagebeforeshow', function() { if(User.userId === scope.item.productSellerId) { buyItNowButton.addClass('ui-disabled'); bidButton.addClass('ui-disabled'); } else { bidButton.removeClass('ui-disabled'); buyItNowButton.removeClass('ui-disabled'); } }); scope.placeBid = function() { }; scope.addToCart = function() { // Get the item quantity and multiply it by the price to get the total cost scope.item.cost = scope.item.quantity * scope.item.productBuyItNowPrice; User.me().all('carts').post(scope.item); }; scope.placeMinBid = function() { placeBidInput.attr('value', scope.item.productCurrentBidPrice + 5); }; } }; });
'use strict'; angular.module('eMarketApp') .directive('itemView', function (User) { return { templateUrl: 'views/itemView.html', restrict: 'E', scope: { item: '=' }, replace: true, link: function (scope, elem) { var page = $(elem[0]); var popupItemAddedToCart = page.find('#popupItemAddedToCart'); var buyItNowButton = page.find('#buy-it-now-button'); var bidButton = page.find('#place-bid-button'); var placeBidInput = page.find('#placeBid'); if (scope.item.productSellerId) { page.on('pagebeforeshow', function () { if(scope.item && User.userId === scope.item.productSellerId) { buyItNowButton.addClass('ui-disabled'); bidButton.addClass('ui-disabled'); } else { bidButton.removeClass('ui-disabled'); buyItNowButton.removeClass('ui-disabled'); } }); } scope.placeBid = function () { }; scope.addToCart = function () { // Get the item quantity and multiply it by the price to get the total cost scope.item.cost = scope.item.quantity * scope.item.productBuyItNowPrice; User.me().all('carts').post(scope.item); }; scope.placeMinBid = function () { placeBidInput.attr('value', scope.item.productCurrentBidPrice + 5); }; } }; } );
Add stop method, fix dangerous args.
#! /usr/bin/env python3 """Main XOInvader module, that is entry point to game. Prepare environment for starting game and start it.""" import curses from xoinvader.menu import MainMenuState from xoinvader.ingame import InGameState from xoinvader.render import Renderer from xoinvader.common import Settings from xoinvader.application import Application from xoinvader.curses_utils import create_curses_window from xoinvader.curses_utils import deinit_curses from xoinvader.curses_utils import style class XOInvader(Application): def __init__(self, startup_args={}): super(XOInvader, self).__init__(startup_args) self._update_settings(startup_args) self.screen = create_curses_window( ncols=Settings.layout.field.border.x, nlines=Settings.layout.field.border.y) # Ms per frame self._mspf = 16 style.init_styles(curses) Settings.renderer = Renderer(Settings.layout.field.border) def _update_settings(self, args): for arg, val in args.items(): if arg in Settings.system: Settings.system[arg] = val else: raise KeyError("No such argument: '%s'." % arg) def stop(self): deinit_curses(self.screen) super(XOInvader, self).stop() def create_game(args=None): """Create XOInvader game instance.""" app = XOInvader(args or dict()) app.register_state(InGameState) app.register_state(MainMenuState) return app
#! /usr/bin/env python3 """Main XOInvader module, that is entry point to game. Prepare environment for starting game and start it.""" import curses from xoinvader.menu import MainMenuState from xoinvader.ingame import InGameState from xoinvader.render import Renderer from xoinvader.common import Settings from xoinvader.application import Application from xoinvader.curses_utils import create_curses_window, style class XOInvader(Application): def __init__(self, startup_args={}): super(XOInvader, self).__init__(startup_args) self._update_settings(startup_args) self.screen = create_curses_window( ncols=Settings.layout.field.border.x, nlines=Settings.layout.field.border.y) # Ms per frame self._mspf = 16 style.init_styles(curses) Settings.renderer = Renderer(Settings.layout.field.border) def _update_settings(self, args): for arg, val in args.items(): if arg in Settings.system: Settings.system[arg] = val else: raise KeyError("No such argument: '%s'." % arg) def create_game(args={}): app = XOInvader(args) app.register_state(InGameState) app.register_state(MainMenuState) return app
Use dynamic self.__class__ and not name directly
import logging import yaml l = logging.getLogger(__name__) def _replace_with_type(type_, replace_type, data): if isinstance(data, type_): return replace_type(data) return data class Config(dict): def __init__(self, items=None): if items is not None: if hasattr(items, 'items'): items = list(items.items()) for i, (k, v) in enumerate(items): items[i] = (k, _replace_with_type(dict, self.__class__, v)) super().__init__(items) else: super().__init__() def __getattr__(self, key): if key in self: return self[key] else: l.warn("AttrDict: did not find key '{}' in {}", key, self.keys()) if l.getEffectiveLevel() <= logging.INFO: import inspect stack = inspect.stack(1)[1:] l.info("-- AttrDict stack --") for info in reversed(stack): l.info(' File "{0[1]}", line {0[2]}, in {0[3]} -- {1}', info, info[4][-1].strip()) l.info("-- AttrDict stack -- end") return self.__class__() # return empty 'Config' as default def read_file(filename): l.debug("reading config file: '{}'", filename) with open(filename) as f: config = Config(yaml.safe_load(f)) l.debug("config: {!s}", config) return config
import logging import yaml l = logging.getLogger(__name__) def _replace_with_type(type_, replace_type, data): if isinstance(data, type_): return replace_type(data) return data class Config(dict): def __init__(self, items=None): if items is not None: if hasattr(items, 'items'): items = list(items.items()) for i, (k, v) in enumerate(items): items[i] = (k, _replace_with_type(dict, Config, v)) super().__init__(items) else: super().__init__() def __getattr__(self, key): if key in self: return self[key] else: l.warn("AttrDict: did not find key '{}' in keys {}", key, self.keys()) if l.getEffectiveLevel() <= logging.INFO: import inspect stack = inspect.stack(1)[1:] l.info("-- AttrDict stack --") for info in reversed(stack): l.info(' File "{0[1]}", line {0[2]}, in {0[3]} -- {1}', info, info[4][-1].strip()) l.info("-- AttrDict stack -- end") return Config() # return empty 'dict' as default def read_file(filename): l.debug("reading config file: '{}'", filename) with open(filename) as f: config = Config(yaml.safe_load(f)) l.debug("config: {!s}", config) return config
Change password reset error message
'use strict'; angular.module('arachne.controllers') /** * Set new password. * * @author: Daniel M. de Oliveira */ .controller('PwdActivationController', ['$scope', '$stateParams', '$filter', '$location', 'PwdActivation', 'messageService', function ($scope, $stateParams, $filter, $location, PwdActivation, messages) { /** * Copy the user so that the shown passwords * of user object in $scope do not get modified * * @param user */ var copyUser = function (user) { var newUser = JSON.parse(JSON.stringify(user)); if (user.password) newUser.password = $filter('md5')(user.password); if (user.passwordConfirm) newUser.passwordConfirm = $filter('md5')(user.passwordConfirm); return newUser; }; var handleActivationSuccess = function () { messages.dontClearOnNextLocationChange(); messages.add('ui.passwordactivation.success', 'success'); $location.path("/"); }; var handleActivationError = function (data) { console.log(data); messages.add('ui.register.passwordsDontMatch', 'danger'); }; $scope.submit = function () { PwdActivation.save({token: $stateParams.token}, copyUser($scope.user), handleActivationSuccess, handleActivationError ); } }]);
'use strict'; angular.module('arachne.controllers') /** * Set new password. * * @author: Daniel M. de Oliveira */ .controller('PwdActivationController', ['$scope', '$stateParams', '$filter', '$location', 'PwdActivation', 'messageService', function ($scope, $stateParams, $filter, $location, PwdActivation, messages) { /** * Copy the user so that the shown passwords * of user object in $scope do not get modified * * @param user */ var copyUser = function (user) { var newUser = JSON.parse(JSON.stringify(user)); if (user.password) newUser.password = $filter('md5')(user.password); if (user.passwordConfirm) newUser.passwordConfirm = $filter('md5')(user.passwordConfirm); return newUser; }; var handleActivationSuccess = function () { messages.dontClearOnNextLocationChange(); messages.add('ui.passwordactivation.success', 'success'); $location.path("/"); }; var handleActivationError = function (data) { console.log(data); messages.add('default', 'danger'); }; $scope.submit = function () { PwdActivation.save({token: $stateParams.token}, copyUser($scope.user), handleActivationSuccess, handleActivationError ); } }]);
Enable placeholder to be docked
Ext.define('Slate.ui.mixin.PlaceholderItem', { extend: 'Ext.Mixin', requires: [ 'Slate.ui.Placeholder' ], mixinConfig: { after: { initItems: 'initPlaceholderItem' } }, config: { /** * @cfg {Slate.ui.Placeholder|Object|string|boolean} * Instance or configuration for placeholder component. * * Setting boolean values change visibility. */ placeholderItem: null, }, // config handlers applyPlaceholderItem: function(placeholderItem, oldPlaceholderItem) { var type = typeof placeholderItem; if (type == 'boolean') { placeholderItem = { hidden: !placeholderItem }; } else if (type == 'string') { placeholderItem = { html: placeholderItem }; } return Ext.factory(placeholderItem, 'Slate.ui.Placeholder', oldPlaceholderItem && !oldPlaceholderItem.destroyed ? oldPlaceholderItem : null); }, updatePlaceholderItem: function(placeholderItem, oldPlaceholderItem) { var me = this, items = me.items; if (items && items.isMixedCollection) { if (oldPlaceholderItem) { me.remove(oldPlaceholderItem); } if (placeholderItem) { me[placeholderItem.dock ? 'insertDocked' : 'insert'](0, placeholderItem); } } }, // container lifecycle initPlaceholderItem: function() { var me = this, placeholderItem = me.getPlaceholderItem(); if (placeholderItem) { me[placeholderItem.dock ? 'insertDocked' : 'insert'](0, placeholderItem); } } });
Ext.define('Slate.ui.mixin.PlaceholderItem', { extend: 'Ext.Mixin', requires: [ 'Slate.ui.Placeholder' ], mixinConfig: { after: { initItems: 'initPlaceholderItem' } }, config: { /** * @cfg {Slate.ui.Placeholder|Object|string|boolean} * Instance or configuration for placeholder component. * * Setting boolean values change visibility. */ placeholderItem: null, }, // config handlers applyPlaceholderItem: function(placeholderItem, oldPlaceholderItem) { var type = typeof placeholderItem; if (type == 'boolean') { placeholderItem = { hidden: !placeholderItem }; } else if (type == 'string') { placeholderItem = { html: placeholderItem }; } return Ext.factory(placeholderItem, 'Slate.ui.Placeholder', oldPlaceholderItem && !oldPlaceholderItem.destroyed ? oldPlaceholderItem : null); }, updatePlaceholderItem: function(placeholderItem, oldPlaceholderItem) { var me = this, items = me.items; if (items && items.isMixedCollection) { if (oldPlaceholderItem) { me.remove(oldPlaceholderItem); } if (placeholderItem) { me.insert(0, placeholderItem); } } }, // container lifecycle initPlaceholderItem: function() { var me = this, placeholderItem = me.getPlaceholderItem(); if (placeholderItem) { me.insert(0, placeholderItem); } } });
Fix wrong key in websocket message
from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from info_internet_connection.models import Internet import datetime import huawei_b593_status import json import redis #{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connected'} class Command(BaseCommand): args = '' help = 'Fetches home 4g router status information' def handle(self, *args, **options): r = redis.StrictRedis() status = huawei_b593_status.HuaweiStatus() data = status.read() age_threshold = datetime.timedelta(minutes=2) try: latest_data = Internet.objects.latest() if now() - latest_data.timestamp > age_threshold: latest_data = Internet() except Internet.DoesNotExist: latest_data = Internet() latest_data.wifi = data["WIFI"] != "off" latest_data.signal = int(data["SIG"]) latest_data.mode = data["Mode"] latest_data.sim = data["SIM"] latest_data.connect_status = data["Connect"] latest_data.update_timestamp = now() latest_data.save() r.publish("home:broadcast:generic", json.dumps({"key": "internet", "content": "updated"}) # TODO: send all information
from django.core.management.base import BaseCommand, CommandError from django.utils.timezone import now from info_internet_connection.models import Internet import datetime import huawei_b593_status import json import redis #{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connected'} class Command(BaseCommand): args = '' help = 'Fetches home 4g router status information' def handle(self, *args, **options): r = redis.StrictRedis() status = huawei_b593_status.HuaweiStatus() data = status.read() age_threshold = datetime.timedelta(minutes=2) try: latest_data = Internet.objects.latest() if now() - latest_data.timestamp > age_threshold: latest_data = Internet() except Internet.DoesNotExist: latest_data = Internet() latest_data.wifi = data["WIFI"] != "off" latest_data.signal = int(data["SIG"]) latest_data.mode = data["Mode"] latest_data.sim = data["SIM"] latest_data.connect_status = data["Connect"] latest_data.update_timestamp = now() latest_data.save() r.publish("home:broadcast:generic", json.dumps({"key": "internet", "value": "updated"}) # TODO: send all information
Remove default classifier path from default config
""" Base line settings """ CONFIG = { 'input_path': None, 'backup_path': None, 'dest_path': None, 'life_all': None, 'db': { 'host': None, 'port': None, 'name': None, 'user': None, 'pass': None }, # 'preprocess': { # 'max_acc': 30.0 # }, 'smoothing': { 'use': True, 'algorithm': 'inverse', 'noise': 10 }, 'segmentation': { 'use': True, 'epsilon': 1.0, 'min_time': 80 }, 'simplification': { 'max_dist_error': 2.0, 'max_speed_error': 1.0, 'eps': 0.15 }, 'location': { 'max_distance': 20, 'min_samples': 2, 'limit': 5, 'google_key': '' }, 'transportation': { 'remove_stops': False, 'min_time': 60, 'classifier_path': None#'classifier.data'# None }, 'trip_learning': { 'epsilon': 0.0, 'classifier_path': None, }, 'trip_name_format': '%Y-%m-%d' }
""" Base line settings """ CONFIG = { 'input_path': None, 'backup_path': None, 'dest_path': None, 'life_all': None, 'db': { 'host': None, 'port': None, 'name': None, 'user': None, 'pass': None }, # 'preprocess': { # 'max_acc': 30.0 # }, 'smoothing': { 'use': True, 'algorithm': 'inverse', 'noise': 10 }, 'segmentation': { 'use': True, 'epsilon': 1.0, 'min_time': 80 }, 'simplification': { 'max_dist_error': 2.0, 'max_speed_error': 1.0, 'eps': 0.15 }, 'location': { 'max_distance': 20, 'min_samples': 2, 'limit': 5, 'google_key': '' }, 'transportation': { 'remove_stops': False, 'min_time': 60, 'classifier_path': 'classifier.data'# None }, 'trip_learning': { 'epsilon': 0.0, 'classifier_path': None, }, 'trip_name_format': '%Y-%m-%d' }
Test that .info() and .warn() set the correct event type. Former-commit-id: 17449ebde702c82594b0d592047ae7c684f14fc9
package org.gem.log; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; public class AMQPAppenderTest { private DummyChannel dummyChannel; private DummyAppender dummyAppender; private Logger logger = Logger.getLogger(AMQPAppenderTest.class); void tearDown() { dummyChannel = null; dummyAppender = null; // this closes the RabbitMQ connections BasicConfigurator.resetConfiguration(); } private void setUpDummyAppender() { dummyAppender = new DummyAppender(); dummyAppender.setLayout(new PatternLayout()); BasicConfigurator.configure(dummyAppender); } @Test public void basicLogging() { setUpDummyAppender(); logger.info("Test1"); logger.warn("Test2"); dummyChannel = (DummyChannel) dummyAppender.getChannel(); assertThat(dummyChannel.entries.size(), is(equalTo(2))); DummyChannel.Entry entry1 = dummyChannel.entries.get(0); assertThat(entry1.exchange, is(equalTo(""))); assertThat(entry1.routingKey, is(equalTo(""))); assertThat(entry1.properties.getType(), is(equalTo("INFO"))); assertThat(entry1.body, is(equalTo("Test1\n"))); DummyChannel.Entry entry2 = dummyChannel.entries.get(1); assertThat(entry2.exchange, is(equalTo(""))); assertThat(entry2.routingKey, is(equalTo(""))); assertThat(entry2.properties.getType(), is(equalTo("WARN"))); assertThat(entry2.body, is(equalTo("Test2\n"))); } }
package org.gem.log; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; public class AMQPAppenderTest { private DummyChannel dummyChannel; private DummyAppender dummyAppender; private Logger logger = Logger.getLogger(AMQPAppenderTest.class); void tearDown() { dummyChannel = null; dummyAppender = null; // this closes the RabbitMQ connections BasicConfigurator.resetConfiguration(); } private void setUpDummyAppender() { dummyAppender = new DummyAppender(); dummyAppender.setLayout(new PatternLayout()); BasicConfigurator.configure(dummyAppender); } @Test public void basicLogging() { setUpDummyAppender(); logger.info("Test"); dummyChannel = (DummyChannel) dummyAppender.getChannel(); assertThat(dummyChannel.entries.size(), is(equalTo(1))); DummyChannel.Entry entry = dummyChannel.entries.get(0); assertThat(entry.exchange, is(equalTo(""))); assertThat(entry.routingKey, is(equalTo(""))); assertThat(entry.properties.getType(), is(equalTo("INFO"))); assertThat(entry.body, is(equalTo("Test\n"))); } }
Convert settings.INSTALLED_APPS to list before concatenating django. According to the Django documentation settings.INSTALLED_APPS is a tuple. To go for sure that only list + list are concatenated, settings.INSTALLED_APPS is converted to list type before adding ['django'].
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/versions.html' has_content = True def nav_title(self): return _('Versions') def nav_subtitle(self): return 'Django %s' % django.get_version() def url(self): return '' def title(self): return _('Versions') def process_response(self, request, response): versions = {} versions['Python'] = '%d.%d.%d' % sys.version_info[:3] for app in list(settings.INSTALLED_APPS) + ['django']: name = app.split('.')[-1].replace('_', ' ').capitalize() __import__(app) app = sys.modules[app] if hasattr(app, 'get_version'): get_version = app.get_version if callable(get_version): version = get_version() else: version = get_version elif hasattr(app, 'VERSION'): version = app.VERSION elif hasattr(app, '__version__'): version = app.__version__ else: continue if isinstance(version, (list, tuple)): version = '.'.join(str(o) for o in version) versions[name] = version self.record_stats({ 'versions': versions, 'paths': sys.path, })
import sys import django from django.conf import settings from django.utils.translation import ugettext_lazy as _ from debug_toolbar.panels import DebugPanel class VersionDebugPanel(DebugPanel): """ Panel that displays the Django version. """ name = 'Version' template = 'debug_toolbar/panels/versions.html' has_content = True def nav_title(self): return _('Versions') def nav_subtitle(self): return 'Django %s' % django.get_version() def url(self): return '' def title(self): return _('Versions') def process_response(self, request, response): versions = {} versions['Python'] = '%d.%d.%d' % sys.version_info[:3] for app in settings.INSTALLED_APPS + ['django']: name = app.split('.')[-1].replace('_', ' ').capitalize() __import__(app) app = sys.modules[app] if hasattr(app, 'get_version'): get_version = app.get_version if callable(get_version): version = get_version() else: version = get_version elif hasattr(app, 'VERSION'): version = app.VERSION elif hasattr(app, '__version__'): version = app.__version__ else: continue if isinstance(version, (list, tuple)): version = '.'.join(str(o) for o in version) versions[name] = version self.record_stats({ 'versions': versions, 'paths': sys.path, })
Set the autocomplete list size to 10 elements maximum.
var autocomplete = { // options for the EasyAutocomplete API setUp: function(input) { $input = $(input); options = { adjustWidth: false, data: autocompleteDict[$input.attr('name')], getValue: 'name', template: { type: 'custom', method: function(value, item) { return value + ' <span class="label radius">' + item.count + '</span>'; } }, list: { match: { enabled: true, method: function(element, phrase) { if (element.indexOf(phrase) === 0) { return true; } else { return false; } } }, maxNumberOfElements: 10, sort: { enabled: true }, onChooseEvent: function() { $input.closest('form').submit(); }, }, placeholder: $input.attr('title') }; $input.easyAutocomplete(options); }, init: function() { self = this; $('input.autocomplete').each(function() { self.setUp(this); }); } }; $(document).ready(function() { autocomplete.init(); });
var autocomplete = { // options for the EasyAutocomplete API setUp: function(input) { $input = $(input); options = { adjustWidth: false, data: autocompleteDict[$input.attr('name')], getValue: 'name', template: { type: 'custom', method: function(value, item) { return value + ' <span class="label radius">' + item.count + '</span>'; } }, list: { match: { enabled: true, method: function(element, phrase) { if (element.indexOf(phrase) === 0) { return true; } else { return false; } } }, maxNumberOfElements: 20, sort: { enabled: true }, onChooseEvent: function() { $input.closest('form').submit(); }, }, placeholder: $input.attr('title') }; $input.easyAutocomplete(options); }, init: function() { self = this; $('input.autocomplete').each(function() { self.setUp(this); }); } }; $(document).ready(function() { autocomplete.init(); });
Fix redirect generation for reverse proxied solutions
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.script_root + request.path return redirect(url_for(".login")) return nufun
from datetime import timedelta, datetime from functools import wraps import hmac from hashlib import sha1 from flask import Blueprint, session, redirect, url_for, request, current_app ADMIN = "valid_admin" TIME_FORMAT = '%Y%m%d%H%M%S' TIME_LIMIT = timedelta(hours=3) def _create_hmac(payload): key = current_app.config["SECRET_KEY"] payload = payload.encode("utf8") mac = hmac.new(key, payload, sha1) return mac.hexdigest() def set_token(): expire = datetime.now() + TIME_LIMIT token = expire.strftime(TIME_FORMAT) session[ADMIN] = "%s|%s" % (token, _create_hmac(token)) def delete_token(): del session[ADMIN] def _valid_token(token): try: token, token_mac = token.split(u"|", 1) except: return False if not token_mac == _create_hmac(token): return False if datetime.now().strftime(TIME_FORMAT) < token: return True def valid_admin(fn): @wraps(fn) def nufun(*args, **kwargs): if ADMIN in session: if _valid_token(session[ADMIN]): set_token() return fn(*args, **kwargs) delete_token() session["next"] = request.path return redirect(url_for(".login")) return nufun
Change name: logged_in => check_online
import subprocess import requests def check_online(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', data={'action': 'check_online'}) if r: # status: OK infos = r.text.split(',') if len(infos) == 5: # Decode successfully return dict(username=infos[1], byte=infos[2], duration=infos[4]) # Failed to get infos return False def arp_scan(): """Generate (IP, MAC) pairs using arp-scan""" proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE) out = proc.stdout # Skip the first two lines. next(out) next(out) # Parse IPs & MACs for line in out: infos = line.split() if not infos: # Empty line at the end of the output return if len(infos) < 2: raise RuntimeError('Invalid output of arp-scan: "%s"' % line) yield (infos[0], infos[1]) # Generate (IP, MAC)
import subprocess import requests def logged_in(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', data={'action': 'check_online'}) if r: # status: OK infos = r.text.split(',') if len(infos) == 5: # Decode successfully return dict(username=infos[1], byte=infos[2], duration=infos[4]) # Failed to get infos return False def arp_scan(): """Generate (IP, MAC) pairs using arp-scan""" proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE) out = proc.stdout # Skip the first two lines. next(out) next(out) # Parse IPs & MACs for line in out: infos = line.split() if not infos: # Empty line at the end of the output return if len(infos) < 2: raise RuntimeError('Invalid output of arp-scan: "%s"' % line) yield (infos[0], infos[1]) # Generate (IP, MAC)
Add interims link and reword narratives
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', //TODO: Delete extra link when nav panel arrow collapse is fixed title: 'Student Progress', data: true, applyData: function(data) { if (data !== true) { return data; } return [ { href: '#progress/interims', text: 'Section Interim Reports', children: [ { href: '#progress/interims/print', text: 'Search & Print' } // { // href: '#progress/interims/email', text: 'Email' // } ] }, { href: '#progress/narratives', text: 'Section Term Reports', children: [ { href: '#progress/narratives/print', text: 'Search & Print' } // { // href: '#progress/narratives/email', text: 'Email' // } ] } ]; } });
/*jslint browser: true, undef: true *//*global Ext*/ Ext.define('SlateAdmin.view.progress.NavPanel', { extend: 'SlateAdmin.view.LinksNavPanel', xtype: 'progress-navpanel', //TODO: Delete extra link when nav panel arrow collapse is fixed title: 'Student Progress', data: true, applyData: function(data) { if (data !== true) { return data; } return location.search.match(/\Wenablesbg(\W|$)/) ? [ { href: '#progress/standards', text: 'Standards Based Grades', children: [{ href: '#progress/standards/worksheets', text: 'Manage Worksheets' },{ href: '#progress/standards/printing', text: 'Search & Print' }] }, { href: '#progress/standards/worksheets', text: 'Manage Worksheets' },{ href: '#progress/standards/printing', text: 'Search & Print' }, { href: '#progress/narratives', text: 'Narrative Reports', children: [{ href: '#progress/narratives/printing', text: 'Search & Print' },{ href: '#progress/narratives/email', text: 'Email' }] }, { href: '#progress/narratives/printing', text: 'Search & Print' }, { href: '#progress/interims', text: 'Interim Reports', children: [{ href: '#progress/interims/printing', text: 'Search & Print' },{ href: '#progress/interims/email', text: 'Email' }] }, { href: '#progress/interims/printing', text: 'Search & Print' },{ href: '#progress/interims/email', text: 'Email' } ] : [ { href: '#progress/narratives', text: 'Narrative Reports' }, { href: '#progress/narratives/printing', text: '↳ Search & Print' },{ href: '#progress/narratives/email', text: 'Email' } ]; } });
Fix accidental typo that snuck in
(function (window){ requirejs([ 'underscore', 'backbone', 'BB' ], function(_, Backbone, BB) { BB.model_definitions.search = Backbone.Model.extend({ defaults: {}, initialize: function(){ if(BB.bootstrapped.filters){ this.set(BB.bootstrapped.filters); } else { var model = this; $.ajax({ url: '/search', dataType: 'json', contentType : 'application/json', success: function(data){ model.set(data); } }); } }, url: '/api/search' }); }); })(window);
(function (window){ requirejs([ 'underscore', 'backbone', 'BB' ], function(_, Backbone, BB) { BB.model_definitions.search = Backbone.Model.extend({ defaults: {}, initialize: function(){ if(BB.bootstrapped.filters4){ this.set(BB.bootstrapped.filters); } else { var model = this; $.ajax({ url: '/search', dataType: 'json', contentType : 'application/json', success: function(data){ model.set(data); } }); } }, url: '/api/search' }); }); })(window);
Fix approximate count double test Use DoubleType instead of BigintType
/* * 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. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.spi.type.Type; import com.facebook.presto.util.IterableTransformer; import com.google.common.base.Predicates; import java.util.List; import static com.facebook.presto.operator.aggregation.ApproximateCountColumnAggregations.DOUBLE_APPROXIMATE_COUNT_AGGREGATION; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; public class TestApproximateCountDoubleAggregation extends AbstractTestApproximateAggregationFunction { @Override protected Type getType() { return DOUBLE; } @Override protected Double getExpectedValue(List<Number> values) { return (double) IterableTransformer.on(values) .select(Predicates.notNull()) .list() .size(); } @Override public InternalAggregationFunction getFunction() { return DOUBLE_APPROXIMATE_COUNT_AGGREGATION; } }
/* * 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. */ package com.facebook.presto.operator.aggregation; import com.facebook.presto.spi.type.Type; import com.facebook.presto.util.IterableTransformer; import com.google.common.base.Predicates; import java.util.List; import static com.facebook.presto.operator.aggregation.ApproximateCountColumnAggregations.DOUBLE_APPROXIMATE_COUNT_AGGREGATION; import static com.facebook.presto.spi.type.BigintType.BIGINT; public class TestApproximateCountDoubleAggregation extends AbstractTestApproximateAggregationFunction { @Override protected Type getType() { return BIGINT; } @Override protected Double getExpectedValue(List<Number> values) { return (double) IterableTransformer.on(values) .select(Predicates.notNull()) .list() .size(); } @Override public InternalAggregationFunction getFunction() { return DOUBLE_APPROXIMATE_COUNT_AGGREGATION; } }
Establish new session upon login.
package controllers; import play.*; import play.data.*; import play.mvc.*; import views.html.*; import static play.data.Form.*; public class Application extends Controller { public static Result home() { return ok(home.render("Hi! This is Ode.")); } public static Result login() { return ok(login.render("Hi! Use the form below to log in.", form(Login.class))); } public static Result authenticate() { Form<Login> loginForm = form(Login.class).bindFromRequest(); if (loginForm.hasErrors()) { return badRequest(login.render("Do I know you?", loginForm)); } else { session().clear(); session("email", loginForm.get().email); return redirect(routes.Application.home()); } } public static Result rules() { return ok(rules.render("Hi! This is Ode's Rule Browser.")); } public static Result rule(int id) { return ok(rule.render("Hi! You are looking at rule " + id + ".")); } public static Result search() { return ok(search.render("Hi! This is Ode's Search Interface.")); } public static Result features() { return ok(features.render("Hi! This is Ode's Feature Editor.")); } // Forms public static class Login { public String email; public String password; public String validate() { if (email == "" || password == "") { return "You must provide input for all fields."; } return null; } } }
package controllers; import play.*; import play.data.*; import play.mvc.*; import views.html.*; import static play.data.Form.*; public class Application extends Controller { public static Result home() { return ok(home.render("Hi! This is Ode.")); } public static Result login() { return ok(login.render("Hi! Use the form below to log in.", form(Login.class))); } public static Result authenticate() { Form<Login> loginForm = form(Login.class).bindFromRequest(); if (loginForm.hasErrors()) { return badRequest(login.render("Do I know you?", loginForm)); } else { return redirect(routes.Application.home()); } } public static Result rules() { return ok(rules.render("Hi! This is Ode's Rule Browser.")); } public static Result rule(int id) { return ok(rule.render("Hi! You are looking at rule " + id + ".")); } public static Result search() { return ok(search.render("Hi! This is Ode's Search Interface.")); } public static Result features() { return ok(features.render("Hi! This is Ode's Feature Editor.")); } // Forms public static class Login { public String email; public String password; public String validate() { if (email == "" || password == "") { return "You must provide input for all fields."; } return null; } } }
Fix token getter and improve error reporting
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeTokens = [], getter) { if (storeTokens.some(token => token === undefined)) { throw new TypeError('@listeningTo cannot handle undefined tokens'); } return decorator; function decorator(ChildComponent) { class ListeningContainerComponent extends Component { static contextTypes = { dependencyCache: PropTypes.instanceOf(Map) } static Original = ChildComponent getStores() { const {dependencyCache} = this.context; return lodash.map(storeTokens, token => { if (typeof token === 'string') { return this.props[token]; } else { if (dependencyCache.has(token)) { return dependencyCache.get(token); } else { throw new RangeError(`@listeningTo cannot find ${token.name || token} in dependency cache`); } } }); } componentDidMount() { lodash.each(this.stores, store => { store.on('change', this.setStateFromStores); }); } componentWillUnmount() { lodash.each(this.stores, store => { store.removeListener('change', this.setStateFromStores); }); } constructor(props, context) { super(props, context); this.stores = this.getStores(); this.state = { childProps: getter(this.props) }; this.setStateFromStores = () => { this.setState({ childProps: getter(this.props) }); }; } render() { const {childProps} = this.state; return <ChildComponent {...this.props} {...childProps}/>; } } return ListeningContainerComponent; } }
import React, {Component, PropTypes} from 'react'; import lodash from 'lodash'; export function listeningTo(storeTokens, getter) { return decorator; function decorator(ChildComponent) { class ListeningContainerComponent extends Component { static contextTypes = { dependencyCache: PropTypes.instanceOf(Map) } static Original = ChildComponent getStores() { const {dependencyCache} = this.context; return lodash.map(storeTokens, name => { if (typeof this.props[name] === 'string') { return this.props[name]; } else { return dependencyCache.get([name]); } }); } componentDidMount() { lodash.each(this.stores, store => { store.on('change', this.setStateFromStores); }); } componentWillUnmount() { lodash.each(this.stores, store => { store.removeListener('change', this.setStateFromStores); }); } constructor(props, context) { super(props, context); this.stores = this.getStores(); this.state = { childProps: getter(this.props) }; this.setStateFromStores = () => { this.setState({ childProps: getter(this.props) }); }; } render() { const {childProps} = this.state; return <ChildComponent {...this.props} {...childProps}/>; } } return ListeningContainerComponent; } }
BB-4780: Convert Organization scope to Global in NavigationBundle, remove Website and AccountUser scope from FrontendNavigationBundle - removed unused constant
<?php namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class MenuUpdateProviderPass implements CompilerPassInterface { const BUILDER_SERVICE_ID = 'oro_navigation.menu_update.builder'; const OWNERSHIP_PROVIDER_TAG = 'oro_navigation.ownership_provider'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $this->processUpdateProviders($container); } /** * @param ContainerBuilder $container */ protected function processUpdateProviders(ContainerBuilder $container) { if (!$container->hasDefinition(self::BUILDER_SERVICE_ID)) { return; } $providers = $container->findTaggedServiceIds(self::OWNERSHIP_PROVIDER_TAG); if (!$providers) { return; } $builderService = $container->getDefinition(self::BUILDER_SERVICE_ID); foreach ($providers as $id => $tags) { foreach ($tags as $attributes) { $builderService->addMethodCall( 'addProvider', [new Reference($id), $attributes['area'], $attributes['priority']] ); } } } }
<?php namespace Oro\Bundle\NavigationBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; class MenuUpdateProviderPass implements CompilerPassInterface { const BUILDER_SERVICE_ID = 'oro_navigation.menu_update.builder'; const MENU_UPDATE_PROVIDER_SERVICE_ID = 'oro_navigation.menu_update_provider.default'; const OWNERSHIP_PROVIDER_TAG = 'oro_navigation.ownership_provider'; /** * {@inheritdoc} */ public function process(ContainerBuilder $container) { $this->processUpdateProviders($container); } /** * @param ContainerBuilder $container */ protected function processUpdateProviders(ContainerBuilder $container) { if (!$container->hasDefinition(self::BUILDER_SERVICE_ID)) { return; } $providers = $container->findTaggedServiceIds(self::OWNERSHIP_PROVIDER_TAG); if (!$providers) { return; } $builderService = $container->getDefinition(self::BUILDER_SERVICE_ID); foreach ($providers as $id => $tags) { foreach ($tags as $attributes) { $builderService->addMethodCall( 'addProvider', [new Reference($id), $attributes['area'], $attributes['priority']] ); } } } }
Change string formating for Credential
import os class Credential(object): def __init__(self, name, login, password, comments): self.name = name self.login = login self.password = password self.comments = comments def save(self, database_path): credential_path = os.path.join(database_path, self.name) os.makedirs(credential_path) with open(os.path.join(credential_path, "login"), "w") as f: f.write(self.login) with open(os.path.join(credential_path, "password"), "w") as f: f.write(self.password) with open(os.path.join(credential_path, "comments"), "w") as f: f.write(self.comments) @classmethod def from_path(cls, path): return Credential( name=os.path.basename(path), login=open(path + "/login").read(), password=open(path + "/password").read(), comments=open(path + "/comments").read() ) def __str__(self): return "<name={}, login={}, password='...', {}>".format( self.name, self.login, self.comments )
import os class Credential(object): def __init__(self, name, login, password, comments): self.name = name self.login = login self.password = password self.comments = comments def save(self, database_path): credential_path = os.path.join(database_path, self.name) os.makedirs(credential_path) with open(os.path.join(credential_path, "login"), "w") as f: f.write(self.login) with open(os.path.join(credential_path, "password"), "w") as f: f.write(self.password) with open(os.path.join(credential_path, "comments"), "w") as f: f.write(self.comments) @classmethod def from_path(cls, path): return Credential( name=os.path.basename(path), login=open(path + "/login").read(), password=open(path + "/password").read(), comments=open(path + "/comments").read() ) def __str__(self): return "<Credential: name={}, login={}, password='...', {}>".format( self.name, self.login, self.comments )
Fix casting in form to_python() method NetAddressFormField.to_python() was calling "self.python_type()" to cast the form value to an IP() object. Unfortunately, for is no such method defined here, or in the Django forms.Field() class, at least in 1.4 and up
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return IP(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
import re from IPy import IP from django import forms from django.utils.encoding import force_unicode from django.utils.safestring import mark_safe class NetInput(forms.Widget): input_type = 'text' def render(self, name, value, attrs=None): # Default forms.Widget compares value != '' which breaks IP... if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value: final_attrs['value'] = force_unicode(value) return mark_safe(u'<input%s />' % forms.util.flatatt(final_attrs)) class NetAddressFormField(forms.Field): widget = NetInput default_error_messages = { 'invalid': u'Enter a valid IP Address.', } def __init__(self, *args, **kwargs): super(NetAddressFormField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: return None if isinstance(value, IP): return value return self.python_type(value) MAC_RE = re.compile(r'^(([A-F0-9]{2}:){5}[A-F0-9]{2})$') class MACAddressFormField(forms.RegexField): default_error_messages = { 'invalid': u'Enter a valid MAC address.', } def __init__(self, *args, **kwargs): super(MACAddressFormField, self).__init__(MAC_RE, *args, **kwargs)
Fix repeated prompt bug in keep run
import json import os import re import click from keep import cli, utils @click.command('run', short_help='Executes a saved command.') @click.argument('pattern') @cli.pass_context def cli(ctx, pattern): """Executes a saved command.""" json_path = os.path.join(os.path.expanduser('~'), '.keep', 'commands.json') if not os.path.exists(json_path): click.echo('No commands to run. Add one by `keep new`.') else: FOUND = False for cmd, desc in json.loads(open(json_path, 'r').read()).items(): if re.search(pattern, cmd + " :: " + desc): FOUND = True if click.confirm("Execute\n\n\t{}\n\n\n?".format(cmd), default=True): os.system(cmd) break # Execute if all the parts of the pattern are in one command/desc keywords_len = len(pattern.split()) i_keyword = 0 for keyword in pattern.split(): if keyword.lower() in cmd.lower() or keyword.lower() in desc.lower(): FOUND = True i_keyword += 1 if i_keyword == keywords_len: if click.confirm("Execute\n\n\t{}\n\n\n?".format(cmd), default=True): os.system(cmd) break if not FOUND: click.echo('No saved commands matches the pattern "{}"'.format(pattern))
import json import os import re import click from keep import cli, utils @click.command('run', short_help='Executes a saved command.') @click.argument('pattern') @cli.pass_context def cli(ctx, pattern): """Executes a saved command.""" json_path = os.path.join(os.path.expanduser('~'), '.keep', 'commands.json') if not os.path.exists(json_path): click.echo('No commands to run. Add one by `keep new`.') else: FOUND = False for cmd, desc in json.loads(open(json_path, 'r').read()).items(): if re.search(pattern, cmd + " :: " + desc): FOUND = True if click.confirm("Execute\n\n\t{}\n\n\n?".format(cmd), default=True): os.system(cmd) break # Execute if all the parts of the pattern are in one command/desc keywords_len = len(pattern.split()) i_keyword = 0 for keyword in pattern.split(): if keyword.lower() in cmd.lower() or keyword.lower() in desc.lower(): FOUND = True i_keyword += 1 if i_keyword == keywords_len: if click.confirm("Execute\n\n\t{}\n\n\n?".format(cmd), default=True): os.system(cmd) break if not FOUND: click.echo('No saved commands matches the pattern "{}"'.format(pattern))
Write db errors to error.log
import threading import time import accounts import args import config import log as _log MAX_TEXT_LENGTH = 1024 enabled = bool(args.args['database']) if enabled: import MySQLdb connected = False conn = None cur = None db_lock = threading.RLock() def _connect(): global conn, cur, connected if not connected: conn = MySQLdb.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database'), charset='utf8mb4') cur = conn.cursor() connected = True def log(message, kind, text_msg=None): global connected, enabled if enabled: if not config.get('db_logger.host') or not config.get('db_logger.database'): print('Incorrect database configuration!') enabled = False return with db_lock: try: _connect() if text_msg is None: text_msg = message text_msg = text_msg[:MAX_TEXT_LENGTH] cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW(), %s, %s)', (message, kind, text_msg, accounts.current_account)) conn.commit() except MySQLdb.Error as e: print(e, flush=True) _log.write('error', 'MySQL error: ' + str(e)) time.sleep(5) connected = False log(message, kind, text_msg)
import threading import time import accounts import args import config MAX_TEXT_LENGTH = 1024 enabled = bool(args.args['database']) if enabled: import MySQLdb connected = False conn = None cur = None db_lock = threading.RLock() def _connect(): global conn, cur, connected if not connected: conn = MySQLdb.connect(host=config.get('db_logger.host'), user=config.get('db_logger.username'), password=config.get('db_logger.password'), database=config.get('db_logger.database'), charset='utf8mb4') cur = conn.cursor() connected = True def log(message, kind, text_msg=None): global connected, enabled if enabled: if not config.get('db_logger.host') or not config.get('db_logger.database'): print('Incorrect database configuration!') enabled = False return with db_lock: try: _connect() if text_msg is None: text_msg = message text_msg = text_msg[:MAX_TEXT_LENGTH] cur.execute('INSERT INTO vkbot_logmessage VALUES (NULL, %s, %s, NOW(), %s, %s)', (message, kind, text_msg, accounts.current_account)) conn.commit() except MySQLdb.Error as e: print(e, flush=True) time.sleep(5) connected = False log(message, kind, text_msg)
Comment out fix_fee_product_index from migration
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): try: schema_editor.execute( 'DROP INDEX idx_16977_product_id;' 'ALTER TABLE cfpb.ratechecker_fee ' 'DROP CONSTRAINT IF EXISTS idx_16977_product_id;' 'ALTER TABLE cfpb.ratechecker_fee ' 'ADD CONSTRAINT idx_16977_product_id ' 'UNIQUE (product_id, state_id, lender, single_family, condo, coop);' ) except (ProgrammingError, OperationalError): pass class Migration(migrations.Migration): dependencies = [ ('ratechecker', '0001_initial'), ] operations = [ #migrations.RunPython(fix_fee_product_index), migrations.AlterUniqueTogether( name='fee', unique_together=set([]), ), migrations.RemoveField( model_name='fee', name='plan', ), migrations.DeleteModel( name='Fee', ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-10-31 16:33 from __future__ import unicode_literals from django.db import migrations, OperationalError, ProgrammingError def fix_fee_product_index(apps, schema_editor): table_name = 'cfpb.ratechecker_fee' index_name = 'idx_16977_product_id' try: schema_editor.execute( 'DROP INDEX idx_16977_product_id;' 'ALTER TABLE cfpb.ratechecker_fee ' 'DROP CONSTRAINT IF EXISTS idx_16977_product_id;' 'ALTER TABLE cfpb.ratechecker_fee ' 'ADD CONSTRAINT idx_16977_product_id ' 'UNIQUE (product_id, state_id, lender, single_family, condo, coop);' ) except (ProgrammingError, OperationalError): pass class Migration(migrations.Migration): dependencies = [ ('ratechecker', '0001_initial'), ] operations = [ migrations.RunPython(fix_fee_product_index), migrations.AlterUniqueTogether( name='fee', unique_together=set([]), ), migrations.RemoveField( model_name='fee', name='plan', ), migrations.DeleteModel( name='Fee', ), ]
Test port change for hapi-auth-hawk plugin
/** * Created by Omnius on 6/15/16. */ 'use strict'; const Boom = require('boom'); exports.register = (server, options, next) => { server.auth.strategy('hawk-login-auth-strategy', 'hawk', { getCredentialsFunc: (sessionId, callback) => { const redis = server.app.redis; const methods = server.methods; const dao = methods.dao; const userCredentialDao = dao.userCredentialDao; userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => { if (err) { server.log(err); return callback(Boom.serverUnavailable(err)); } if (!Object.keys(dbCredentials).length) { return callback(Boom.forbidden()); } const credentials = { hawkSessionToken: dbCredentials.hawkSessionToken, algorithm: dbCredentials.algorithm, userId: dbCredentials.userId, key: dbCredentials.key, id: dbCredentials.id }; return callback(null, credentials); }); }, hawk: { port: 443 } }); next(); }; exports.register.attributes = { pkg: require('./package.json') };
/** * Created by Omnius on 6/15/16. */ 'use strict'; const Boom = require('boom'); exports.register = (server, options, next) => { server.auth.strategy('hawk-login-auth-strategy', 'hawk', { getCredentialsFunc: (sessionId, callback) => { const redis = server.app.redis; const methods = server.methods; const dao = methods.dao; const userCredentialDao = dao.userCredentialDao; userCredentialDao.readUserCredential(redis, sessionId, (err, dbCredentials) => { if (err) { server.log(err); return callback(Boom.serverUnavailable(err)); } if (!Object.keys(dbCredentials).length) { return callback(Boom.forbidden()); } const credentials = { hawkSessionToken: dbCredentials.hawkSessionToken, algorithm: dbCredentials.algorithm, userId: dbCredentials.userId, key: dbCredentials.key, id: dbCredentials.id }; return callback(null, credentials); }); } }); next(); }; exports.register.attributes = { pkg: require('./package.json') };
9397: Fix warning when rendering null value
import React from 'react'; import PropTypes from 'prop-types'; class FormSelect extends React.Component { static propTypes = { id: PropTypes.string, includeBlank: PropTypes.bool, name: PropTypes.string, options: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, name: PropTypes.string, })).isRequired, prompt: PropTypes.string, value: PropTypes.node, onChange: PropTypes.func, }; static defaultProps = { includeBlank: true, }; render() { const { options, prompt, includeBlank, name, id, value, onChange } = this.props; const optionTags = []; if (prompt || includeBlank !== false) { optionTags.push( <option key="blank" value="" > {prompt || ''} </option>, ); } options.forEach((o) => optionTags.push( <option key={o.id} value={o.id} > {o.name} </option>, )); const props = { className: 'form-control', name, id, key: id, value: value || '', onChange: onChange ? (e) => onChange(e.target.value) : undefined, }; return ( <select {...props}> {optionTags} </select> ); } } export default FormSelect;
import React from 'react'; import PropTypes from 'prop-types'; class FormSelect extends React.Component { static propTypes = { id: PropTypes.string, includeBlank: PropTypes.bool, name: PropTypes.string, options: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, name: PropTypes.string, })).isRequired, prompt: PropTypes.string, value: PropTypes.node, onChange: PropTypes.func, }; static defaultProps = { includeBlank: true, }; render() { const { options, prompt, includeBlank, name, id, value, onChange } = this.props; const optionTags = []; if (prompt || includeBlank !== false) { optionTags.push( <option key="blank" value="" > {prompt || ''} </option>, ); } options.forEach((o) => optionTags.push( <option key={o.id} value={o.id} > {o.name} </option>, )); const props = { className: 'form-control', name, id, key: id, value, onChange: onChange ? (e) => onChange(e.target.value) : undefined, }; return ( <select {...props}> {optionTags} </select> ); } } export default FormSelect;
Update ethereum tokens limit to 50
'use strict'; var axios = require('axios'); var db = require('./db'); var limit = 50; function save(tokens) { var operations = tokens.map(function(token) { return {replaceOne: {filter: {_id: token._id}, replacement: token, upsert: true}}; }); var collection = db().collection('ethereum_tokens'); return collection.bulkWrite(operations) .then(function() { return true; }); } function getFromAPI() { return axios({ url: 'https://api.ethplorer.io/getTop', params: { apiKey: 'freekey', criteria: 'cap', limit: limit } }).then(function(response) { if (!response.data) throw new Error('Bad ethereumTokens response'); response.data.tokens.shift(); var rank = 0; return response.data.tokens.map(function(item) { return { _id: rank++, address: item.address, name: item.name, decimals: parseInt(item.decimals), symbol: item.symbol, price: item.price ? parseFloat(item.price.rate) : 0.0, } }); }); } function getAllFromCache() { var collection = db().collection('ethereum_tokens'); return collection .find({}, {projection: {_id: 0}}) .sort({symbol: 1}) .limit(limit) .toArray(); } module.exports = { save: save, getFromAPI: getFromAPI, getAllFromCache: getAllFromCache };
'use strict'; var axios = require('axios'); var db = require('./db'); var limit = 100; function save(tokens) { var operations = tokens.map(function(token) { return {replaceOne: {filter: {_id: token._id}, replacement: token, upsert: true}}; }); var collection = db().collection('ethereum_tokens'); return collection.bulkWrite(operations) .then(function() { return true; }); } function getFromAPI() { return axios({ url: 'https://api.ethplorer.io/getTop', params: { apiKey: 'freekey', criteria: 'cap', limit: limit } }).then(function(response) { if (!response.data) throw new Error('Bad ethereumTokens response'); response.data.tokens.shift(); var rank = 0; return response.data.tokens.map(function(item) { return { _id: rank++, address: item.address, name: item.name, decimals: parseInt(item.decimals), symbol: item.symbol, price: item.price ? parseFloat(item.price.rate) : 0.0, } }); }); } function getAllFromCache() { var collection = db().collection('ethereum_tokens'); return collection .find({}, {projection: {_id: 0}}) .sort({symbol: 1}) .limit(limit) .toArray(); } module.exports = { save: save, getFromAPI: getFromAPI, getAllFromCache: getAllFromCache };
Use the same vocabulary to make a findDate as well as retrieving it
<?php namespace App\Models; class FindEvent extends Base { public static $NODE_TYPE = 'E10'; public static $NODE_NAME = 'findEvent'; protected $has_unique_id = true; protected $related_models = [ 'P12' => [ 'key' => 'object', 'model_name' => 'Object', 'cascade_delete' => true ], 'P7' => [ 'key' => 'findSpot', 'model_name' => 'FindSpot', 'cascade_delete' => true ], 'P29' => [ 'key' => 'person', 'model_name' => 'person', 'cascade_delete' => false, 'link_only' => true, 'reverse_relationhip' => 'P29' ] ]; protected $implicit_models = [ [ 'relationship' => 'P4', 'config' => [ 'key' => 'findDate', 'name' => 'findDate', 'value_node' => true, 'cidoc_type' => 'E52' ] ], ]; }
<?php namespace App\Models; class FindEvent extends Base { public static $NODE_TYPE = 'E10'; public static $NODE_NAME = 'findEvent'; protected $has_unique_id = true; protected $related_models = [ 'P12' => [ 'key' => 'object', 'model_name' => 'Object', 'cascade_delete' => true ], 'P7' => [ 'key' => 'findSpot', 'model_name' => 'FindSpot', 'cascade_delete' => true ], 'P29' => [ 'key' => 'person', 'model_name' => 'person', 'cascade_delete' => false, 'link_only' => true, 'reverse_relationhip' => 'P29' ] ]; protected $implicit_models = [ [ 'relationship' => 'P4', 'config' => [ 'key' => 'findDate', 'name' => 'findPeriod', 'value_node' => true, 'cidoc_type' => 'E52' ] ], ]; }
Change iteritems to items, as it was breaking tests
from functools import wraps __version__ = '0.2.0' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. The names of the test methods follow the pattern ``test_func_name + "_" + str(data)``. If ``data.__name__`` exists, it is used instead for the test method name. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.items(): if hasattr(f, MAGIC): for i, v in enumerate(getattr(f, MAGIC)): test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) setattr(cls, test_name, feed_data(f, v)) delattr(cls, name) return cls
from functools import wraps __version__ = '0.2.0' MAGIC = '%values' # this value cannot conflict with any real python attribute def data(*values): """ Method decorator to add to your test methods. Should be added to methods of instances of ``unittest.TestCase``. """ def wrapper(func): setattr(func, MAGIC, values) return func return wrapper def ddt(cls): """ Class decorator for subclasses of ``unittest.TestCase``. Apply this decorator to the test case class, and then decorate test methods with ``@data``. For each method decorated with ``@data``, this will effectively create as many methods as data items are passed as parameters to ``@data``. The names of the test methods follow the pattern ``test_func_name + "_" + str(data)``. If ``data.__name__`` exists, it is used instead for the test method name. """ def feed_data(func, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) return wrapper for name, f in cls.__dict__.iteritems(): if hasattr(f, MAGIC): for i, v in enumerate(getattr(f, MAGIC)): test_name = getattr(v, "__name__", "{0}_{1}".format(name, v)) setattr(cls, test_name, feed_data(f, v)) delattr(cls, name) return cls
Fix Bitbucket Server appearing twice in the repository list. When Power Pack is installed, Bitbucket Server appears twice in the repository form's hosting list. This is because the fake entry was using the wrong module path for Bitbucket Server. This fixes that to use the right path, showing only a single entry. Testing Done: Loaded the repository form. Saw only a single, correct entry. Reviewed at https://reviews.reviewboard.org/r/9822/
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. """ hosting_service_id = None class FakeAWSCodeCommitHostingService(FakeHostingService): name = 'AWS CodeCommit' supported_scmtools = ['Git'] hosting_service_id = 'aws-codecommit' class FakeBitbucketServerHostingService(FakeHostingService): name = 'Bitbucket Server' supported_scmtools = ['Git'] hosting_service_id = 'bitbucket-server' class FakeGitHubEnterpriseHostingService(FakeHostingService): name = 'GitHub Enterprise' supported_scmtools = ['Git'] hosting_service_id = 'github-enterprise' class FakeVisualStudioTeamServicesHostingService(FakeHostingService): name = 'VisualStudio.com' supported_scmtools = [ 'Team Foundation Server', 'Team Foundation Server (git)', ] hosting_service_id = 'visual-studio-online' FAKE_HOSTING_SERVICES = { 'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit': FakeAWSCodeCommitHostingService, 'rbpowerpack.hostingsvcs.bitbucket_server.BitbucketServer': FakeBitbucketServerHostingService, 'rbpowerpack.hostingsvcs.githubenterprise.GitHubEnterprise': FakeGitHubEnterpriseHostingService, 'rbpowerpack.hostingsvcs.visualstudio.VisualStudioTeamServices': FakeVisualStudioTeamServicesHostingService, }
from __future__ import unicode_literals from reviewboard.hostingsvcs.service import HostingService class FakeHostingService(HostingService): """A hosting service that is not provided by Review Board. Fake hosting services are intended to be used to advertise for Beanbag, Inc.'s Power Pack extension. """ hosting_service_id = None class FakeAWSCodeCommitHostingService(FakeHostingService): name = 'AWS CodeCommit' supported_scmtools = ['Git'] hosting_service_id = 'aws-codecommit' class FakeBitbucketServerHostingService(FakeHostingService): name = 'Bitbucket Server' supported_scmtools = ['Git'] hosting_service_id = 'bitbucket-server' class FakeGitHubEnterpriseHostingService(FakeHostingService): name = 'GitHub Enterprise' supported_scmtools = ['Git'] hosting_service_id = 'github-enterprise' class FakeVisualStudioTeamServicesHostingService(FakeHostingService): name = 'VisualStudio.com' supported_scmtools = [ 'Team Foundation Server', 'Team Foundation Server (git)', ] hosting_service_id = 'visual-studio-online' FAKE_HOSTING_SERVICES = { 'rbpowerpack.hostingsvcs.aws_codecommit.AWSCodeCommit': FakeAWSCodeCommitHostingService, 'rbpowerpack.hostingsvcs.bitbucketserver.BitbucketServer': FakeBitbucketServerHostingService, 'rbpowerpack.hostingsvcs.githubenterprise.GitHubEnterprise': FakeGitHubEnterpriseHostingService, 'rbpowerpack.hostingsvcs.visualstudio.VisualStudioTeamServices': FakeVisualStudioTeamServicesHostingService, }
Unify cases of create and no create
import { select, local } from "d3-selection"; var componentLocal = local(), noop = function (){}; export default function (tagName, className){ var create, render = noop, destroy = noop, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className); enter.each(function (){ var local = componentLocal.set(this, { selection: select(this), state: {}, render: noop }); if(create){ create(function setState(state){ Object.assign(local.state, state); local.render(); }); } }); enter.merge(update).each(function (props){ var local = componentLocal.get(this); if(local.render === noop){ local.render = function (){ render(local.selection, local.props, local.state); }; } local.props = props; local.render(); }); exit.each(function (){ destroy(componentLocal.get(this).state); }); exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
import { select, local } from "d3-selection"; var componentLocal = local(), noop = function (){}; export default function (tagName, className){ var create, render = noop, destroy = noop, selector = className ? "." + className : tagName; function component(selection, props){ var update = selection.selectAll(selector) .data(Array.isArray(props) ? props : [props]), exit = update.exit(), enter = update.enter().append(tagName).attr("class", className); enter.each(function (){ componentLocal.set(this, { selection: select(this) }); }); if(create){ enter.each(function (){ var local = componentLocal.get(this); local.state = {}; local.render = noop; create(function setState(state){ Object.assign(local.state, state); local.render(); }); }); enter.merge(update).each(function (props){ var local = componentLocal.get(this); if(local.render === noop){ local.render = function (){ render(local.selection, local.props, local.state); }; } local.props = props; local.render(); }); exit.each(function (){ destroy(componentLocal.get(this).state); }); } else { enter.merge(update).each(function (props){ render(componentLocal.get(this).selection, props); }); } exit.remove(); } component.render = function(_) { return (render = _, component); }; component.create = function(_) { return (create = _, component); }; component.destroy = function(_) { return (destroy = _, component); }; return component; };
Use ->exec for generating the test SQL database from setup/
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <[email protected]> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace ImboBehatFeatureContext\DatabaseTest; use ImboBehatFeatureContext\AdapterTest; use Imbo\Database\Doctrine as Database; use PDO; /** * Class for suites that want to use the Doctrine database adapter with a SQLite database * * @author Christer Edvartsen <[email protected]> */ class DoctrineSQLite implements AdapterTest { /** * {@inheritdoc} */ static public function setUp(array $config) { $path = tempnam(sys_get_temp_dir(), 'imbo_behat_test_database_doctrine_sqlite'); // Create tmp tables $pdo = new PDO(sprintf('sqlite:%s', $path)); $sqlStatementsFile = sprintf('%s/setup/doctrine.sqlite.sql', $config['project_root']); $pdo->exec(file_get_contents($sqlStatementsFile)); return ['path' => $path]; } /** * {@inheritdoc} */ static public function tearDown(array $config) { unlink($config['path']); } /** * {@inheritdoc} */ static public function getAdapter(array $config) { return new Database([ 'path' => $config['path'], 'driver' => 'pdo_sqlite', ]); } }
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <[email protected]> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace ImboBehatFeatureContext\DatabaseTest; use ImboBehatFeatureContext\AdapterTest; use Imbo\Database\Doctrine as Database; use PDO; /** * Class for suites that want to use the Doctrine database adapter with a SQLite database * * @author Christer Edvartsen <[email protected]> */ class DoctrineSQLite implements AdapterTest { /** * {@inheritdoc} */ static public function setUp(array $config) { $path = tempnam(sys_get_temp_dir(), 'imbo_behat_test_database_doctrine_sqlite'); // Create tmp tables $pdo = new PDO(sprintf('sqlite:%s', $path)); $sqlStatementsFile = sprintf('%s/setup/doctrine.sqlite.sql', $config['project_root']); array_map(function($query) use ($pdo) { $pdo->query($query); }, explode("\n\n", file_get_contents($sqlStatementsFile))); return ['path' => $path]; } /** * {@inheritdoc} */ static public function tearDown(array $config) { unlink($config['path']); } /** * {@inheritdoc} */ static public function getAdapter(array $config) { return new Database([ 'path' => $config['path'], 'driver' => 'pdo_sqlite', ]); } }
Fix Events mixin callbacks binding.
define([ 'fossil/core', 'underscore', 'backbone' ], function (Fossil, _, Backbone) { var Events = Fossil.Mixins.Events = _.extend({}, Backbone.Events, { registerEvents: function () { var events = _.extend( {}, _.result(this, 'events'), _.result(this.options || {}, 'events') ); var observable = this; _.each(events, function (method, eventid) { // create callback from method // if it is not a function already, it should be a method if (!_.isFunction(method)) { method = observable[method]; } observable.listenTo(observable, eventid, _.bind(method, observable)); }); }, // expose application's PubSub to plug it in application. createPubSub: function (observer, property) { var pubsub = {}, observable = this; _.each(['on', 'off', 'trigger', 'once'], function (method) { pubsub[method] = _.bind(observable[method], observable); }); // in case there is no observer if (!observer) {return pubsub;} var events = _.extend( {}, _.result(observer, property), _.result(observer.options || {}, property) ); _.each(events, function (method, eventid) { // create callback from method // if it is not a function already, it should be a method if (!_.isFunction(method)) { method = observer[method]; } observable.listenTo(observable, eventid, _.bind(method, observer)); }); return pubsub; } }); return Events; });
define([ 'fossil/core', 'underscore', 'backbone' ], function (Fossil, _, Backbone) { var Events = Fossil.Mixins.Events = _.extend({}, Backbone.Events, { registerEvents: function () { var events = _.extend( {}, _.result(this, 'events'), _.result(this.options || {}, 'events') ); var observable = this; _.each(events, function (method, eventid) { // create callback from method // if it is not a function already, it should be a method if (!_.isFunction(method)) { method = observable[method]; } observable.listenTo(observable, eventid, method, observable); }); }, // expose application's PubSub to plug it in application. createPubSub: function (observer, property) { var pubsub = {}, observable = this; _.each(['on', 'off', 'trigger', 'once'], function (method) { pubsub[method] = _.bind(observable[method], observable); }); // in case there is no observer if (!observer) {return pubsub;} var events = _.extend( {}, _.result(observer, property), _.result(observer.options || {}, property) ); _.each(events, function (method, eventid) { // create callback from method // if it is not a function already, it should be a method if (!_.isFunction(method)) { method = observer[method]; } observable.listenTo(observable, eventid, method, observer); }); return pubsub; } }); return Events; });
Fix select outside code area.
$(function () { function restore() { $(".ghs-highlight").removeClass("ghs-highlight"); $(".ghs-partial-highlight").contents().unwrap(); } $("body").mouseup(function (e) { restore(); var selection = $.trim(window.getSelection()); if (selection) { var codeArea = $(".js-file-line-container"); codeArea.find("span:not(:has(*))").each(function () { if (this != e.target) { if ($(this).text() == selection) { $(this).addClass("ghs-highlight"); } else if ($(this).text().indexOf(selection) > -1) { $(this).html(function(_, html) { return html.replace(selection, '<span class="ghs-partial-highlight">' + selection + '</span>'); }); } } }); } }); });
$(function () { function restore() { $(".ghs-highlight").removeClass("ghs-highlight"); $(".ghs-partial-highlight").contents().unwrap(); } $("body").mouseup(function (e) { restore(); var selection = $.trim(window.getSelection()); if (selection) { var codeArea = $(".file-box"); codeArea.find("span:not(:has(*))").each(function () { if (this != e.target) { if ($(this).text() == selection) { $(this).addClass("ghs-highlight"); } else if ($(this).text().indexOf(selection) > -1) { $(this).html(function(_, html) { return html.replace(selection, '<span class="ghs-partial-highlight">' + selection + '</span>'); }); } } }); } }); });
Fix slug unicode on template tag article get ArticleBox
# -*- coding: utf-8 -*- from django import template from django.conf import settings from django.utils import timezone from opps.articles.models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = u"{0}-{1}".format(slug, channel_slug) try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, date_available__lte=timezone.now(), published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
# -*- coding: utf-8 -*- from django import template from django.conf import settings from django.utils import timezone from .models import ArticleBox register = template.Library() @register.simple_tag def get_articlebox(slug, channel_slug=None, template_name=None): if channel_slug: slug = "{0}-{1}".format(slug, channel_slug) try: box = ArticleBox.objects.get(site=settings.SITE_ID, slug=slug, date_available__lte=timezone.now(), published=True) except ArticleBox.DoesNotExist: box = None t = template.loader.get_template('articles/articlebox_detail.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articlebox': box, 'slug': slug})) @register.simple_tag def get_all_articlebox(channel_slug, template_name=None): boxes = ArticleBox.objects.filter(site=settings.SITE_ID, date_available__lte=timezone.now(), published=True, channel__slug=channel_slug) t = template.loader.get_template('articles/articlebox_list.html') if template_name: t = template.loader.get_template(template_name) return t.render(template.Context({'articleboxes': boxes}))
Use canvas width/height for futureproofing
const jpegThumbnail = dataUrl => new Promise((resolve, reject) => { const image = new Image(); image.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxDimension = 96; // 3x the maximum displayed size of 32px if (image.height < 1 || image.width < 1) { canvas.width = canvas.height = maxDimension; // drawImage can fail if image height/width is less than 1 // Use blank image; the costume is too small to render anyway ctx.fillStyle = 'white'; // Create white background, since jpeg doesn't have transparency ctx.fillRect(0, 0, canvas.width, canvas.height); } else { if (image.height > image.width) { canvas.height = maxDimension; canvas.width = (maxDimension / image.height) * image.width; } else { canvas.width = maxDimension; canvas.height = (maxDimension / image.width) * image.height; } ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(image, 0, 0, canvas.width, canvas.height); } resolve(canvas.toDataURL('image/jpeg', 0.92 /* quality */)); // Default quality is 0.92 }; image.onerror = err => { reject(err); }; image.src = dataUrl; }); export default jpegThumbnail;
const jpegThumbnail = dataUrl => new Promise((resolve, reject) => { const image = new Image(); image.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxDimension = 96; // 3x the maximum displayed size of 32px if (image.height < 1 || image.width < 1) { canvas.width = canvas.height = maxDimension; // drawImage can fail if image height/width is less than 1 // Use blank image; the costume is too small to render anyway ctx.fillStyle = 'white'; // Create white background, since jpeg doesn't have transparency ctx.fillRect(0, 0, maxDimension, maxDimension); } else { if (image.height > image.width) { canvas.height = maxDimension; canvas.width = (maxDimension / image.height) * image.width; } else { canvas.width = maxDimension; canvas.height = (maxDimension / image.width) * image.height; } ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(image, 0, 0, canvas.width, canvas.height); } resolve(canvas.toDataURL('image/jpeg', 0.92 /* quality */)); // Default quality is 0.92 }; image.onerror = err => { reject(err); }; image.src = dataUrl; }); export default jpegThumbnail;
Fix bug in abort functionality. We stored the deferred object instead of the complete XHR object, so attempting an xhr.abort() caused a fatal
(function($) { // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); $.ajaxQueue = function( ajaxOpts ) { var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); // run the actual query function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ); jqXHR.done( dfd.resolve ) .fail( dfd.reject ) .then( next, next ); } // queue our ajax request ajaxQueue.queue( doRequest ); // add the abort method promise.abort = function( statusText ) { // proxy abort to the jqXHR if it is active if ( jqXHR ) { return jqXHR.abort( statusText ); } // if there wasn't already a jqXHR we need to remove from queue var queue = ajaxQueue.queue(), index = $.inArray( doRequest, queue ); if ( index > -1 ) { queue.splice( index, 1 ); } // and then reject the deferred dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] ); return promise; }; return promise; }; })(jQuery);
(function($) { // jQuery on an empty object, we are going to use this as our Queue var ajaxQueue = $({}); $.ajaxQueue = function( ajaxOpts ) { var jqXHR, dfd = $.Deferred(), promise = dfd.promise(); // run the actual query function doRequest( next ) { jqXHR = $.ajax( ajaxOpts ) .done( dfd.resolve ) .fail( dfd.reject ) .then( next, next ); } // queue our ajax request ajaxQueue.queue( doRequest ); // add the abort method promise.abort = function( statusText ) { // proxy abort to the jqXHR if it is active if ( jqXHR ) { return jqXHR.abort( statusText ); } // if there wasn't already a jqXHR we need to remove from queue var queue = ajaxQueue.queue(), index = $.inArray( doRequest, queue ); if ( index > -1 ) { queue.splice( index, 1 ); } // and then reject the deferred dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] ); return promise; }; return promise; }; })(jQuery);
Use the `@Timed` annotation on SQLObjects Looks more reasonable to me this way instead logging everything by default.
package com.github.arteam.jdbi3; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator; import java.time.LocalDate; import java.util.Optional; @UseStringTemplateSqlLocator @Timed(name = "game-dao") public interface GameDao { @SqlQuery ImmutableList<Integer> findGameIds(); @SqlQuery ImmutableSet<String> findAllUniqueHomeTeams(); @SqlQuery Optional<Integer> findIdByTeamsAndDate(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam, @Bind("played_at") LocalDate date); @SqlQuery LocalDate getFirstPlayedSince(@Bind("up") LocalDate up); @SqlQuery @Timed(name = "last-played-date") Optional<LocalDate> getLastPlayedDateByTeams(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam); @SqlQuery Optional<String> findHomeTeamByGameId(@Bind("id") Optional<Integer> id); }
package com.github.arteam.jdbi3; import com.codahale.metrics.annotation.Timed; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import org.jdbi.v3.sqlobject.customizer.Bind; import org.jdbi.v3.sqlobject.statement.SqlQuery; import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator; import java.time.LocalDate; import java.util.Optional; @UseStringTemplateSqlLocator public interface GameDao { @SqlQuery ImmutableList<Integer> findGameIds(); @SqlQuery ImmutableSet<String> findAllUniqueHomeTeams(); @SqlQuery Optional<Integer> findIdByTeamsAndDate(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam, @Bind("played_at") LocalDate date); @SqlQuery LocalDate getFirstPlayedSince(@Bind("up") LocalDate up); @SqlQuery @Timed(name = "get-last-played") Optional<LocalDate> getLastPlayedDateByTeams(@Bind("home_team") String homeTeam, @Bind("visitor_team") String visitorTeam); @SqlQuery Optional<String> findHomeTeamByGameId(@Bind("id") Optional<Integer> id); }
Revert "Zastąpienie findAll generowaniem pustej listy" This reverts commit b28c03003ff556dd56690ba848062505f951476d.
package org.pwd.web.websites; import org.pwd.domain.websites.Website; import org.pwd.domain.websites.WebsiteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.GET; /** * @author bartosz.walacik */ @Controller @RequestMapping("/serwisy") class WebsitesController { private WebsiteRepository websiteRepository; @Autowired public WebsitesController(WebsiteRepository websiteRepository) { this.websiteRepository = websiteRepository; } @RequestMapping(method = GET) public String getWebsites(Model model, @RequestParam(value = "query", required = false) String query) { model.addAttribute("query", query); List<Website> websites; if (StringUtils.isEmpty(query)) { websites = websiteRepository.findAll(); } else { websites = websiteRepository.search(query); } model.addAttribute("websites", websites); model.addAttribute("websitesTotalCount", websiteRepository.count()); model.addAttribute("websitesCount", websites.size()); return "websites"; } }
package org.pwd.web.websites; import org.pwd.domain.websites.Website; import org.pwd.domain.websites.WebsiteRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.GET; /** * @author bartosz.walacik */ @Controller @RequestMapping("/serwisy") class WebsitesController { private WebsiteRepository websiteRepository; @Autowired public WebsitesController(WebsiteRepository websiteRepository) { this.websiteRepository = websiteRepository; } @RequestMapping(method = GET) public String getWebsites(Model model, @RequestParam(value = "query", required = false) String query) { model.addAttribute("query", query); List<Website> websites; if (StringUtils.isEmpty(query)) { websites = websiteRepository.search("XYZ"); //websiteRepository.findAll(); } else { websites = websiteRepository.search(query); } model.addAttribute("websites", websites); model.addAttribute("websitesTotalCount", websiteRepository.count()); model.addAttribute("websitesCount", websites.size()); return "websites"; } }
Change recursive call to private function
/* * deep-clone * @author Garrett Reed <[email protected]> 2016 * MIT Licensed * * Suports: * Primitives: null, string, number, function (inherits prototype) * Collections: object, array * * @param {object} target Receiving object * @param {object/array} obj Object to clone * @return {object/array} the clone * */ var deepClone = (function() { 'use strict'; var _isPrimitive = function(value) { if (value === null) { return true; } switch (typeof value) { case 'string': case 'number': case 'boolean': case 'undefined': case 'function': return true; default: return false; } }; var _isArray = function(value) { return Object.prototype.toString.call(value) === '[object Array]'; }; var _clone = function(target, obj) { for (var key in obj) { if (_isPrimitive(obj[key])) { target[key] = obj[key]; if (typeof target[key] === 'function') { target[key].prototype = Object.create(obj[key].prototype); } } else if (_isArray(obj[key])) { target[key] = []; _clone(target[key], obj[key]); } else { target[key] = Object.create(Object.getPrototypeOf(obj[key])); _clone(target[key], obj[key]); } } return target; }; return _clone; })();
/* * deep-clone * @author Garrett Reed <[email protected]> 2016 * MIT Licensed * * Suports: * Primitives: null, string, number, function (inherits prototype) * Collections: object, array * * @param {object} target Receiving object * @param {object/array} obj Object to clone * @return {object/array} the clone * */ var deepClone = (function() { 'use strict'; var _isPrimitive = function(value) { if (value === null) { return true; } switch (typeof value) { case 'string': case 'number': case 'boolean': case 'undefined': case 'function': return true; default: return false; } }; var _isArray = function(value) { return Object.prototype.toString.call(value) === '[object Array]'; }; var _clone = function(target, obj) { for (var key in obj) { if (_isPrimitive(obj[key])) { target[key] = obj[key]; if (typeof target[key] === 'function') { target[key].prototype = Object.create(obj[key].prototype); } } else if (_isArray(obj[key])) { target[key] = []; deepClone(target[key], obj[key]); } else { target[key] = Object.create(Object.getPrototypeOf(obj[key])); _clone(target[key], obj[key]); } } return target; }; return _clone; })();
Make raw_data and data as properties
#!/usr/bin/env python # -*- coding: utf-8 -*- """utils for data crunching, saving. """ import numpy as np class ScanDataFactory(object): """Post processor of data from scan server. Parameters ---------- data : dict Raw data retrieving from scan server regarding scan ID, after completing certain scan task. n_sample : int Sample number for every scan device setup. """ def __init__(self, data, n_sample): self._raw_data = data self._n = n_sample self._rebuild_data() @property def raw_data(self): """dict: Dict of array, raw scan data.""" return self._raw_data @property def data(self): """dict: Dict of array, raw scan data after postprocessing.""" return self._data def _rebuild_data(self): """Rebuild raw_data """ self._data = {k:np.array(v.get('value')).reshape(-1, self._n) for k,v in self._raw_data.iteritems()} def get_average(self, name): """Get average. Parameters ---------- name : str Key name of raw_data. """ return self._data.get(name).mean(axis=1) def get_errorbar(self, name): """Get errorbar Parameters ---------- name : str Key name of raw_data. """ return self._data.get(name).std(axis=1) def get_all_names(self): """Get all key names of raw_data. Returns ------- ret : list List of keys. """ return self._data.keys() def save(self, ext='dat'): """ """ pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """utils for data crunching, saving. """ import numpy as np class ScanDataFactory(object): """Post processor of data from scan server. Parameters ---------- data : dict Raw data retrieving from scan server regarding scan ID, after completing certain scan task. n_sample : int Sample number for every scan device setup. """ def __init__(self, data, n_sample): self._raw_data = data self._n = n_sample self._rebuild_data() def _rebuild_data(self): """Rebuild raw_data """ self._data = {k:np.array(v.get('value')).reshape(-1, self._n) for k,v in self._raw_data.iteritems()} def get_average(self, name): """Get average. Parameters ---------- name : str Key name of raw_data. """ return self._data.get(name).mean(axis=1) def get_errorbar(self, name): """Get errorbar Parameters ---------- name : str Key name of raw_data. """ return self._data.get(name).std(axis=1) def get_all_names(self): """Get all key names of raw_data. Returns ------- ret : list List of keys. """ return self._data.keys() def save(self, ext='dat'): """ """ pass
Make main link go to dashboard for election
<?php require_once('config.php'); global $config; $userid = session_get_user_id(); $stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?"); $stmt->bindParam(1, $userid); $stmt->execute(); $elections = $stmt->fetchAll(); ?> <aside class="main-sidebar"> <section class="sidebar"> <ul class="sidebar-menu"> <li class="header">ELECTIONS</li> <?php foreach ($elections as $row) { $stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?"); $stmt->bindParam(1, $row["election"]); $stmt->execute(); $election_name = $stmt->fetch(PDO::FETCH_NUM)[0]; ?> <li <?php if($_GET['id'] == $row['election']) { ?>class="active"<?php } ?>><a href="/election?id=<?php echo $row["election"]; ?>&subid=dashboard"><i class="fa fa-users"></i> <span><?php echo $election_name; ?></span></a></li> <?php } ?> <li <?php if($_GET['id'] == "new") { ?>class="active"<?php } ?>><a href="/election?id=new"><i class="fa fa-pencil-square-o"></i> <span>New Election...</span></a></li> </ul> </section> </aside>
<?php require_once('config.php'); global $config; $userid = session_get_user_id(); $stmt = $pdo->prepare("SELECT `election` FROM `access` WHERE `user`= ?"); $stmt->bindParam(1, $userid); $stmt->execute(); $elections = $stmt->fetchAll(); ?> <aside class="main-sidebar"> <section class="sidebar"> <ul class="sidebar-menu"> <li class="header">ELECTIONS</li> <?php foreach ($elections as $row) { $stmt = $pdo->prepare("SELECT `name` FROM `elections` WHERE `id`= ?"); $stmt->bindParam(1, $row["election"]); $stmt->execute(); $election_name = $stmt->fetch(PDO::FETCH_NUM)[0]; ?> <li <?php if($_GET['id'] == $row['election']) { ?>class="active"<?php } ?>><a href="/election?id=<?php echo $row["election"]; ?>"><i class="fa fa-users"></i> <span><?php echo $election_name; ?></span></a></li> <?php } ?> <li <?php if($_GET['id'] == "new") { ?>class="active"<?php } ?>><a href="/election?id=new"><i class="fa fa-pencil-square-o"></i> <span>New Election...</span></a></li> </ul> </section> </aside>
feat(plugins): Add moduleURLs in addition to scriptURLs
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL, type = "text/javascript") { const script = document.createElement("script"); script.src = scriptURL; script.type = type; script.async = false; const head = document.getElementsByTagName("head")[0]; head.appendChild(script); head.removeChild(script); return script; } // reload all the dependency scripts and also // the main plugin script url. static reloadPlugin(plugin) { if (plugin.scriptURLs && plugin.scriptURLs.length) { plugin.scriptURLs.forEach(scriptURL => { this.loadScript(scriptURL).onload = function() {} }); } // TODO: Later we should probably merge script and module URLs if (plugin.moduleURLs && plugin.moduleURLs.length) { plugin.moduleURLs.forEach(moduleURLs => { this.loadScript(moduleURLs, "module").onload = function() {} }); } let scriptURL = plugin.url; if (plugin.allowCaching === false) { scriptURL += "?" + performance.now(); } this.loadScript(scriptURL).onload = function() { const entryPointFunction = OHIF.plugins.entryPoints[plugin.name]; if (entryPointFunction) { entryPointFunction(); } } } }
export class OHIFPlugin { // TODO: this class is still under development and will // likely change in the near future constructor () { this.name = "Unnamed plugin"; this.description = "No description available"; } // load an individual script URL static loadScript(scriptURL) { const script = document.createElement("script"); script.src = scriptURL; script.type = "text/javascript"; script.async = false; const head = document.getElementsByTagName("head")[0]; head.appendChild(script); head.removeChild(script); return script; } // reload all the dependency scripts and also // the main plugin script url. static reloadPlugin(plugin) { console.warn(`reloadPlugin: ${plugin.name}`); if (plugin.scriptURLs && plugin.scriptURLs.length) { plugin.scriptURLs.forEach(scriptURL => { this.loadScript(scriptURL).onload = function() {} }); } let scriptURL = plugin.url; if (plugin.allowCaching === false) { scriptURL += "?" + performance.now(); } this.loadScript(scriptURL).onload = function() { const entryPointFunction = OHIF.plugins.entryPoints[plugin.name]; if (entryPointFunction) { entryPointFunction(); } } } }
Refresh iframe on "RENDERING" change
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', initialize: function() { this.$el.load(_.bind(function(){ console.log("it did a reload"); console.log(this.$el.contents()[0].title); if (!(this.$el.contents()[0].title)) { console.log("RENDERING it says"); document.getElementById('visualization') .contentWindow .location .reload(true); } }, this)); }, // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: "GET" }).done(_.bind(function(d) { //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); iframe.find('.menubar').remove(); // iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } });
AV.VisualizationView = Backbone.View.extend({ el: '#visualization', // The rendering of the visualization will be slightly // different here, because there is no templating necessary: // The server gives back a page. render: function() { this.model.url = this.model.urlRoot + this.model.id + '/view?mode=heatmap&condensed=true'; var response = $.ajax({ url: this.model.url, type: "GET" }).done(_.bind(function(d) { //If the server returns an HTML document if (d[0] != 'R') { return d; } else { //Rendering setTimeout(function(){}, 1000); return this.render(); } }, this)); this.$el.attr('src', this.model.url).load(_.bind(function() { var iframe = this.$el.contents(); // iframe.find('.menubar').remove(); // iframe.find('.title-bar').remove(); }, this)); $('#basicModal').modal({ show: true }); } });
Fix encoding (thanks to Yasushi Masuda) git-svn-id: 305ad3fa995f01f9ce4b4f46c2a806ba00a97020@433 3777fadb-0f44-0410-9e7f-9d8fa6171d72
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
BB-7489: Test & Merge - moved FrontendBundle files from commerce package to customer-portal - removed test page templates
<?php namespace Oro\Bundle\EntityBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue; class EntityFieldFallbackTransformer implements DataTransformerInterface { /** * {@inheritdoc} */ public function transform($value) { if (!$value instanceof EntityFieldFallbackValue) { return $value; } if (is_null($value->getFallback()) && !$value->getArrayValue()) { return $value->setScalarValue($value->getOwnValue()); } return $value; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (!$value instanceof EntityFieldFallbackValue) { return $value; } // set entity value to null, so entity will use fallback value $fallbackId = $value->getFallback(); if (isset($fallbackId)) { $value->setScalarValue(null); $value->setArrayValue(null); return $value; } // not fallback, so make sure we clean fallback field $value->setFallback(null); if (is_array($value->getScalarValue())) { return $value ->setArrayValue($value->getScalarValue()) ->setScalarValue(null); } return $value->setArrayValue(null); } }
<?php namespace Oro\Bundle\EntityBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Oro\Bundle\EntityBundle\Entity\EntityFieldFallbackValue; class EntityFieldFallbackTransformer implements DataTransformerInterface { /** * {@inheritdoc} */ public function transform($value) { if (!$value instanceof EntityFieldFallbackValue) { return $value; } // if (is_null($value->getFallback())) { // return $value->setScalarValue($value->getOwnValue()); // } return $value; } /** * {@inheritdoc} */ public function reverseTransform($value) { if (!$value instanceof EntityFieldFallbackValue) { return $value; } // set entity value to null, so entity will use fallback value $fallbackId = $value->getFallback(); if (isset($fallbackId)) { $value->setScalarValue(null); $value->setArrayValue(null); return $value; } // not fallback, so make sure we clean fallback field $value->setFallback(null); if (is_array($value->getScalarValue())) { return $value ->setArrayValue($value->getScalarValue()) ->setScalarValue(null); } return $value->setArrayValue(null); } }
Make CLI linter messages a bit easier to read
'use strict'; var configLoader = require('./config-loader'); var LessHint = require('./lesshint'); var exit = require('exit'); var Vow = require('vow'); module.exports = function (program) { var lesshint = new LessHint(); var exitDefer = Vow.defer(); var exitPromise = exitDefer.promise(); var promises = []; var config; exitPromise.always(function (status) { exit(status.valueOf()); }); if (!program.args.length) { console.error('No files to lint were passed. See lesshint -h'); exitDefer.reject(66); } try { config = configLoader(program.config); } catch (e) { console.error('Something\'s wrong with the config file. Error: ' + e.message); exitDefer.reject(78); } lesshint.configure(config); promises = program.args.map(lesshint.checkPath, lesshint); Vow.all(promises).then(function (errors) { errors = [].concat.apply([], errors); if (!errors.length) { exitDefer.resolve(0); return; } errors.forEach(function (error) { console.log( '%s: line %d, col %d, %s: %s', error.file, error.line, error.column, error.linter, error.message ); }); exitDefer.reject(1); }); return exitPromise; };
'use strict'; var configLoader = require('./config-loader'); var LessHint = require('./lesshint'); var exit = require('exit'); var Vow = require('vow'); module.exports = function (program) { var lesshint = new LessHint(); var exitDefer = Vow.defer(); var exitPromise = exitDefer.promise(); var promises = []; var config; exitPromise.always(function (status) { exit(status.valueOf()); }); if (!program.args.length) { console.error('No files to lint were passed. See lesshint -h'); exitDefer.reject(66); } try { config = configLoader(program.config); } catch (e) { console.error('Something\'s wrong with the config file. Error: ' + e.message); exitDefer.reject(78); } lesshint.configure(config); promises = program.args.map(lesshint.checkPath, lesshint); Vow.all(promises).then(function (errors) { errors = [].concat.apply([], errors); if (!errors.length) { exitDefer.resolve(0); return; } errors.forEach(function (error) { console.log( '%s %s:%d %s', error.linter, error.file, error.line, error.message ); }); exitDefer.reject(1); }); return exitPromise; };
Fix page where site key is entered
<?php $themeManager = $this->website->getThemeManager(); $theme = $themeManager->getCurrentTheme(); $stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css" /> </head> <body style="background-image:none;text-align:center"> <div id="login"> <h1><?php echo $this->website->getConfig()->get('hometitle') ?></h1> <form action="" method="post"> <p> <?php echo $this->website->t("main.code_request") ?> </p> <p> <input type="password" name="key" id="key" style="width:10em;" /> <script type="text/javascript"> document.getElementById("key").focus(); </script> </p> <p> <input type="submit" class="button" style="width:11em;" value="<?php echo $this->website->t("main.log_in") ?>" /> </p> </form> </div> </body> </html>
<?php $themeManager = $this->getThemeManager(); $theme = $themeManager->getCurrentTheme(); $stylesheet = $themeManager->getUrlTheme($theme) . $theme->getErrorPageStylesheet(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <link href="<?php echo $stylesheet ?>" rel="stylesheet" type="text/css" /> </head> <body style="background-image:none;text-align:center"> <div id="login"> <h1><?php echo $this->getConfig()->get('hometitle') ?></h1> <form action="" method="post"> <p> <?php echo $this->t("main.code_request") ?> </p> <p> <input type="password" name="key" id="key" style="width:10em;" /> <script type="text/javascript"> document.getElementById("key").focus(); </script> </p> <p> <input type="submit" class="button" style="width:11em;" value="<?php echo $this->t("main.log_in") ?>" /> </p> </form> </div> </body> </html>
Fix href for filter lists items
var React = require('react'); var classNames = require('classnames'); var FilterItem = React.createClass({ propTypes: { selected: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, count: React.PropTypes.number, onClick: React.PropTypes.func }, getDefaultProps: function() { return { selected: false, href: '#' }; }, onClick: function(e) { if (!this.props.onClick) { return; } e.preventDefault(); this.props.onClick(); }, render: function() { var className = classNames('filter-item', this.props.className, { selected: this.props.selected }); var count = this.props.count; var href = this.props.href; var inner = ''; if (typeof count !== 'undefined') { inner = <span className="count">{count}</span>; } return ( <li> <a className={className} href={href} onClick={this.onClick}> {inner} {this.props.children} </a> </li> ); } }); var FilterList = React.createClass({ render: function() { return ( <ul className="filter-list"> {this.props.children} </ul> ); } }); module.exports = FilterList; module.exports.Item = FilterItem;
var React = require('react'); var classNames = require('classnames'); var FilterItem = React.createClass({ propTypes: { selected: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, count: React.PropTypes.number, onClick: React.PropTypes.func }, getDefaultProps: function() { return { selected: false, href: '#' }; }, onClick: function(e) { if (!this.props.onClick) { return; } e.preventDefault(); this.props.onClick(); }, render: function() { var className = classNames('filter-item', this.props.className, { selected: this.props.selected }); var count = this.props.count; var inner = ''; if (typeof count !== 'undefined') { inner = <span className="count">{count}</span>; } return ( <li> <a className={className} onClick={this.onClick}> {inner} {this.props.children} </a> </li> ); } }); var FilterList = React.createClass({ render: function() { return ( <ul className="filter-list"> {this.props.children} </ul> ); } }); module.exports = FilterList; module.exports.Item = FilterItem;
Tweak to migration so it is a bit faster for future migraters
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): Msg = apps.get_model('msgs', 'Msg') # this is our new bucket name bucket_name = settings.AWS_STORAGE_BUCKET_NAME # our old bucket name had periods instead of dashes old_bucket_domain = 'http://' + bucket_name.replace('-', '.') # our new domain is more specific new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN for msg in Msg.objects.filter(direction='I', msg_type='V').exclude(recording_url=None): # if our recording URL is on our old bucket if msg.recording_url.find(old_bucket_domain) >= 0: # rename it to our new bucket old_recording_url = msg.recording_url msg.recording_url = msg.recording_url.replace(old_bucket_domain, new_bucket_domain) print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url) msg.save(update_fields=['recording_url']) operations = [ migrations.RunPython(move_recording_domains) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('msgs', '0033_exportmessagestask_uuid'), ] def move_recording_domains(apps, schema_editor): Msg = apps.get_model('msgs', 'Msg') # this is our new bucket name bucket_name = settings.AWS_STORAGE_BUCKET_NAME # our old bucket name had periods instead of dashes old_bucket_domain = 'http://' + bucket_name.replace('-', '.') # our new domain is more specific new_bucket_domain = 'https://' + settings.AWS_BUCKET_DOMAIN for msg in Msg.objects.filter(msg_type='V').exclude(recording_url=None): # if our recording URL is on our old bucket if msg.recording_url.find(old_bucket_domain) >= 0: # rename it to our new bucket old_recording_url = msg.recording_url msg.recording_url = msg.recording_url.replace(old_bucket_domain, new_bucket_domain) print "[%d] %s to %s" % (msg.id, old_recording_url, msg.recording_url) msg.save(update_fields=['recording_url']) operations = [ migrations.RunPython(move_recording_domains) ]
Fix a bug where widgets wouldn't be rendered w/ their themes in wysiwyg
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widget: null }; } componentWillMount() { const { item } = this.props; this.getChart(item.content.widgetId); } shouldComponentUpdate(nextProps, nextState) { // This fixes a bug where the widgets would reload when hovering them return this.state !== nextState || this.props.item.content.widgetId !== nextProps.item.content.widgetId; } getChart(widgetId) { fetch(`${window.location.origin}/widget_data.json?widget_id=${widgetId}`).then((res) => { return res.json(); }).then((w) => { const widget = w; if (widget.visualization.width !== undefined) delete widget.visualization.width; if (widget.visualization.height !== undefined) delete widget.visualization.height; this.setState({ loading: false, widget }); }); } render() { if (this.state.loading) { return null; } return ( <VegaChart data={this.state.widget.visualization} reloadOnResize /> ); } } WidgetBlock.propTypes = { item: PropTypes.object.isRequired }; export default WidgetBlock;
import React from 'react'; import PropTypes from 'prop-types'; import { VegaChart, getVegaTheme } from 'widget-editor'; // /widget_data.json?widget_id= class WidgetBlock extends React.Component { constructor(props) { super(props); this.widgetConfig = null; this.state = { loading: true, widget: null }; } componentWillMount() { const { item } = this.props; this.getChart(item.content.widgetId); } shouldComponentUpdate(nextProps, nextState) { // This fixes a bug where the widgets would reload when hovering them return this.state !== nextState || this.props.item.content.widgetId !== nextProps.item.content.widgetId; } getChart(widgetId) { fetch(`${window.location.origin}/widget_data.json?widget_id=${widgetId}`).then((res) => { return res.json(); }).then((w) => { const widget = w; if (widget.visualization.width !== undefined) delete widget.visualization.width; if (widget.visualization.height !== undefined) delete widget.visualization.height; this.setState({ loading: false, widget }); }); } render() { if (this.state.loading) { return null; } return ( <VegaChart data={this.state.widget.visualization} theme={getVegaTheme()} reloadOnResize /> ); } } WidgetBlock.propTypes = { item: PropTypes.object.isRequired }; export default WidgetBlock;
Refactor spec with a let/letgo. chdiring to fixtures dir
<?php namespace spec\MageTest\PHPSpec2\MagentoExtension\Loader; use PHPSpec2\ObjectBehavior; use PHPSpec2\Loader\Node\Specification as NodeSpecification; use ReflectionClass; class SpecificationsClassLoader extends ObjectBehavior { function it_loads_controller_specs() { $specification = $this->loadFromfile('spec/Acme/Cms/controllers/IndexController.php'); $specification->shouldBeLike(array( new NodeSpecification( 'spec\Acme_Cms_IndexController', new \ReflectionClass('spec\Acme_Cms_IndexController') ) )); } function it_checks_if_controller_spec_implements_magespec_controller_behavior() { $specifications = $this->loadFromfile('spec/Acme/Cms/controllers/PageController.php'); $specifications[0] ->getClass() ->isSubclassOf('MageTest\PHPSpec2\MagentoExtension\Specification\ControllerBehavior') ->shouldBe(true); } private $currentWorkingDirectory; function let() { $this->currentWorkingDirectory = getcwd(); chdir($this->currentWorkingDirectory . '/fixtures'); } function letgo() { chdir($this->currentWorkingDirectory); } }
<?php namespace spec\MageTest\PHPSpec2\MagentoExtension\Loader; use PHPSpec2\ObjectBehavior; use PHPSpec2\Loader\Node\Specification as NodeSpecification; use ReflectionClass; class SpecificationsClassLoader extends ObjectBehavior { function it_loads_controller_specs() { $currentWorkingDirectory = getcwd(); chdir($currentWorkingDirectory . '/fixtures'); $specification = $this->loadFromfile('spec/Acme/Cms/controllers/IndexController.php'); $specification->shouldBeLike(array( new NodeSpecification( 'spec\Acme_Cms_IndexController', new \ReflectionClass('spec\Acme_Cms_IndexController') ) )); chdir($currentWorkingDirectory); } function it_checks_if_controller_spec_implements_magespec_controller_behavior() { $currentWorkingDirectory = getcwd(); chdir($currentWorkingDirectory . '/fixtures'); $specifications = $this->loadFromfile('spec/Acme/Cms/controllers/PageController.php'); $specifications[0] ->getClass() ->isSubclassOf('MageTest\PHPSpec2\MagentoExtension\Specification\ControllerBehavior') ->shouldBe(true); chdir($currentWorkingDirectory); } }
Add bots with no games to the leaderboard
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank, BotIdentity class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( BotIdentity.id, func.coalesce(func.sum(MatchResult.delta_chips), 0), func.coalesce(func.sum(MatchResult.hands), 0), ) \ .outerjoin(MatchResult) \ .group_by(BotIdentity.id) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, self.calc_winnings_per_hand(s[1], s[2]), yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() def calc_winnings_per_hand(self, chips, hand): try: return chips / hand except ZeroDivisionError: return 0 class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
import datetime from sqlalchemy.sql import func from models import MatchResult, BotSkill, BotRank class SkillUpdater(object): def run(self, db): session = db.session today = datetime.date.today() skills = session.query( MatchResult.bot, func.sum(MatchResult.delta_chips), func.sum(MatchResult.hands) ) \ .group_by(MatchResult.bot) \ .all() yesterday = today - datetime.timedelta(days=1) yesterdays_skills = {b.bot: b.skill for b in BotSkill.query.filter_by(date=yesterday).all()} BotSkill.query.filter_by(date=today).delete() session.bulk_save_objects( [BotSkill(s[0], today, s[1] / s[2], yesterdays_skills.get(s[0], 0)) for s in skills] ) session.commit() class RankUpdater(object): def run(self, db): BotRank.query.delete() today = datetime.date.today() skills = BotSkill.query.filter_by(date=today) \ .order_by(BotSkill.skill.desc()) \ .all() for i, skill in enumerate(skills, 1): rank = BotRank(skill.bot, i) db.session.add(rank) db.session.commit()
Make search results more clickable Refs #148.
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { getAvailableTime, getCaption, getMainImage, getName, getOpeningHours, } from 'utils/DataUtils'; class SearchResult extends Component { renderImage(image) { if (image && image.url) { const src = `${image.url}?dim=80x80`; return <img alt={getCaption(image)} src={src} />; } return null; } render() { const { date, result, unit } = this.props; return ( <tr> <td style={{ height: '80px', width: '80px' }}> <Link to={`/resources/${result.id}`}> {this.renderImage(getMainImage(result.images))} </Link> </td> <td> <Link to={`/resources/${result.id}`}> <h4>{getName(result)}</h4> <div>{getName(unit)}</div> </Link> </td> <td> <Link to={`/resources/${result.id}/reservation`} query={{ date: date.split('T')[0] }} > {getAvailableTime(getOpeningHours(result), result.reservations)} </Link> </td> </tr> ); } } SearchResult.propTypes = { date: PropTypes.string.isRequired, result: PropTypes.object.isRequired, unit: PropTypes.object.isRequired, }; export default SearchResult;
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { getAvailableTime, getCaption, getMainImage, getName, getOpeningHours, } from 'utils/DataUtils'; class SearchResult extends Component { renderImage(image) { if (image && image.url) { const src = `${image.url}?dim=80x80`; return <img alt={getCaption(image)} src={src} />; } return null; } render() { const { date, result, unit } = this.props; return ( <tr> <td style={{ height: '80px', width: '80px' }}> {this.renderImage(getMainImage(result.images))} </td> <td> <Link to={`/resources/${result.id}`}> {getName(result)} </Link> <div>{getName(unit)}</div> </td> <td> <Link to={`/resources/${result.id}/reservation`} query={{ date: date.split('T')[0] }} > {getAvailableTime(getOpeningHours(result), result.reservations)} </Link> </td> </tr> ); } } SearchResult.propTypes = { date: PropTypes.string.isRequired, result: PropTypes.object.isRequired, unit: PropTypes.object.isRequired, }; export default SearchResult;
Fix invalid bitmask for release archives
var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.json').version; return eventStream.merge( getSources() .pipe(zip('operator-status-plugin-' + version + '.zip')), getSources() .pipe(tar('operator-status-plugin-' + version + '.tar')) .pipe(gzip()) ) .pipe(chmod(644)) .pipe(gulp.dest('release')); }); // Builds and packs plugins sources gulp.task('default', ['prepare-release'], function() { // The "default" task is just an alias for "prepare-release" task. }); /** * Returns files stream with the plugin sources. * * @returns {Object} Stream with VinylFS files. */ var getSources = function() { return gulp.src([ 'Controller/*', 'LICENSE', 'Plugin.php', 'README.md', 'routing.yml' ], {base: './'} ) .pipe(rename(function(path) { path.dirname = 'Mibew/Mibew/Plugin/OperatorStatus/' + path.dirname; })); }
var eventStream = require('event-stream'), gulp = require('gulp'), chmod = require('gulp-chmod'), zip = require('gulp-zip'), tar = require('gulp-tar'), gzip = require('gulp-gzip'), rename = require('gulp-rename'); gulp.task('prepare-release', function() { var version = require('./package.json').version; return eventStream.merge( getSources() .pipe(zip('operator-status-plugin-' + version + '.zip')), getSources() .pipe(tar('operator-status-plugin-' + version + '.tar')) .pipe(gzip()) ) .pipe(chmod(0644)) .pipe(gulp.dest('release')); }); // Builds and packs plugins sources gulp.task('default', ['prepare-release'], function() { // The "default" task is just an alias for "prepare-release" task. }); /** * Returns files stream with the plugin sources. * * @returns {Object} Stream with VinylFS files. */ var getSources = function() { return gulp.src([ 'Controller/*', 'LICENSE', 'Plugin.php', 'README.md', 'routing.yml' ], {base: './'} ) .pipe(rename(function(path) { path.dirname = 'Mibew/Mibew/Plugin/OperatorStatus/' + path.dirname; })); }
Use hooks for progress updates
import os, youtube_dl from youtube_dl import YoutubeDL from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = '' done = False error = False started = None uuid = '' total = 0 finished = 0 title = '' def __init__(self, link): self.link = link self.started = datetime.now() self.uuid = str(uuid4()) def __call__(self, info): if info['status'] == 'finished': self.finished += 1 print("\n \n INFO: " + str(info) + "\n") def download(self): curr_path = os.path.dirname(os.path.abspath(__file__)) output_tmpl = curr_path + '/downloads/' + self.uuid + '/%(title)s-%(id)s.%(ext)s' try: options = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '5', }], 'progress_hooks': [self], 'outtmpl': output_tmpl, } ydl = YoutubeDL(options) ydl.download([self.link]) except DownloadError: self.error = True finally: self.done = True def get_files(self): file_path = os.path.dirname(os.path.abspath(__file__)) + '/downloads/' + self.uuid return [f for f in os.listdir(file_path) if os.isfile(os.join(file_path, f))] def start(self): pool = ThreadPool() pool.apply_async(self.download)
import youtube_dl, os from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = "" done = False error = False started = None uuid = "" total = 0 finished = 0 title = "" def __init__(self, link): self.link = link self.started = datetime.now() self.uuid = str(uuid4()) def download(self): curr_path = os.path.dirname(os.path.abspath(__file__)) output_path = curr_path + "/downloads/" + self.uuid + "/%(title)s-%(id)s.%(ext)s" try: youtube_dl._real_main(["--yes-playlist", "-R", "10", "-x", "--audio-format", "mp3", "--output", output_path, "--restrict-filenames", "-v", self.link]) except DownloadError: self.error = True finally: self.done = True def get_files(self): file_path = os.path.dirname(os.path.abspath(__file__)) + "/downloads/" + self.uuid return [f for f in os.listdir(file_path) if os.isfile(os.join(file_path, f))] def start(self): pool = ThreadPool() pool.apply_async(self.download)
Add titles to columns and use write instead of print
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each model" def handle(self, *args, **options): total_count = 0 print_pattern = "{:<15} {:<30s} {:>10d}" title_pattern = "{:<15} {:<30s} {:>10s}" self.stdout.write(title_pattern.format("App", "Model", "Revisions")) self.stdout.write(title_pattern.format("===", "=====", "=========")) prev_app = None for model in sorted( apps.get_models(), key=lambda mod: mod.__module__ + '.' + mod.__name__): app_name = model._meta.app_label model_name = model.__name__ try: qs = Version.objects.get_for_model(model) count = qs.count() total_count += count if prev_app and prev_app != app_name: self.stdout.write("") self.stdout.write(print_pattern.format( app_name if prev_app != app_name else "", model_name, count )) prev_app = app_name except RegistrationError: # model is not registered with reversion ignore pass self.stdout.write("") self.stdout.write(print_pattern.format("Total Records", "", total_count))
# -*- encoding: utf-8 -*- from django.core.management.base import BaseCommand from django.apps import apps # from reversion import revisions as reversion from reversion.models import Version from reversion.errors import RegistrationError class Command(BaseCommand): help = "Count reversion records for each model" def handle(self, *args, **options): total_count = 0 print_pattern = "{:<15} {:<30s} {:>10d}" prev_app = None for model in sorted( apps.get_models(), key=lambda mod: mod.__module__ + '.' + mod.__name__): app_name = model._meta.app_label model_name = model.__name__ try: qs = Version.objects.get_for_model(model) count = qs.count() total_count += count if prev_app and prev_app != app_name: print() print (print_pattern.format( app_name if prev_app != app_name else "", model_name, count )) prev_app = app_name except RegistrationError: # model is not registered with reversion ignore pass print () print (print_pattern.format("Total Records", "", total_count))
Fix filename instead of path in meta
import os import hashlib import magic from datetime import datetime from .settings import METADATA_PATH from .meta import get_meta from .encryption import copy_and_encrypt, decrypt_blob from .utils import dumps hashing = hashlib.sha256 def save_metadata(meta): destination = os.path.join(METADATA_PATH, meta['id'] + '.json') open(destination, 'w').write(dumps(meta)) def add_file(filepath): "Import a file into Dis." if not os.path.isfile(filepath): raise FileNotFoundError key = b'0'*32 file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) # TODO: replace by a hash of the encrypted file id_ = copy_and_encrypt(filepath, key) meta = { 'key': key, 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(filepath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(filepath).decode(), 'mimetype': magic.from_file(filepath, mime=True).decode(), 'filename': os.path.basename(filepath), 'path': filepath, } } save_metadata(meta) return meta def get_content(id_): key = get_meta(id_)['key'] return decrypt_blob(id_, key)
import os import hashlib import magic from datetime import datetime from .settings import METADATA_PATH from .meta import get_meta from .encryption import copy_and_encrypt, decrypt_blob from .utils import dumps hashing = hashlib.sha256 def save_metadata(meta): destination = os.path.join(METADATA_PATH, meta['id'] + '.json') open(destination, 'w').write(dumps(meta)) def add_file(filepath): "Import a file into Dis." if not os.path.isfile(filepath): raise FileNotFoundError key = b'0'*32 file_hash = hashing() file_hash.update(open(filepath, 'rb').read()) # TODO: replace by a hash of the encrypted file id_ = copy_and_encrypt(filepath, key) meta = { 'key': key, 'hash': 'sha256-' + file_hash.hexdigest(), 'size': os.path.getsize(filepath), 'timestamp': datetime.now(), 'id': id_, 'info': { 'type': magic.from_file(filepath).decode(), 'mimetype': magic.from_file(filepath, mime=True).decode(), 'filename': filepath, 'path': filepath, } } save_metadata(meta) return meta def get_content(id_): key = get_meta(id_)['key'] return decrypt_blob(id_, key)
Put hero text more to the right
import React from 'react'; import Hero from 'grommet/components/Hero'; import Image from 'grommet/components/Image'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import Carousel from 'grommet/components/Carousel'; import styles from './MyHero.module.scss'; class MyHero extends React.Component { render() { return ( <Hero background={ <Image fit="cover" size="large" src="/public/bikegrass.jpeg" /> } backgroundColorIndex="dark" size="large" > <Box direction="row" justify="end" align="center" textAlign="right" > <Box basis="small" align="end" pad="small"> <Image src="/public/wolf.png" size="small"/> </Box> <Box basis="medium" align="start" pad="none"> <Heading className={styles.heading} tag="h2" margin="none" uppercase={true} strong={false}> Nordic Bikes </Heading> </Box> </Box> </Hero> ) } } export default MyHero
import React from 'react'; import Hero from 'grommet/components/Hero'; import Image from 'grommet/components/Image'; import Box from 'grommet/components/Box'; import Heading from 'grommet/components/Heading'; import Carousel from 'grommet/components/Carousel'; import styles from './MyHero.module.scss'; class MyHero extends React.Component { render() { return ( <Hero background={ <Image fit="cover" size="large" src="/public/bikegrass.jpeg" /> } backgroundColorIndex="dark" size="large" > <Box direction="row" justify="end" align="center" textAlign="right" > <Box basis="small" align="end" pad="small"> <Image src="/public/wolf.png" size="small"/> </Box> <Box basis="large" align="start" pad="none"> <Heading className={styles.heading} margin="none" uppercase={true} strong={false}> Nordic Bikes </Heading> </Box> </Box> </Hero> ) } } export default MyHero
Update user provider to expect model.
<?php namespace Aurora\Auth; use GuzzleHttp\Exception\ClientException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Auth\EloquentUserProvider; class NorthstarUserProvider extends EloquentUserProvider implements UserProvider { /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { // Get the Northstar user $northstar = new \Aurora\Services\Northstar; $response = $northstar->getUser('email', $credentials['email']); // If a matching user is found, find or create local Aurora user. return $this->createModel()->firstOrCreate([ '_id' => $response->id, ]); } /** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { $northstar = new \Aurora\Services\Northstar; try { $northstar->login($credentials); return true; } catch (ClientException $e) { // If an exception is returned, we couldn't log in... } return false; } }
<?php namespace Aurora\Auth; use GuzzleHttp\Exception\ClientException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Auth\EloquentUserProvider; class NorthstarUserProvider extends EloquentUserProvider implements UserProvider { /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { // Get the Northstar user $northstar = new \Aurora\Services\Northstar; $response = $northstar->getUser('email', $credentials['email']); // If a matching user is found, find or create local Aurora user. return $this->createModel()->firstOrCreate([ '_id' => $response['_id'], ]); } /** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { $northstar = new \Aurora\Services\Northstar; try { $northstar->login($credentials); return true; } catch (ClientException $e) { // If an exception is returned, we couldn't log in... } return false; } }
Move ITEM_MAP to method variable
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' def handle(self, *args, **options): s = serial.Serial(settings.ARDUINO_433, 9600) ITEM_MAP = settings.ARDUINO_433_ITEM_MAP sent_event_map = {} while True: line = s.readline() if line.startswith("Received "): id = line.split(" ")[1] if id in ITEM_MAP: item_name = ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: continue logger.info("Processing trigger %s (%s)", item_name, id) process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: logger.warn("Unknown ID: %s", id)
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' def handle(self, *args, **options): s = serial.Serial(settings.ARDUINO_433, 9600) ITEM_MAP = settings.ARDUINO_433_ITEM_MAP sent_event_map = {} while True: line = s.readline() if line.startswith("Received "): id = line.split(" ")[1] if id in self.ITEM_MAP: item_name = self.ITEM_MAP[id] if item_name in sent_event_map: if sent_event_map[item_name] > time.time() - 5: continue logger.info("Processing trigger %s (%s)", item_name, id) process_automatic_trigger(item_name) sent_event_map[item_name] = time.time() else: logger.warn("Unknown ID: %s", id)
Make the message nicer with a picture of jen
@extends('layouts.master') @section('main_content') @include('layouts.header', ['header' => 'Upload a CSV for import']) <div class="container -padded"> <div class="wrapper"> <div class="container__block -narrow"> <article class="figure margin-bottom-none -left -small"> <div class="figure__media rounded-figure"> <img src={{asset('images/Jen.png')}}> </div> <div class="figure__body"> <strong>Attention:</strong> <br> <p class="footnote">For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack</p> </div> </article> </div> <div class="container__block -narrow"> <form action={{url('/import')}} method="post" enctype="multipart/form-data"> {{ csrf_field()}} <div class="form-item"> <label for="upload-file" class="field-label">Upload</label> <input type="file" name="upload-file" class="form-control"> </div> <label class="field-label">Type of Import</label> <div class="form-item"> <label class="option -checkbox"> <input checked type="checkbox" id="importType" value="turbovote" name="importType"> <span class="option__indicator"></span> <span>Turbovote Import</span> </label> </div> <div class="form-actions -padded"> <input type="submit" class="button" value="Submit CSV"> </div> </form> </div> </div> </div> @stop
@extends('layouts.master') @section('main_content') @include('layouts.header', ['header' => 'Upload a CSV for import']) <div class="container -padded"> <div class="wrapper"> <div class="container__block -narrow"> <p>For the time being, This feature should only be used by Jen Ng. If you have any questions please reach out to Jen directly or post a message in the #rogue channel in slack</p> </div> <div class="container__block -narrow"> <form action={{url('/import')}} method="post" enctype="multipart/form-data"> {{ csrf_field()}} <div class="form-item"> <label for="upload-file" class="field-label">Upload</label> <input type="file" name="upload-file" class="form-control"> </div> <label class="field-label">Type of Import</label> <div class="form-item"> <label class="option -checkbox"> <input checked type="checkbox" id="importType" value="turbovote" name="importType"> <span class="option__indicator"></span> <span>Turbovote Import</span> </label> </div> <div class="form-actions -padded"> <input type="submit" class="button" value="Submit CSV"> </div> </form> </div> </div> </div> @stop
Use 'open' to open about dialog URLs on OS X
import gtk import os import sys def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): if sys.platform == 'darwin': return '/usr/bin/open' for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
import gtk import os def _find_program_in_path(progname): try: path = os.environ['PATH'] except KeyError: path = os.defpath for dir in path.split(os.pathsep): p = os.path.join(dir, progname) if os.path.exists(p): return p return None def _find_url_open_program(): for progname in ['xdg-open', 'htmlview', 'gnome-open']: path = _find_program_in_path(progname) if path != None: return path return None def _open_url(dialog, url): prog = _find_url_open_program() os.spawnl(os.P_NOWAIT, prog, prog, url) class AboutDialog(gtk.AboutDialog): def __init__(self, parent): gtk.AboutDialog.__init__(self) self.set_transient_for(parent) self.set_name("Reinteract") self.set_logo_icon_name("reinteract") self.set_copyright("Copyright \302\251 2007-2008 Owen Taylor, Red Hat, Inc., and others") self.set_website("http://www.reinteract.org") self.connect("response", lambda d, r: d.destroy()) def run(self): if _find_url_open_program() != None: gtk.about_dialog_set_url_hook(_open_url) gtk.AboutDialog.run(self)
feature/oop-api-refactoring: Remove unused imports and `pass` keywords
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- language : Language The required language. template : Template The required template. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The ported estimator. """ @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- language : Language The required language. template : Template The required template directory : str or Path The destination directory. to_json : bool (default: False) Return the result as JSON string. kwargs Returns ------- The paths to the dumped files. """
# -*- coding: utf-8 -*- from typing import Union, Optional, Tuple from pathlib import Path from abc import ABC, abstractmethod from sklearn_porter.enums import Method, Language, Template class EstimatorApiABC(ABC): """ An abstract interface to ensure equal methods between the main class `sklearn_porter.Estimator` and all subclasses in `sklearn-porter.estimator.*`. """ @abstractmethod def port( self, language: Optional[Language] = None, template: Optional[Template] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Port an estimator. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template. kwargs Returns ------- The ported estimator. """ pass @abstractmethod def dump( self, language: Optional[Language] = None, template: Optional[Template] = None, directory: Optional[Union[str, Path]] = None, to_json: bool = False, **kwargs ) -> Union[str, Tuple[str, str]]: """ Dump an estimator to the filesystem. Parameters ---------- method : Method The required method. language : Language The required language. template : Template The required template directory : str or Path The destination directory. kwargs Returns ------- The paths to the dumped files. """ pass
Add full image url to Station serializer
from django.conf import settings from django.contrib.sites.models import Site from rest_framework import serializers from base.models import (Antenna, Data, Observation, Satellite, Station, Transponder) class AntennaSerializer(serializers.ModelSerializer): class Meta: model = Antenna fields = ('frequency', 'band', 'antenna_type') class StationSerializer(serializers.ModelSerializer): class Meta: model = Station fields = ('owner', 'name', 'image', 'alt', 'lat', 'lng', 'antenna', 'featured', 'featured_date') image = serializers.SerializerMethodField('image_url') def image_url(self, obj): site = Site.objects.get_current() return '{}{}{}'.format(site, settings.MEDIA_URL, obj.image) class SatelliteSerializer(serializers.ModelSerializer): class Meta: model = Satellite fields = ('norad_cat_id', 'name') class TransponderSerializer(serializers.ModelSerializer): class Meta: model = Transponder fields = ('description', 'alive', 'uplink_low', 'uplink_high', 'downlink_low', 'downlink_high', 'mode', 'invert', 'baud', 'satellite') class ObservationSerializer(serializers.ModelSerializer): class Meta: model = Observation fields = ('satellite', 'transponder', 'author', 'start', 'end') class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('start', 'end', 'observation', 'ground_station', 'payload')
from rest_framework import serializers from base.models import (Antenna, Data, Observation, Satellite, Station, Transponder) class AntennaSerializer(serializers.ModelSerializer): class Meta: model = Antenna fields = ('frequency', 'band', 'antenna_type') class StationSerializer(serializers.ModelSerializer): class Meta: model = Station fields = ('owner', 'name', 'image', 'alt', 'lat', 'lng', 'antenna', 'featured', 'featured_date') class SatelliteSerializer(serializers.ModelSerializer): class Meta: model = Satellite fields = ('norad_cat_id', 'name') class TransponderSerializer(serializers.ModelSerializer): class Meta: model = Transponder fields = ('description', 'alive', 'uplink_low', 'uplink_high', 'downlink_low', 'downlink_high', 'mode', 'invert', 'baud', 'satellite') class ObservationSerializer(serializers.ModelSerializer): class Meta: model = Observation fields = ('satellite', 'transponder', 'author', 'start', 'end') class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('start', 'end', 'observation', 'ground_station', 'payload')
Move GC collect after loading unit test function.
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = "Unittest (%s)"%(test) padding = "."*(60-len(s)) print(s + padding + ("PASSED" if passed == True else "FAILED")) for module in sorted(os.listdir(SCRIPT_DIR)): mod_path = "/".join((SCRIPT_DIR, module)) for test in sorted(os.listdir(mod_path)): if test.endswith(".py"): test_passed = True test_path = "/".join((mod_path, test)) try: exec(open(test_path).read()) gc.collect() if unittest(DATA_DIR, TEMP_DIR) == False: raise Exception() except Exception as e: test_failed = True test_passed = False print_result(test, test_passed) if test_failed: print("\nSome tests have FAILED!!!\n\n") else: print("\nAll tests PASSED.\n\n")
# OpenMV Unit Tests. # import os, sensor, gc TEST_DIR = "unittest" TEMP_DIR = "unittest/temp" DATA_DIR = "unittest/data" SCRIPT_DIR = "unittest/script" if not (TEST_DIR in os.listdir("")): raise Exception('Unittest dir not found!') print("") test_failed = False def print_result(test, passed): s = "Unittest (%s)"%(test) padding = "."*(60-len(s)) print(s + padding + ("PASSED" if passed == True else "FAILED")) for module in sorted(os.listdir(SCRIPT_DIR)): mod_path = "/".join((SCRIPT_DIR, module)) for test in sorted(os.listdir(mod_path)): if test.endswith(".py"): test_passed = True test_path = "/".join((mod_path, test)) try: gc.collect() exec(open(test_path).read()) if unittest(DATA_DIR, TEMP_DIR) == False: raise Exception() except Exception as e: test_failed = True test_passed = False print_result(test, test_passed) if test_failed: print("\nSome tests have FAILED!!!\n\n") else: print("\nAll tests PASSED.\n\n")
Add return statent to 'run' method
<?php declare(strict_types=1); namespace Onion\Framework\Application; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; class Application implements ServerMiddlewareInterface { /** * @var DelegateInterface */ protected $delegate; /** * @var EmitterInterface */ protected $emitter; public function __construct(DelegateInterface $delegate, EmitterInterface $emitter) { $this->delegate = $delegate; $this->emitter = $emitter; } public function run(ServerRequestInterface $request) { return $this->emitter->emit($this->process($request, null)); } /** * @param ServerRequestInterface $request * @param DelegateInterface $delegate * * @throws \Throwable Rethrows the exceptions if no $delegate is available * * @return ResponseInterface */ public function process(ServerRequestInterface $request, DelegateInterface $delegate = null): ResponseInterface { try { return $this->delegate->process($request); } catch (\Throwable $ex) { if ($delegate === null) { throw $ex; } return $delegate->process($request->withAttribute('exception', $ex)); } } }
<?php declare(strict_types=1); namespace Onion\Framework\Application; use Interop\Http\Middleware\DelegateInterface; use Interop\Http\Middleware\ServerMiddlewareInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\EmitterInterface; class Application implements ServerMiddlewareInterface { /** * @var DelegateInterface */ protected $delegate; /** * @var EmitterInterface */ protected $emitter; public function __construct(DelegateInterface $delegate, EmitterInterface $emitter) { $this->delegate = $delegate; $this->emitter = $emitter; } public function run(ServerRequestInterface $request) { $this->emitter->emit($this->process($request, null)); } /** * @param ServerRequestInterface $request * @param DelegateInterface $delegate * * @throws \Throwable Rethrows the exceptions if no $delegate is available * * @return ResponseInterface */ public function process(ServerRequestInterface $request, DelegateInterface $delegate = null): ResponseInterface { try { return $this->delegate->process($request); } catch (\Throwable $ex) { if ($delegate === null) { throw $ex; } return $delegate->process($request->withAttribute('exception', $ex)); } } }
Fix bug with list formatting Before it would completely fail to format any list of strings
from enum import Enum, unique from inspect import signature, isclass from mycroft.plugin.base_plugin import BasePlugin from mycroft.util import log @unique class Format(Enum): speech = 1 text = 2 class FormatterPlugin(BasePlugin): and_ = 'and' def __init__(self, rt): super().__init__(rt) self.formatters = { str: str, int: str, float: lambda x: '{:.2f}'.format(x), list: self.format_list } def format_list(self, obj, fmt): if len(obj) == 0: return '' if len(obj) == 1: return self.format(obj[0], fmt) return '{}, {} {}'.format( ', '.join(self.format(i, fmt) for i in obj[:-1]), self.and_, self.format(obj[-1], fmt) ) def add(self, cls, formatter): self.formatters[cls] = formatter def format(self, obj, fmt=Format.speech): handler = self.formatters.get(type(obj)) if not handler: log.warning('No formatter for', type(obj)) return str(obj) if isclass(handler) or len(signature(handler).parameters) == 1: return handler(obj) else: return handler(obj, fmt)
from enum import Enum, unique from inspect import signature, isclass from mycroft.plugin.base_plugin import BasePlugin from mycroft.util import log @unique class Format(Enum): speech = 1 text = 2 class FormatterPlugin(BasePlugin): and_ = 'and' def __init__(self, rt): super().__init__(rt) self.formatters = { str: str, int: str, float: lambda x: '{:.2f}'.format(x), list: self.format_list } def format_list(self, obj, fmt): if len(obj) == 0: return '' if len(obj) == 1: return self.format(obj[0], fmt) return '{}, {} {}'.format( ', '.join(self.format(obj[:-1], fmt)), self.and_, self.format(obj[-1], fmt) ) def add(self, cls, formatter): self.formatters[cls] = formatter def format(self, obj, fmt=Format.speech): handler = self.formatters.get(type(obj)) if not handler: log.warning('No formatter for', type(obj)) return str(obj) if isclass(handler) or len(signature(handler).parameters) == 1: return handler(obj) else: return handler(obj, fmt)
Handle empty cells in the spreadsheet
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def attribute_exists(self, key): return key in self.detailed_data def get_datum(self, key): datum = self.handle_bad_data(self.get(key)) return datum def get(self, key): return self.detailed_data[key] def identifier(self): """Return a unique identifier for the service""" return self.get('Slug') def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr') def handle_bad_data(self, datum): # TODO: Should we be more explicit about non-requested (***) data? if datum == '' or datum == '-' or datum == '***' or datum == None: return None elif not isinstance(datum, (int, long, float, complex)): # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None else: return datum
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def attribute_exists(self, key): return key in self.detailed_data def get_datum(self, key): datum = self.handle_bad_data(self.get(key)) return datum def get(self, key): return self.detailed_data[key] def identifier(self): """Return a unique identifier for the service""" return self.get('Slug') def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr') def handle_bad_data(self, datum): # TODO: Should we be more explicit about non-requested (***) data? if datum == '' or datum == '-' or datum == '***': return None elif not isinstance(datum, (int, long, float, complex)): # If the value we get from the spreadsheet is not numeric, send # that to Backdrop as a null data point print "Data from the spreadsheet doesn't look numeric: <{0}> (from {1})".format(datum, self.identifier()) return None else: return datum
Update default background color & formatting updates
import React, { Component, PropTypes, View, Image } from 'react-native'; import Icon from './Icon'; import { getColor } from './helpers'; export default class Avatar extends Component { static propTypes = { icon: PropTypes.string, src: PropTypes.string, size: PropTypes.number, color: PropTypes.string, backgroundColor: PropTypes.string }; static defaultProps = { size: 40, color: '#ffffff', backgroundColor: getColor('paperGrey500') }; render() { const { icon, src, size, color, backgroundColor } = this.props; if (src) { return ( <Image style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }} source={{ uri: src }} /> ); } if (icon) { return ( <View style={{ flex: 1 }}> <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: getColor(backgroundColor), alignItems:'center' }}> <Icon name={icon} color={color} size={0.6 * size} style={{ position: 'relative', top: -3 }} /> </View> </View> ); } } }
import React, { Component, PropTypes, View, Image } from 'react-native'; import Icon from './Icon'; import { ICON_NAME } from './config'; export default class Avatar extends Component { static propTypes = { icon: PropTypes.string, src: PropTypes.string, size: PropTypes.number, color: PropTypes.string, backgroundColor: PropTypes.string }; static defaultProps = { size: 40, color: '#ffffff', backgroundColor: '#bdbdbd' }; render() { const { icon, src, size, color, backgroundColor } = this.props; if (src) { return ( <Image style={{ width: size, height: size, borderRadius: size / 2, borderColor: 'rgba(0,0,0,.1)', borderWidth: 1 }} source={{ uri: src }} /> ); } if (icon) { return ( <View style={{ flex: 1 }}> <View style={{ width: size, height: size, borderRadius: size / 2, backgroundColor: backgroundColor, alignItems:'center' }}> <Icon name={icon} color={color} size={0.6 * size} style={{ position: 'relative', top: -3 }} /> </View> </View> ); } } }
Fix cache.manifest generation when desktop app isn't loaded, also don't include unnecessary touchmaplite files (MOLLY-113)
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers if 'admin' in dirs: dirs.remove('admin') if 'desktop' in dirs: dirs.remove('desktop') if 'markers' in dirs: dirs.remove('markers') if root == os.path.join(setting.STATIC_ROOT, 'touchmaplite', 'images'): # Don't cache touchmaplite markers, we don't use them if 'markers' in dirs: dirs.remove('markers') if 'iui' in dirs: dirs.remove('iui') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue # Don't cache ourselves! print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
import os import os.path from django.core.management.base import NoArgsCommand from django.conf import settings class Command(NoArgsCommand): can_import_settings = True def handle_noargs(self, **options): cache_manifest_path = os.path.join(settings.STATIC_ROOT, 'cache.manifest') static_prefix_length = len(settings.STATIC_ROOT.split(os.sep)) with open(cache_manifest_path, 'w') as cache_manifest: print >>cache_manifest, "CACHE MANIFEST" print >>cache_manifest, "CACHE:" for root, dirs, files in os.walk(settings.STATIC_ROOT): if root == settings.STATIC_ROOT: # Don't cache admin media, desktop or markers dirs.remove('admin') dirs.remove('desktop') dirs.remove('markers') url = '/'.join(root.split(os.sep)[static_prefix_length:]) for file in files: # Don't cache uncompressed JS/CSS _, ext = os.path.splitext(file) if ext in ('.js','.css') and 'c' != url.split('/')[0]: continue print >>cache_manifest, "%s%s/%s" % (settings.STATIC_URL, url, file)
Support both Python 2 and 3
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "[email protected]" URL = "http://github.com/pinax/phileo" VERSION = "1.3" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=read("README.rst"), author=AUTHOR, author_email=AUTHOR_EMAIL, license="MIT", url=URL, packages=find_packages(), package_data={ "phileo": [ "templates/phileo/_like.html", "templates/phileo/_widget.html", "templates/phileo/_widget_brief.html" ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Framework :: Django", ], test_suite="runtests.runtests", tests_require=[ ], zip_safe=False, )
import codecs from os import path from setuptools import find_packages, setup def read(*parts): filename = path.join(path.dirname(__file__), *parts) with codecs.open(filename, encoding="utf-8") as fp: return fp.read() PACKAGE = "phileo" NAME = "phileo" DESCRIPTION = "a liking app" AUTHOR = "Pinax Team" AUTHOR_EMAIL = "[email protected]" URL = "http://github.com/pinax/phileo" VERSION = "1.3" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=read("README.rst"), author=AUTHOR, author_email=AUTHOR_EMAIL, license="MIT", url=URL, packages=find_packages(), package_data={ "phileo": [ "templates/phileo/_like.html", "templates/phileo/_widget.html", "templates/phileo/_widget_brief.html" ] }, classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ], test_suite="runtests.runtests", tests_require=[ ], zip_safe=False, )
Update JSMA test tutorial constant
import unittest class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, 'train_end': 1000, 'test_start': 0, 'test_end': 1666, 'viz_enabled': False, 'source_samples': 1, 'nb_epochs': 2} report = mnist_tutorial_jsma.mnist_tutorial_jsma(**jsma_tutorial_args) # Check accuracy values contained in the AccuracyReport object self.assertTrue(report.clean_train_clean_eval > 0.75) self.assertTrue(report.clean_train_adv_eval < 0.05) # There is no adversarial training in the JSMA tutorial self.assertTrue(report.adv_train_clean_eval == 0.) self.assertTrue(report.adv_train_adv_eval == 0.) if __name__ == '__main__': unittest.main()
import unittest class TestMNISTTutorialJSMA(unittest.TestCase): def test_mnist_tutorial_jsma(self): from tutorials import mnist_tutorial_jsma # Run the MNIST tutorial on a dataset of reduced size # and disable visualization. jsma_tutorial_args = {'train_start': 0, 'train_end': 10000, 'test_start': 0, 'test_end': 1666, 'viz_enabled': False, 'source_samples': 1, 'nb_epochs': 2} report = mnist_tutorial_jsma.mnist_tutorial_jsma(**jsma_tutorial_args) print(report.clean_train_adv_eval) # Check accuracy values contained in the AccuracyReport object self.assertTrue(report.clean_train_clean_eval > 0.75) self.assertTrue(report.clean_train_adv_eval < 0.05) # There is no adversarial training in the JSMA tutorial self.assertTrue(report.adv_train_clean_eval == 0.) self.assertTrue(report.adv_train_adv_eval == 0.) if __name__ == '__main__': unittest.main()