text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Input: Fix movement using the "S" key to go down (typo!)
var Player = Entity.extend({ init: function() { this._super(); this.width = 32; this.height = 18; this.setCoord(9, 2); this.sprite = Gfx.load('hero'); this.spriteShadow = Gfx.load('hero_shadow'); }, update: function() { if (Keyboard.isKeyDown(KeyEvent.DOM_VK_LEFT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_A)) { this.velocityX = -this.movementSpeed; this.direction = Direction.LEFT; } else if (Keyboard.isKeyDown(KeyEvent.DOM_VK_RIGHT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_D)) { this.velocityX = +this.movementSpeed; this.direction = Direction.RIGHT; } else { this.velocityX = 0; } if (Keyboard.isKeyDown(KeyEvent.DOM_VK_UP) || Keyboard.isKeyDown(KeyEvent.DOM_VK_W)) { this.velocityY = -this.movementSpeed; this.direction = Direction.UP; } else if (Keyboard.isKeyDown(KeyEvent.DOM_VK_DOWN) || Keyboard.isKeyDown(KeyEvent.DOM_VK_S)) { this.velocityY = +this.movementSpeed; this.direction = Direction.DOWN; } else { this.velocityY = 0; } this._super(); } });
var Player = Entity.extend({ init: function() { this._super(); this.width = 32; this.height = 18; this.setCoord(9, 2); this.sprite = Gfx.load('hero'); this.spriteShadow = Gfx.load('hero_shadow'); }, update: function() { if (Keyboard.isKeyDown(KeyEvent.DOM_VK_LEFT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_A)) { this.velocityX = -this.movementSpeed; this.direction = Direction.LEFT; } else if (Keyboard.isKeyDown(KeyEvent.DOM_VK_RIGHT) || Keyboard.isKeyDown(KeyEvent.DOM_VK_D)) { this.velocityX = +this.movementSpeed; this.direction = Direction.RIGHT; } else { this.velocityX = 0; } if (Keyboard.isKeyDown(KeyEvent.DOM_VK_UP) || Keyboard.isKeyDown(KeyEvent.DOM_VK_W)) { this.velocityY = -this.movementSpeed; this.direction = Direction.UP; } else if (Keyboard.isKeyDown(KeyEvent.DOM_VK_DOWN) || Keyboard.isKeyDown(Keyboard.DOM_VK_S)) { this.velocityY = +this.movementSpeed; this.direction = Direction.DOWN; } else { this.velocityY = 0; } this._super(); } });
Fix handling broken daily endpoint
<h3>{{ trans('achievement.daily.type.'.$type) }}</h3> <ul class="itemList"> @foreach($daily->achievements->{$type} as $achievement) @if(isset($achievement->achievement)) <li> {{ $achievement->achievement->link(32, null, $achievement->name[$language]) }} <span class="daily-box__level"> @if(!is_null($achievement->level) && $type !== 'fractals') @lang('achievement.daily.level', [ 'level' => $achievement->level->min == $achievement->level->max ? $achievement->level->min : $achievement->level->min.' – '.$achievement->level->max ]) @endif @if(isset($achievement->required_access) && !is_array($achievement->required_access)) @if(!is_null($achievement->level) && $type !== 'fractals') • @endif {{ trans('achievement.access.condition.'.$achievement->required_access->condition, [ 'product' => trans('achievement.access.product.'.$achievement->required_access->product) ]) }} @endif </span> </li> @endif @endforeach </ul>
<h3>{{ trans('achievement.daily.type.'.$type) }}</h3> <ul class="itemList"> @foreach($daily->achievements->{$type} as $achievement) @if(isset($achievement->achievement)) <li> {{ $achievement->achievement->link(32, null, $achievement->name[$language]) }} <span class="daily-box__level"> @if(!is_null($achievement->level) && $type !== 'fractals') @lang('achievement.daily.level', [ 'level' => $achievement->level->min == $achievement->level->max ? $achievement->level->min : $achievement->level->min.' – '.$achievement->level->max ]) @endif @if(isset($achievement->required_access)) @if(!is_null($achievement->level) && $type !== 'fractals') • @endif {{ trans('achievement.access.condition.'.$achievement->required_access->condition, [ 'product' => trans('achievement.access.product.'.$achievement->required_access->product) ]) }} @endif </span> </li> @endif @endforeach </ul>
Add check for no records.
var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.handler = function(event, context) { console.log(JSON.stringify(event, null, 2)); if(event.Records.length == 0) { //Nothing to do console.log('Got no records.'); context.succeed(); return; } var firstRecord = event.Records[0]; var stackName = context.functionName.split("-")[0]; var accountId = firstRecord.eventSourceARN.split(":")[4]; var s3Bucket = stackName + "-eventarchive-" + accountId; var date = new Date(); var s3Key = date.toISOString().split("T")[0] + "/" + firstRecord.kinesis.sequenceNumber + ".json"; var body = "{ \"Records\" : [\n"; event.Records.forEach(function(record, index) { // Kinesis data is base64 encoded so decode here var payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); console.log('Decoded payload:', payload); body = body + (index == 0 ? "" : ",\n") + payload; }); body = body + "\n]}"; var params = { Bucket: s3Bucket, Key: s3Key, Body: body }; s3.putObject(params, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred context.fail(err); } else { console.log(data); // successful response context.succeed(); } }); };
var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.handler = function(event, context) { console.log(JSON.stringify(event, null, 2)); var stackName = context.functionName.split("-")[0]; var accountId = event.Records[0].eventSourceARN.split(":")[4]; var s3Bucket = stackName + "-eventarchive-" + accountId; var date = new Date(); var s3Key = date.toISOString().split("T")[0] + "/" + event.Records[0].kinesis.sequenceNumber + ".json"; var body = "{ \"Records\" : [\n"; event.Records.forEach(function(record, index) { // Kinesis data is base64 encoded so decode here var payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); console.log('Decoded payload:', payload); body = body + (index == 0 ? "" : ",\n") + payload; }); body = body + "\n]}"; var params = { Bucket: s3Bucket, Key: s3Key, Body: body }; s3.putObject(params, function(err, data) { if (err) { console.log(err, err.stack); // an error occurred context.fail(err); } else { console.log(data); // successful response context.succeed(); } }); };
Fix input submit, now clear itself after submit
(function (angular){ 'use strict'; angular.module('app') .controller('counterController', counterController) .controller('todoController', todoController) counterController.$inject = [] todoController.$inject = [] function counterController(){ this.counter = 0; this.add = function() { this.counter >= 10 ? this.counter : this.counter ++; } this.sub = function(){ this.counter === 0 ? this.counter : this.counter --; } }; function todoController(){ this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}]; this.newTask = ''; this.completed = 1; this.total = this.tasks.length; this.showCompleted = true this.add = function(){ console.log(this.newTask) this.tasks.push({name: this.newTask, complete: false}); this.newTask = '' this.total = this.tasks.length; }.bind(this) this.complete = function(taskIndex){ console.log(taskIndex); this.tasks[taskIndex].complete = true; this.completed = this.tasks.reduce(function(p, n){ return n.complete === true ? p + 1 : p; }, 0); } this.hideCompleted= function(){ showCompleted = false }; } })(window.angular);
(function (angular){ 'use strict'; angular.module('app') .controller('counterController', counterController) .controller('todoController', todoController) counterController.$inject = [] todoController.$inject = [] function counterController(){ this.counter = 0; this.add = function() { this.counter >= 10 ? this.counter : this.counter ++; } this.sub = function(){ this.counter === 0 ? this.counter : this.counter --; } }; function todoController(){ this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}]; this.newTask = ''; this.completed = 1; this.total = this.tasks.length; this.add = function(){ console.log(this.newTask) this.tasks.push({name: this.newTask, complete: false}); this.total = this.tasks.length; }.bind(this) this.complete = function(taskIndex){ console.log(taskIndex); this.tasks[taskIndex].complete = true; this. this.completed = this.tasks.reduce(function(p, n){ return n.complete === true ? p + 1 : p; }, 0); this.removeCompleted= function(){ }; } } })(window.angular);
Apply a default timer name
<?php namespace SamBenne\Execute; /** * Class Timer * @package Execute */ class Timer { /** * @var \SamBenne\Execute\Timer|null */ protected static $instance = null; /** * @var array $timers */ private static $timers = []; public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static(); } return static::$instance; } /** * Start Timer * * @param string $id */ public static function start( $id = "default") { self::$timers[$id] = [ 'start' => microtime(TRUE) ]; } /** * Stop Timer * * @param string $id */ public static function stop( $id = "default") { self::$timers[$id]['stop'] = microtime(TRUE); } /** * Output Time * * This will call self::stop * * @param string $id * * @return string */ public static function output( $id = "default") { self::stop($id); $timer = self::$timers[$id]; $executionTime = ($timer['stop'] - $timer['start']); return '<b>Total Execution Time:</b> '.$executionTime.' Secs'; } }
<?php namespace SamBenne\Execute; /** * Class Timer * @package Execute */ class Timer { /** * @var \SamBenne\Execute\Timer|null */ protected static $instance = null; /** * @var array $timers */ private static $timers = []; public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static(); } return static::$instance; } /** * Start Timer * * @param string $id */ public static function start( $id ) { self::$timers[$id] = [ 'start' => microtime(TRUE) ]; } /** * Stop Timer * * @param string $id */ public static function stop( $id ) { self::$timers[$id]['stop'] = microtime(TRUE); } /** * Output Time * * This will call self::stop * * @param string $id * * @return string */ public static function output( $id ) { self::stop($id); $timer = self::$timers[$id]; $executionTime = ($timer['stop'] - $timer['start']); return '<b>Total Execution Time:</b> '.$executionTime.' Secs'; } }
Fix displaying undefined for episode.
angular.module('proxtop').controller('MainController', ['$scope', 'ipc', '$state', 'notification', '$mdToast', function($scope, ipc, $state, notification, $mdToast) { ipc.on('check-login', function(result) { if(result) { ipc.send('watchlist-update'); $state.go('profile'); } else { $state.go('login'); } }); ipc.on('error', function(severity, message) { $mdToast.show($mdToast.simple().content(severity + ':' + message)); }); var displayNotification = function(type) { return function(update) { notification.displayNotification('Proxtop', 'Episode ' + update.episode + ' of ' + update.name + ' is now available', '', function() { if(type == 'anime') { open.openAnime(update.id, update.episode, update.sub); } else { open.openManga(update.id, update.episode, update.sub); } }); }; }; ipc.on('new-anime-ep', displayNotification('anime')); ipc.on('new-manga-ep', displayNotification('manga')); ipc.send('check-login'); }]);
angular.module('proxtop').controller('MainController', ['$scope', 'ipc', '$state', 'notification', '$mdToast', function($scope, ipc, $state, notification, $mdToast) { ipc.on('check-login', function(result) { if(result) { ipc.send('watchlist-update'); $state.go('profile'); } else { $state.go('login'); } }); ipc.on('error', function(severity, message) { $mdToast.show($mdToast.simple().content(severity + ':' + message)); }); var displayNotification = function(type) { return function(update) { notification.displayNotification('Proxtop', 'Episode ' + update.ep + ' of ' + update.name + ' is now available', '', function() { if(type == 'anime') { open.openAnime(update.id, update.ep, update.sub); } else { open.openManga(update.id, update.ep, update.sub); } }); }; }; ipc.on('new-anime-ep', displayNotification('anime')); ipc.on('new-manga-ep', displayNotification('manga')); ipc.send('check-login'); }]);
Add css to add-option button
/* global $ */ (function (window, document, $) { 'use strict'; var LiveEditorToolbar = function LiveEditorToolbar (params) { this.init(params); }; LiveEditorToolbar.prototype.init = function (params) { this.$appendTo = params.$appendTo; this.create(); }; LiveEditorToolbar.prototype.create = function () { this.$modeSelect = $('<select class="form-control">') .append('<option value="edit">Edit mode</option>') .append('<option value="view">View mode</option>'); this.$buttonAddOption = $('<button type="button" class="btn btn-default add-option">+ add option</button>'); this.$undoButton = $('<button type="button" class="btn btn-default btn-undo">Undo</button>'); this.$codePanelButton = $('<button class="btn btn-primary btn-sm code-panel-button" type="button" data-toggle="collapse" data-target="#code-panel">').text('< edit code >'); this.$toolbar = $('<ul class="toolbar">'); this.$toolbar.append($('<li>').append(this.$buttonAddOption)); this.$toolbar.append($('<li>').append(this.$modeSelect)); this.$toolbar.append($('<li>').append(this.$undoButton)); this.$toolbar.append($('<li>').append(this.$codePanelButton)); this.$appendTo.append(this.$toolbar); }; window.LiveEditorToolbar = LiveEditorToolbar; })(window, document, $);
/* global $ */ (function (window, document, $) { 'use strict'; var LiveEditorToolbar = function LiveEditorToolbar (params) { this.init(params); }; LiveEditorToolbar.prototype.init = function (params) { this.$appendTo = params.$appendTo; this.create(); }; LiveEditorToolbar.prototype.create = function () { this.$modeSelect = $('<select class="form-control">') .append('<option value="edit">Edit mode</option>') .append('<option value="view">View mode</option>'); this.$buttonAddOption = $('<button class="add-option" type="button">+ add option</button>'); this.$undoButton = $('<button type="button" class="btn btn-default btn-undo">Undo</button>'); this.$codePanelButton = $('<button class="btn btn-primary btn-sm code-panel-button" type="button" data-toggle="collapse" data-target="#code-panel">').text('< edit code >'); this.$toolbar = $('<ul class="toolbar">'); this.$toolbar.append($('<li>').append(this.$buttonAddOption)); this.$toolbar.append($('<li>').append(this.$modeSelect)); this.$toolbar.append($('<li>').append(this.$undoButton)); this.$toolbar.append($('<li>').append(this.$codePanelButton)); this.$appendTo.append(this.$toolbar); } window.LiveEditorToolbar = LiveEditorToolbar; })(window, document, $);
Fix empty history issue, when we never could go back
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); if (not_push) phoxy.ApiRequest(url); else phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
phoxy._ClickHook = { _: {}, }; phoxy._ClickHook._.click = { InitClickHook: function() { document.querySelector('body').addEventListener('click', function(event) { var target = event.target; while (true) { if (target === null) return; if (target.nodeName === 'A') break; // only click on A is triggered target = target.parentElement; } var url = target.getAttribute('href'); if (url === undefined || target.hasAttribute('not-phoxy')) return; if (phoxy._.click.OnClick(url, false)) return; event.preventDefault() }, true); window.onpopstate = phoxy._.click.OnPopState; } , OnClick: function (url, not_push) { if (url.indexOf('#') !== -1) return true; if (url[0] === '/') url = url.substring(1); phoxy.MenuCall(url); return false; } , OnPopState: function(e) { var path = e.target.location.pathname; var hash = e.target.location.hash; phoxy._.click.OnClick(path, true); } };
Add linebreak to improve readability
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 = "([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(); } }
Abort if privileges can't be dropped
import grp import logging import os import pwd import sys from hades.common.cli import ( ArgumentParser, parser as common_parser, setup_cli_logging, ) logger = logging.getLogger(__name__) def drop_privileges(passwd, group): os.setgid(group.gr_gid) os.initgroups(passwd.pw_name, group.gr_gid) os.setuid(passwd.pw_uid) def main(): parser = ArgumentParser(parents=[common_parser]) parser.add_argument('user') parser.add_argument('command') parser.add_argument('arguments', nargs='*') args = parser.parse_args() setup_cli_logging(parser.prog, args) try: passwd = pwd.getpwnam(args.user) group = grp.getgrgid(passwd.pw_gid) except KeyError: logger.critical("No such user or group") return os.EX_NOUSER filename = args.command try: drop_privileges(passwd, group) except PermissionError: logging.exception("Can't drop privileges") return os.EX_NOPERM try: os.execvp(filename, [filename] + args.arguments) except (FileNotFoundError, PermissionError): logger.critical("Could not execute {}".format(filename), file=sys.stderr) return os.EX_NOINPUT except OSError: logger.exception("An OSError occurred") return os.EX_OSERR if __name__ == '__main__': sys.exit(main())
import grp import logging import os import pwd import sys from hades.common.cli import ( ArgumentParser, parser as common_parser, setup_cli_logging, ) logger = logging.getLogger(__name__) def drop_privileges(passwd, group): if os.geteuid() != 0: logger.error("Can't drop privileges (EUID != 0)") return os.setgid(group.gr_gid) os.initgroups(passwd.pw_name, group.gr_gid) os.setuid(passwd.pw_uid) def main(): parser = ArgumentParser(parents=[common_parser]) parser.add_argument('user') parser.add_argument('command') parser.add_argument('arguments', nargs='*') args = parser.parse_args() setup_cli_logging(parser.prog, args) try: passwd = pwd.getpwnam(args.user) group = grp.getgrgid(passwd.pw_gid) except KeyError: logger.critical("No such user or group") return os.EX_NOUSER filename = args.command try: drop_privileges(passwd, group) os.execvp(filename, [filename] + args.arguments) except (FileNotFoundError, PermissionError): logger.critical("Could not execute {}".format(filename), file=sys.stderr) return os.EX_NOINPUT except OSError: logger.exception("An OSError occurred") return os.EX_OSERR if __name__ == '__main__': sys.exit(main())
Make the exception message check for malformed UTF-8 source looser so that SyntaxError triggered from UnicodeDecodeError is also acceptable.
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest from test import support class PEP3120Test(unittest.TestCase): def test_pep3120(self): self.assertEqual( "Питон".encode("utf-8"), b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( "\П".encode("utf-8"), b'\\\xd0\x9f' ) def test_badsyntax(self): try: import test.badsyntax_pep3120 except SyntaxError as msg: msg = str(msg) self.assertTrue('UTF-8' in msg or 'utf8' in msg) else: self.fail("expected exception didn't occur") class BuiltinCompileTests(unittest.TestCase): # Issue 3574. def test_latin1(self): # Allow compile() to read Latin-1 source. source_code = '# coding: Latin-1\nu = "Ç"\n'.encode("Latin-1") try: code = compile(source_code, '<dummy>', 'exec') except SyntaxError: self.fail("compile() cannot handle Latin-1 source") ns = {} exec(code, ns) self.assertEqual('Ç', ns['u']) def test_main(): support.run_unittest(PEP3120Test, BuiltinCompileTests) if __name__=="__main__": test_main()
# This file is marked as binary in the CVS, to prevent MacCVS from recoding it. import unittest from test import support class PEP3120Test(unittest.TestCase): def test_pep3120(self): self.assertEqual( "Питон".encode("utf-8"), b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd' ) self.assertEqual( "\П".encode("utf-8"), b'\\\xd0\x9f' ) def test_badsyntax(self): try: import test.badsyntax_pep3120 except SyntaxError as msg: self.assertTrue(str(msg).find("Non-UTF-8 code starting with") >= 0) else: self.fail("expected exception didn't occur") class BuiltinCompileTests(unittest.TestCase): # Issue 3574. def test_latin1(self): # Allow compile() to read Latin-1 source. source_code = '# coding: Latin-1\nu = "Ç"\n'.encode("Latin-1") try: code = compile(source_code, '<dummy>', 'exec') except SyntaxError: self.fail("compile() cannot handle Latin-1 source") ns = {} exec(code, ns) self.assertEqual('Ç', ns['u']) def test_main(): support.run_unittest(PEP3120Test, BuiltinCompileTests) if __name__=="__main__": test_main()
Add status messages when model gets destroyed
exports.definition = { config: { columns: { "name": "text", "captured": "integer", "url": "text", "capturedLat": "real", "capturedLon": "real" }, "defaults": { "name": "", "captured": 0, "url": "", "capturedLat": "", "capturedLon": "" }, adapter: { type: "sql", collection_name: "fugitives" } }, extendModel: function(Model) { _.extend(Model.prototype, { // extended functions and properties go here initialize: function() { this.on('change', function(model) { Ti.API.info('Attributes changed for fugitive: ' + model.get('name') + ':'); Ti.API.info(JSON.stringify(model.changed)); }); this.on('destroy', function(model) { Ti.API.info('Model was destroyed: ' + model.get('name')); }); } }); return Model; }, extendCollection: function(Collection) { _.extend(Collection.prototype, { initialize: function() { this.on('add', function(model) { Ti.API.info('Fugitive was added to collection: ' + model.get('name')); }); this.on('remove', function(model) { Ti.API.info('Fugitive was removed from collection: ' + model.get('name')); }); } // extended functions and properties go here }); return Collection; } };
exports.definition = { config: { columns: { "name": "text", "captured": "integer", "url": "text", "capturedLat": "real", "capturedLon": "real" }, "defaults": { "name": "", "captured": 0, "url": "", "capturedLat": "", "capturedLon": "" }, adapter: { type: "sql", collection_name: "fugitives" } }, extendModel: function(Model) { _.extend(Model.prototype, { // extended functions and properties go here initialize: function() { this.on('change', function(model) { Ti.API.info('Attributes changed for fugitive: ' + model.get('name') + ':'); Ti.API.info(JSON.stringify(model.changed)); }); } }); return Model; }, extendCollection: function(Collection) { _.extend(Collection.prototype, { initialize: function() { this.on('add', function(model) { Ti.API.info('Fugitive was added to collection: ' + model.get('name')); }); this.on('remove', function(model) { Ti.API.info('Fugitive was removed from collection: ' + model.get('name')); }); } // extended functions and properties go here }); return Collection; } };
Hide Blog button for now
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { StaticQuery, graphql } from 'gatsby'; import { ThemeProvider } from 'styled-components'; import Logo from '../Logo'; import Breadcrumb from '../Breadcrumb'; import PageTransition from '../PageTransition'; // import BlogLink from '../BlogLink'; import theme from '../../styles/theme'; import Container from '../../styles/Container'; import Header from '../../styles/Header'; import Main from '../../styles/Main'; import GlobalStyle from '../../styles/Global'; const Layout = ({ element, props }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title } } } `} render={data => ( <> <Helmet title={data.site.siteMetadata.title} meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }, ]} > <html lang="en" /> </Helmet> <ThemeProvider theme={theme}> <Container> <Header> <Logo icon /> <Breadcrumb /> </Header> <PageTransition {...props}> <Main>{element}</Main> </PageTransition> <GlobalStyle /> {/* <BlogLink /> */} </Container> </ThemeProvider> </> )} /> ); Layout.propTypes = { children: PropTypes.node.isRequired, }; export default Layout;
import React from 'react'; import PropTypes from 'prop-types'; import Helmet from 'react-helmet'; import { StaticQuery, graphql } from 'gatsby'; import { ThemeProvider } from 'styled-components'; import Logo from '../Logo'; import Breadcrumb from '../Breadcrumb'; import PageTransition from '../PageTransition'; import BlogLink from '../BlogLink'; import theme from '../../styles/theme'; import Container from '../../styles/Container'; import Header from '../../styles/Header'; import Main from '../../styles/Main'; import GlobalStyle from '../../styles/Global'; const Layout = ({ element, props }) => ( <StaticQuery query={graphql` query SiteTitleQuery { site { siteMetadata { title } } } `} render={data => ( <> <Helmet title={data.site.siteMetadata.title} meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }, ]} > <html lang="en" /> </Helmet> <ThemeProvider theme={theme}> <Container> <Header> <Logo icon /> <Breadcrumb /> </Header> <PageTransition {...props}> <Main>{element}</Main> </PageTransition> <GlobalStyle /> <BlogLink /> </Container> </ThemeProvider> </> )} /> ); Layout.propTypes = { children: PropTypes.node.isRequired, }; export default Layout;
Use sha1 module from core in generator package
(function () { 'use strict'; var assert = require('assert'); var _ = require('underscore'); var summarizer = require('../src/summarizer'); var sha1 = require('mathsync/src/sha1'); var utils = require('./utils_typedarrays'); function assertThatSetOfArrayEquals(arr1, arr2) { assert.equal(arr1.lenght, arr2.lenght); assert.ok(_(arr1).every(function (item1) { return _(arr2).some(function (item2) { return utils.isEqual(item1, item2); }); })); } function testSummarizer(builder) { it('generate summary with input items', function(done) { function serialize(value) { return new Int8Array(value).buffer; } builder([[1, 2], [2, 2], [3, 2]], serialize)(5).then(function (summary) { var diff = summary._asDifference(); assertThatSetOfArrayEquals(diff.added, [[1, 2], [2, 2], [3, 2]]); assert.equal(0, diff.removed.length); done(); }, function (err) { done(err); }); }); } describe('Summarizer', function() { describe('fromGenerator', function() { testSummarizer(function (array, serialize) { function* generator() { for (var i = 0; i < array.length; i++) { yield array[i]; } } return summarizer.fromGenerator(generator, serialize, sha1, 4); }); }); }); })();
(function () { 'use strict'; var assert = require('assert'); var _ = require('underscore'); var summarizer = require('../src/summarizer'); var sha1 = require('../src/sha1'); var utils = require('./utils_typedarrays'); function assertThatSetOfArrayEquals(arr1, arr2) { assert.equal(arr1.lenght, arr2.lenght); assert.ok(_(arr1).every(function (item1) { return _(arr2).some(function (item2) { return utils.isEqual(item1, item2); }); })); } function testSummarizer(builder) { it('generate summary with input items', function(done) { function serialize(value) { return new Int8Array(value).buffer; } builder([[1, 2], [2, 2], [3, 2]], serialize)(5).then(function (summary) { var diff = summary._asDifference(); assertThatSetOfArrayEquals(diff.added, [[1, 2], [2, 2], [3, 2]]); assert.equal(0, diff.removed.length); done(); }, function (err) { done(err); }); }); } describe('Summarizer', function() { describe('fromGenerator', function() { testSummarizer(function (array, serialize) { function* generator() { for (var i = 0; i < array.length; i++) { yield array[i]; } } return summarizer.fromGenerator(generator, serialize, sha1, 4); }); }); }); })();
Add a function to get user & user orgs
<?php namespace OrgManager\ApiClient; use GuzzleHttp\Client; class OrgManager { /** @var \GuzzleHttp\Client */ protected $client; /** @var string */ protected $baseUrl; /** * @param \GuzzleHttp\Client $client * @param string $apiToken * @param string $rootUrl */ public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com') { $this->client = $client; $this->apiToken = $apiToken; $this->baseUrl = $rootUrl.'/api'; } /** * * @return array */ public function getRoot() { return $this->get(''); } /** * * @return array */ public function getStats() { return $this->get('/stats'); } /** * * @return array */ public function getUser() { return $this->get('/user'); } /** * * @return array */ public function getOrgs() { return $this->get('/user/orgs'); } /** * @param string $resource * @param array $query * * @return array */ public function get($resource, array $query = []) { $query['api_token'] = $this->apiToken; $results = $this->client ->get("{$this->baseUrl}{$resource}", compact('query')) ->getBody() ->getContents(); return json_decode($results, true); } }
<?php namespace OrgManager\ApiClient; use GuzzleHttp\Client; class OrgManager { /** @var \GuzzleHttp\Client */ protected $client; /** @var string */ protected $baseUrl; /** * @param \GuzzleHttp\Client $client * @param string $apiToken * @param string $rootUrl */ public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com') { $this->client = $client; $this->apiToken = $apiToken; $this->baseUrl = $rootUrl.'/api'; } /** * * @return array */ public function getRoot() { return $this->get(''); } /** * * @return array */ public function getStats() { return $this->get('/stats'); } /** * @param string $resource * @param array $query * * @return array */ public function get($resource, array $query = []) { $query['api_token'] = $this->apiToken; $results = $this->client ->get("{$this->baseUrl}{$resource}", compact('query')) ->getBody() ->getContents(); return json_decode($results, true); } }
Enable easy login through browsable API (discovery through serializer_class)
from django.contrib.auth import logout from django.middleware.csrf import get_token as generate_csrf_token_for_frontend from rest_framework import status, viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from yunity.api.serializers import UserSerializer, AuthLoginSerializer class AuthViewSet(viewsets.GenericViewSet): serializer_class = AuthLoginSerializer @list_route(methods=['get']) def status(self, request): """ Get the login state (logged in user) --- response_serializer: UserSerializer """ generate_csrf_token_for_frontend(request) if request.user.is_anonymous(): serializer = UserSerializer() else: serializer = UserSerializer(request.user) return Response(serializer.data) def create(self, request, **kwargs): """ Log in --- request_serializer: AuthLoginSerializer response_serializer: UserSerializer """ serializer = AuthLoginSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): return Response(data=UserSerializer(request.user).data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) @list_route(methods=['POST']) def logout(self, request, **kwargs): logout(request) return Response(status = status.HTTP_200_OK)
from django.contrib.auth import logout from django.middleware.csrf import get_token as generate_csrf_token_for_frontend from rest_framework import status, viewsets from rest_framework.decorators import list_route from rest_framework.response import Response from yunity.api.serializers import UserSerializer, AuthLoginSerializer class AuthViewSet(viewsets.ViewSet): @list_route(methods=['get']) def status(self, request): """ Get the login state (logged in user) --- response_serializer: UserSerializer """ generate_csrf_token_for_frontend(request) if request.user.is_anonymous(): serializer = UserSerializer() else: serializer = UserSerializer(request.user) return Response(serializer.data) def create(self, request, **kwargs): """ Log in --- request_serializer: AuthLoginSerializer response_serializer: UserSerializer """ serializer = AuthLoginSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): return Response(data=UserSerializer(request.user).data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) @list_route(methods=['POST']) def logout(self, request, **kwargs): logout(request) return Response(status = status.HTTP_200_OK)
Add renderware to generated apps
module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipRenderware extends Nodal.Renderware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipRenderware; })();
module.exports = (function() { "use strict"; const Nodal = require('nodal'); const zlib = require('zlib'); class GzipMiddleware extends Nodal.Middleware { exec(controller, data, callback) { let contentType = controller.getHeader('Content-Type', '').split(';')[0]; let acceptEncoding = controller._request.headers['accept-encoding'] || ''; let canCompress = !!{ 'text/plain': 1, 'text/html': 1, 'text/xml': 1, 'text/json': 1, 'text/javascript': 1, 'application/json': 1, 'application/xml': 1, 'application/javascript': 1, 'application/octet-stream': 1 }[contentType]; if (canCompress) { if (acceptEncoding.match(/\bgzip\b/)) { zlib.gzip(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'gzip'); callback(null, result); return; } callback(null, data); }); return true; } else if(acceptEncoding.match(/\bdeflate\b/)) { zlib.deflate(data, function(err, result) { if (!err) { controller.setHeader('Content-Encoding', 'deflate'); callback(null, result); return; } callback(null, data); }); return true; } } callback(null, data); return false; } } return GzipMiddleware; })();
[Client] Fix active link in menu when sub item is displayed
import React from 'react' import {Link, withRouter} from 'react-router-dom' import { Image, Menu } from 'semantic-ui-react' import logo from '../logo.svg' import './MainHeader.css' const MainHeader = ({location}) => { return ( <Menu fixed='top' inverted> <Menu.Item as='a' header> <Image size='mini' className='App-logo' src={logo} style={{ marginRight: '1.5em' }} /> JAMS </Menu.Item> <Menu.Item as={Link} to='/' active={/^\/$/.test(location.pathname)} > Home </Menu.Item> <Menu.Item as={Link} to='/dashboard' active={/^\/dashboard$/.test(location.pathname)} > Dashboard </Menu.Item> <Menu.Item as={Link} to='/session' active={/^\/session$/.test(location.pathname)} > Session </Menu.Item> <Menu.Item as={Link} to='/admin' active={/^\/admin/.test(location.pathname)} > Admin </Menu.Item> </Menu> ) } export default withRouter(MainHeader)
import React from 'react' import {Link, withRouter} from 'react-router-dom' import { Image, Menu } from 'semantic-ui-react' import logo from '../logo.svg' import './MainHeader.css' const MainHeader = ({location}) => { console.log('location', location) return ( <Menu fixed='top' inverted> <Menu.Item as='a' header> <Image size='mini' className='App-logo' src={logo} style={{ marginRight: '1.5em' }} /> JAMS </Menu.Item> <Menu.Item as={Link} to='/' active={/^\/$/.test(location.pathname)} > Home </Menu.Item> <Menu.Item as={Link} to='/dashboard' active={/^\/dashboard$/.test(location.pathname)} > Dashboard </Menu.Item> <Menu.Item as={Link} to='/session' active={/^\/session$/.test(location.pathname)} > Session </Menu.Item> <Menu.Item as={Link} to='/admin' active={/^\/admin$/.test(location.pathname)} > Admin </Menu.Item> </Menu> ) } export default withRouter(MainHeader)
Rename offset in body weight mapper with UTC
package org.openmhealth.shim.fitbit.mapper; import com.fasterxml.jackson.databind.JsonNode; import org.openmhealth.schema.domain.omh.BodyWeight; import org.openmhealth.schema.domain.omh.DataPoint; import org.openmhealth.schema.domain.omh.MassUnit; import org.openmhealth.schema.domain.omh.MassUnitValue; import java.time.*; import java.util.Optional; import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*; /** * Created by Chris Schaefbauer on 6/10/15. */ public class FitbitBodyWeightDataPointMapper extends FitbitDataPointMapper<BodyWeight>{ @Override protected Optional<DataPoint<BodyWeight>> asDataPoint(JsonNode node, int UTCOffsetInMilliseconds) { MassUnitValue bodyWeight = new MassUnitValue(MassUnit.KILOGRAM,asRequiredDouble(node,"weight")); BodyWeight.Builder builder = new BodyWeight.Builder(bodyWeight); Optional<LocalDateTime> dateTime = asOptionalLocalDateTime(node,"date","time"); if(dateTime.isPresent()){ OffsetDateTime offsetDateTime = OffsetDateTime.of(dateTime.get(), ZoneOffset.ofTotalSeconds(UTCOffsetInMilliseconds / 1000)); builder.setEffectiveTimeFrame(offsetDateTime); } Optional<Long> externalId = asOptionalLong(node, "logId"); BodyWeight measure = builder.build(); return Optional.of(newDataPoint(measure, externalId.orElse(null))); } @Override protected String getListNodeName() { return "weight"; } }
package org.openmhealth.shim.fitbit.mapper; import com.fasterxml.jackson.databind.JsonNode; import org.openmhealth.schema.domain.omh.BodyWeight; import org.openmhealth.schema.domain.omh.DataPoint; import org.openmhealth.schema.domain.omh.MassUnit; import org.openmhealth.schema.domain.omh.MassUnitValue; import java.time.*; import java.util.Optional; import static org.openmhealth.shim.common.mapper.JsonNodeMappingSupport.*; /** * Created by Chris Schaefbauer on 6/10/15. */ public class FitbitBodyWeightDataPointMapper extends FitbitDataPointMapper<BodyWeight>{ @Override protected Optional<DataPoint<BodyWeight>> asDataPoint(JsonNode node, int offsetInMilliseconds) { MassUnitValue bodyWeight = new MassUnitValue(MassUnit.KILOGRAM,asRequiredDouble(node,"weight")); BodyWeight.Builder builder = new BodyWeight.Builder(bodyWeight); Optional<LocalDateTime> dateTime = asOptionalLocalDateTime(node,"date","time"); if(dateTime.isPresent()){ OffsetDateTime offsetDateTime = OffsetDateTime.of(dateTime.get(), ZoneOffset.ofTotalSeconds(offsetInMilliseconds / 1000)); builder.setEffectiveTimeFrame(offsetDateTime); } Optional<Long> externalId = asOptionalLong(node, "logId"); BodyWeight measure = builder.build(); return Optional.of(newDataPoint(measure, externalId.orElse(null))); } @Override protected String getListNodeName() { return "weight"; } }
Fix building queries with more than one parameter
<?php namespace Keyteq\Keymedia\API; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Util\RequestSigner; use Keyteq\Keymedia\Util\RequestWrapper; class RestConnector { protected $config; protected $signer; protected $wrapper; public function __construct(Configuration $config) { $this->config = $config; } public function getResource($resourceName, $resourceId, $parameters = array()) { $path = "{$resourceName}/{$resourceId}.json"; $url = $this->buildUrl($path, $parameters); $request = new Request($this->config, $this->signer, $this->wrapper); $request->setMethod('GET')->setUrl($url); return $request->perform(); } public function getCollection($resourceName, $parameters = array()) { $path = "{$resourceName}.json"; $url = $this->buildUrl($path, $parameters); $request = new Request($this->config, new RequestSigner(), new RequestWrapper()); $request->setMethod('GET')->setUrl($url); return $request->perform(); } protected function buildUrl($path = '', $parameters = array()) { $rootUrl = $this->config->getApiUrl(); $url = "{$rootUrl}/{$path}"; if (!empty($parameters)) { $url .= '?' . http_build_query($parameters); } return $url; } }
<?php namespace Keyteq\Keymedia\API; use Keyteq\Keymedia\API\Configuration; use Keyteq\Keymedia\Util\RequestSigner; use Keyteq\Keymedia\Util\RequestWrapper; class RestConnector { protected $config; protected $signer; protected $wrapper; public function __construct(Configuration $config) { $this->config = $config; } public function getResource($resourceName, $resourceId, $parameters = array()) { $path = "{$resourceName}/{$resourceId}.json"; $url = $this->buildUrl($path, $parameters); $request = new Request($this->config, $this->signer, $this->wrapper); $request->setMethod('GET')->setUrl($url); return $request->perform(); } public function getCollection($resourceName, $parameters = array()) { $path = "{$resourceName}.json"; $url = $this->buildUrl($path, $parameters); $request = new Request($this->config, new RequestSigner(), new RequestWrapper()); $request->setMethod('GET')->setUrl($url); return $request->perform(); } protected function buildUrl($path = '', $parameters = array()) { $rootUrl = $this->config->getApiUrl(); $url = "{$rootUrl}/{$path}"; if (!empty($parameters)) { $url .= '?'; foreach ($parameters as $k => $v) { $url .= $k . '=' . $v; } } return $url; } }
Add bind auto method (bind without key)
<?php namespace DB\Driver; /** * Interface for all database driver. Any database driver must implement * this class. * * @package DB\Driver */ interface IDriver { /** * Connect to selected database host * * @param string $host Database host name * @param string $user Username for database host * @param string $password Password for database host */ public function connect($host, $user, $password); /** * Connect to database in the host. * * @param string $name Database name * @param bool $forceCreate If set to true, will create database if * database is not exists */ public function database($name, $forceCreate=false); /** * Perform Query based on the driver. * * @param string $sql SQL that need to be run * * @return \DB\Result Database query result */ public function query($sql); /** * Perform database query by binding the data to query syntax. * * @param string $sql SQL * @param array $data Data that will be binded to query * * @return \DB\Result Database query result */ public function bind($sql, $data=[]); public function bindAuto($sql, $data=array()); } ?>
<?php namespace DB\Driver; /** * Interface for all database driver. Any database driver must implement * this class. * * @package DB\Driver */ interface IDriver { /** * Connect to selected database host * * @param string $host Database host name * @param string $user Username for database host * @param string $password Password for database host */ public function connect($host, $user, $password); /** * Connect to database in the host. * * @param string $name Database name * @param bool $forceCreate If set to true, will create database if * database is not exists */ public function database($name, $forceCreate=false); /** * Perform Query based on the driver. * * @param string $sql SQL that need to be run * * @return \DB\Result Database query result */ public function query($sql); /** * Perform database query by binding the data to query syntax. * * @param string $sql SQL * @param array $data Data that will be binded to query * * @return \DB\Result Database query result */ public function bind($sql, $data=[]); } ?>
[drush] Improve drush command, make stand alone command
<?php /** * @file * Contains \Drupal\Console\Command\DrushCommand. */ namespace Drupal\Console\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Drupal\Console\Command\Command; class DrushCommand extends Command { /** * {@inheritdoc} */ protected function configure() { $this ->setName('drush') ->setDescription($this->trans('commands.drush.description')) ->addArgument( 'args', InputArgument::IS_ARRAY, $this->trans('commands.drush.arguments.args') ) ->setHelp($this->trans('commands.drush.help')); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $args = ''; if ($arguments = $input->getArgument('args')) { $args .= ' '.implode(' ', $arguments); $c_args = preg_replace('/[^a-z0-9-= ]/i', '', $args); } if (`which drush`) { system('drush'.$c_args); } else { $this->getMessageHelper()->addErrorMessage( $this->trans('commands.drush.message.not_found') ); } } }
<?php /** * @file * Contains \Drupal\Console\Command\DrushCommand. */ namespace Drupal\Console\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class DrushCommand extends ContainerAwareCommand { /** * {@inheritdoc} */ protected function configure() { $this ->setName('drush') ->setDescription($this->trans('commands.drush.description')) ->addArgument('args', InputArgument::IS_ARRAY, $this->trans('commands.drush.arguments.args')) ->setHelp($this->trans('commands.drush.help')); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $args = ''; if ($arguments = $input->getArgument('args')) { $args .= ' '.implode(' ', $arguments); $c_args = preg_replace('/[^a-z0-9-= ]/i', '', $args); } if (`which drush`) { system('drush'.$c_args); } else { $output->write('<error>'.$this->trans('commands.drush.message.not_found').'</error>'); } } }
BB-1413: Cover validation by unit tests - fix spaces
<?php namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity; use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper; class EnumValueValidator extends ConstraintValidator { /** * {@inheritdoc} */ public function validate($entity, Constraint $constraint) { if ($entity instanceof EnumValueEntity) { $entity = $entity->toArray(); } if (!is_array($entity)) { throw new UnexpectedTypeException( $entity, 'Oro\Bundle\EntityExtendBundle\Model\EnumValue|array' ); } if (!empty($entity['id']) || empty($entity['label'])) { return; } $valueId = ExtendHelper::buildEnumValueId($entity['label'], false); if (empty($valueId)) { $this->context ->buildViolation($constraint->message, ['{{ value }}' => $entity['label']]) ->atPath('[label]') ->addViolation() ; } } }
<?php namespace Oro\Bundle\EntityExtendBundle\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Oro\Bundle\EntityExtendBundle\Model\EnumValue as EnumValueEntity; use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper; class EnumValueValidator extends ConstraintValidator { /** * {@inheritdoc} */ public function validate($entity, Constraint $constraint) { if ($entity instanceof EnumValueEntity) { $entity = $entity->toArray(); } if (!is_array($entity)) { throw new UnexpectedTypeException( $entity, 'Oro\Bundle\EntityExtendBundle\Model\EnumValue|array' ); } if (!empty($entity['id']) || empty($entity['label'])) { return; } $valueId = ExtendHelper::buildEnumValueId($entity['label'], false); if (empty($valueId)) { $this->context ->buildViolation($constraint->message, ['{{ value }}' => $entity['label']]) ->atPath('[label]') ->addViolation() ; } } }
Fix problem with detecting step lines with failed steps
<?php namespace Tests\Concerns; use PHPUnit\Framework\Assert; class ArtisanResult { private $output; private $status; private $parameters; public function __construct($parameters, $output, $status) { $this->output = $output; $this->status = $status; $this->parameters = $parameters; } public function assertStatus($expected) { Assert::assertEquals($expected, $this->status); } public function assertStepOutput($expectedLines) { foreach ($this->stepLines() as $index => $actualLine) { Assert::assertEquals($expectedLines[$index], $actualLine); } } public function dump() { return tap($this, function () { dump("Status: {$this->status}"); dump("Output:\n{$this->output}"); }); } public function dumpIfFailed() { return $this->status === 0 ? $this : $this->dump(); } private function stepLines() { foreach (explode("\n", $this->output) as $index => $actualLine) { if (substr($actualLine, 0, 1) !== "[") { break; } yield $index => $actualLine; } } }
<?php namespace Tests\Concerns; use PHPUnit\Framework\Assert; class ArtisanResult { private $output; private $status; private $parameters; public function __construct($parameters, $output, $status) { $this->output = $output; $this->status = $status; $this->parameters = $parameters; } public function assertStatus($expected) { Assert::assertEquals($expected, $this->status); } public function assertStepOutput($expectedLines) { foreach ($this->stepLines() as $index => $actualLine) { Assert::assertEquals($expectedLines[$index], $actualLine); } } public function dump() { return tap($this, function () { dump("Status: {$this->status}"); dump("Output:\n{$this->output}"); }); } public function dumpIfFailed() { return $this->status === 0 ? $this : $this->dump(); } private function stepLines() { foreach (explode("\n", $this->output) as $index => $actualLine) { if ($actualLine === "" || substr($actualLine, 0, 7) === "PHPUnit") { break; } yield $index => $actualLine; } } }
Add a future repsonse class for handle dispatcher for asynchronous command
<?php namespace M6Web\Bundle\CassandraBundle\Cassandra; use Cassandra\Future; use M6Web\Bundle\CassandraBundle\EventDispatcher\CassandraEvent; /** * Class FutureResponse * * Handle future response for dispatching event when request is complete */ class FutureResponse implements Future { /** * @var EventDispatcher */ protected $eventDispatcher; /** * @var CassandraEvent */ protected $event; /** * @var Futurer */ protected $future; /** * @param Future $future * @param CassandraEvent $event * @param EventDispatcher $eventDispatcher */ public function __construct(Future $future, CassandraEvent $event, $eventDispatcher) { $this->future = $future; $this->event = $event; $this->eventDispatcher = $eventDispatcher; } /** * Waits for a given future resource to resolve and throws errors if any. * * @param int|null $timeout * * @throws \Cassandra\Exception\InvalidArgumentException * @throws \Cassandra\Exception\TimeoutException * * @return mixed a value that the future has been resolved with */ public function get($timeout = null) { $return = $this->future->get($timeout); $this->event->setExecutionStop(); $this->eventDispatcher->dispatch(CassandraEvent::EVENT_NAME, $this->event); return $return; } }
<?php namespace M6Web\Bundle\CassandraBundle\Cassandra; use Cassandra\Future; use M6Web\Bundle\CassandraBundle\EventDispatcher\CassandraEvent; /** * Class FutureResponse * * Handle future response for dispatching event when request is complete */ class FutureResponse implements Future { /** * @var EventDispatcher */ protected $eventDispatcher; /** * @var CassandraEvent */ protected $event; /** * @var Futurer */ protected $future; /** * @param Future $future * @param CassandraEvent $event * @param EventDispatcher $eventDispatcher */ public function __construct(Future $future, CassandraEvent $event, $eventDispatcher) { $this->future = $future; $this->event = $event; $this->eventDispatcher = $eventDispatcher; } /** * Waits for a given future resource to resolve and throws errors if any. * * @param int|null $timeout * * @throws \Cassandra\Exception\InvalidArgumentException * @throws \Cassandra\Exception\TimeoutException * * @return mixed a value that the future has been resolved with */ public function get($timeout = null) { $return = $this->future->get($timeout); $this->event->setExecutionStop(); $this->eventDispatcher->dispatch('m6web.cassandra', $this->event); return $return; } }
Make the view List only remove Create
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListCreateAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListCreateAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
Implement a very basic http server
package net.zephyrizing.http_server; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HttpServer { public static void main(String[] args) throws Exception { int portNumber; if (args.length == 1) { portNumber = Integer.parseInt(args[0]); } else { portNumber = 80; } System.err.println("Starting server on port " + portNumber); try (ServerSocket listenSocket = new ServerSocket(portNumber)) { System.err.println("Listening for clients..."); try (Socket socket = listenSocket.accept(); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in))) { System.err.println("Connected to client."); String request = in.readLine(); String[] params = request.split(" "); assert(params.length == 3); String method = params[0]; String path = params[1]; String protocolVersion = params[2]; System.out.format("Client requested to %s file %s over %s.\n", method, path, protocolVersion); out.format("%s 200 OK\r\n", protocolVersion); } } } }
package net.zephyrizing.http_server; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class HttpServer { public static void main(String[] args) throws Exception { int portNumber = Integer.parseInt(args[0]); System.err.println("Starting server on port " + args[0]); try (ServerSocket listenSocket = new ServerSocket(portNumber)) { System.err.println("Listening for clients..."); try (Socket socket = listenSocket.accept(); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in))) { System.err.println("Connected to client. Proceeding to echo..."); String clientInput; while ((clientInput = in.readLine()) != null) { System.out.println("Got: "+clientInput); out.println("Echo: "+clientInput); } } } } }
janitoring: Use print as a statement - Let's be Python 3 compatible. Signed-off-by: mr.Shu <[email protected]>
import wikipedia import sys import random import re import nltk.data def process_file(f): names = {} with open(f) as file: for line in file: l = line.strip().split('\t') if len(l) != 2: continue (k, v) = l names[k] = v return names REGEX_IN_DATE = r".*in\s*(?:[^ ,]*?)?\s*\d\d\d\d.*" def process_page(id): page = wikipedia.page(pageid=id) in_date_regex = re.compile(REGEX_IN_DATE, re.IGNORECASE) tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') out = set() for line in tokenizer.tokenize(page.content, realign_boundaries=True): if '\n' in line: line = line.split('\n') else: line = [line] for l in line: if in_date_regex.match(l): out.add(l) return out if __name__ == '__main__': for file in sys.argv[1:]: names = process_file(file) if len(names) > 10: sample = random.sample(names, 10) else: sample = names for name in sample: pageid = names[name] print "Results of processing {} ({})".format(name, pageid) for achievement in process_page(pageid): print ("\t", achievement.encode('utf-8'))
import wikipedia import sys import random import re import nltk.data def process_file(f): names = {} with open(f) as file: for line in file: l = line.strip().split('\t') if len(l) != 2: continue (k, v) = l names[k] = v return names REGEX_IN_DATE = r".*in\s*(?:[^ ,]*?)?\s*\d\d\d\d.*" def process_page(id): page = wikipedia.page(pageid=id) in_date_regex = re.compile(REGEX_IN_DATE, re.IGNORECASE) tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') out = set() for line in tokenizer.tokenize(page.content, realign_boundaries=True): if '\n' in line: line = line.split('\n') else: line = [line] for l in line: if in_date_regex.match(l): out.add(l) return out if __name__ == '__main__': for file in sys.argv[1:]: names = process_file(file) if len(names) > 10: sample = random.sample(names, 10) else: sample = names for name in sample: pageid = names[name] print "Results of processing {} ({})".format(name, pageid) for achievement in process_page(pageid): print "\t", achievement.encode('utf-8')
Exclude 'keep-alive' as a proxied response header.
package com.netflix.zuul.util; import com.netflix.client.http.HttpResponse; import com.netflix.zuul.context.HttpRequestMessage; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * User: [email protected] * Date: 6/8/15 * Time: 11:50 AM */ public class ProxyUtils { public static boolean isValidRequestHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "content-length": case "transfer-encoding": return false; default: return true; } } public static boolean isValidResponseHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "keep-alive": case "content-length": case "server": case "transfer-encoding": return false; default: return true; } } @RunWith(MockitoJUnitRunner.class) public static class TestUnit { @Mock HttpResponse proxyResp; @Mock HttpRequestMessage request; @Test public void testIsValidResponseHeader() { Assert.assertTrue(isValidResponseHeader("test")); Assert.assertFalse(isValidResponseHeader("content-length")); Assert.assertFalse(isValidResponseHeader("connection")); } } }
package com.netflix.zuul.util; import com.netflix.client.http.HttpResponse; import com.netflix.zuul.context.HttpRequestMessage; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * User: [email protected] * Date: 6/8/15 * Time: 11:50 AM */ public class ProxyUtils { public static boolean isValidRequestHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "content-length": case "transfer-encoding": return false; default: return true; } } public static boolean isValidResponseHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "content-length": case "server": case "transfer-encoding": return false; default: return true; } } @RunWith(MockitoJUnitRunner.class) public static class TestUnit { @Mock HttpResponse proxyResp; @Mock HttpRequestMessage request; @Test public void testIsValidResponseHeader() { Assert.assertTrue(isValidResponseHeader("test")); Assert.assertFalse(isValidResponseHeader("content-length")); Assert.assertFalse(isValidResponseHeader("connection")); } } }
Add a default message to ensure that logs are written
package com.volkhart.feedback.utils; import android.util.Log; import java.io.PrintWriter; import java.util.Collections; import java.util.LinkedList; import java.util.List; import timber.log.Timber; public final class FeedbackTree extends Timber.DebugTree { public static final FeedbackTree INSTANCE = new FeedbackTree(); public static int MESSAGES_TO_STORE = 100; private final List<String> logMessages = Collections.synchronizedList(new LinkedList<String>()); private FeedbackTree() { } void writeToStream(PrintWriter writer) { synchronized (logMessages) { for (String message : logMessages) { writer.println(message); } } // We add a line at the end to make sure the file gets create no matter what writer.println(); } @Override protected void log(int priority, String tag, String message, Throwable t) { String displayLevel; switch (priority) { case Log.INFO: displayLevel = "I"; break; case Log.WARN: displayLevel = "W"; break; case Log.ERROR: displayLevel = "E"; break; default: return; } String logMessage = String.format("%22s %s %s", tag, displayLevel, // Indent newlines to match the original indentation. message.replaceAll("\\n", "\n ")); synchronized (logMessages) { logMessages.add(logMessage); if (logMessages.size() > MESSAGES_TO_STORE) { logMessages.remove(0); } } } }
package com.volkhart.feedback.utils; import android.util.Log; import java.io.PrintWriter; import java.util.Collections; import java.util.LinkedList; import java.util.List; import timber.log.Timber; public final class FeedbackTree extends Timber.DebugTree { public static final FeedbackTree INSTANCE = new FeedbackTree(); public static int MESSAGES_TO_STORE = 100; private final List<String> logMessages = Collections.synchronizedList(new LinkedList<String>()); private FeedbackTree() { } void writeToStream(PrintWriter writer) { synchronized (logMessages) { for (String message : logMessages) { writer.println(message); } } } @Override protected void log(int priority, String tag, String message, Throwable t) { String displayLevel; switch (priority) { case Log.INFO: displayLevel = "I"; break; case Log.WARN: displayLevel = "W"; break; case Log.ERROR: displayLevel = "E"; break; default: return; } String logMessage = String.format("%22s %s %s", tag, displayLevel, // Indent newlines to match the original indentation. message.replaceAll("\\n", "\n ")); synchronized (logMessages) { logMessages.add(logMessage); if (logMessages.size() > MESSAGES_TO_STORE) { logMessages.remove(0); } } } }
Fix constructor test, since constructor does not append / at the end
import os, sys sys.path.append(os.path.abspath('..')) import unittest from mock import patch from pynexus import api_client class NexusTest(unittest.TestCase): def test_constructor_appends_base(self): n = api_client.ApiClient('http://test.com', 'testuser', 'testpwd') self.assertEquals(n.uri, 'http://test.com/nexus/service/local') @patch.object(api_client.requests, 'get') def test_get_users_return_list_with_just_anonymous_user(self, mock_get): mock_output = u'{"data":[{"resourceURI":"http://test.com/nexus/' \ 'service/local/users/anonymous","userId":"anonymous",' \ '"firstName":"Nexus","lastName":"Anonymous User",' \ '"status":"active","email":"[email protected]"' \ ',"roles":["anonymous","repository-any-read"]}' mock_get.return_value = mock_output n = api_client.ApiClient('http://test.com', 'testuser', 'testpwd') result = n.get_users() self.assertEqual(result, mock_output) def main(): unittest.main() if __name__ == '__main__': main()
import os, sys sys.path.append(os.path.abspath('..')) import unittest from mock import patch from pynexus import api_client class NexusTest(unittest.TestCase): def test_constructor_appends_base(self): n = api_client.ApiClient('http://test.com', 'testuser', 'testpwd') self.assertEquals(n.uri, 'http://test.com/nexus/service/local/') @patch.object(api_client.requests, 'get') def test_get_users_return_list_with_just_anonymous_user(self, mock_get): mock_output = u'{"data":[{"resourceURI":"http://test.com/nexus/' \ 'service/local/users/anonymous","userId":"anonymous",' \ '"firstName":"Nexus","lastName":"Anonymous User",' \ '"status":"active","email":"[email protected]"' \ ',"roles":["anonymous","repository-any-read"]}' mock_get.return_value = mock_output n = api_client.ApiClient('http://test.com', 'testuser', 'testpwd') result = n.get_users() self.assertEqual(result, mock_output) def main(): unittest.main() if __name__ == '__main__': main()
[ECS] Add shortcut for config file
<?php declare(strict_types=1); namespace Symplify\EasyCodingStandard\Console; use Jean85\PrettyVersions; use Symfony\Component\Console\Application as SymfonyApplication; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; final class Application extends SymfonyApplication { public function __construct() { $version = PrettyVersions::getVersion('symplify/easy-coding-standard'); parent::__construct('EasyCodingStandard', $version->getPrettyVersion()); } protected function getDefaultInputDefinition(): InputDefinition { $inputDefinition = parent::getDefaultInputDefinition(); $this->removeUnusedOptions($inputDefinition); $this->addExtraOptions($inputDefinition); return $inputDefinition; } private function removeUnusedOptions(InputDefinition $inputDefinition): void { $options = $inputDefinition->getOptions(); unset($options['quiet'], $options['version'], $options['no-interaction']); $inputDefinition->setOptions($options); } private function addExtraOptions(InputDefinition $inputDefinition): void { $inputDefinition->addOption(new InputOption( 'config', 'c', InputOption::VALUE_REQUIRED, 'Path to config file.', 'easy-coding-standard.(yml|yaml)' )); $inputDefinition->addOption(new InputOption( 'level', null, InputOption::VALUE_REQUIRED, 'Finds config by shortcut name.' )); } }
<?php declare(strict_types=1); namespace Symplify\EasyCodingStandard\Console; use Jean85\PrettyVersions; use Symfony\Component\Console\Application as SymfonyApplication; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; final class Application extends SymfonyApplication { public function __construct() { $version = PrettyVersions::getVersion('symplify/easy-coding-standard'); parent::__construct('EasyCodingStandard', $version->getPrettyVersion()); } protected function getDefaultInputDefinition(): InputDefinition { $inputDefinition = parent::getDefaultInputDefinition(); $this->removeUnusedOptions($inputDefinition); $this->addExtraOptions($inputDefinition); return $inputDefinition; } private function removeUnusedOptions(InputDefinition $inputDefinition): void { $options = $inputDefinition->getOptions(); unset($options['quiet'], $options['version'], $options['no-interaction']); $inputDefinition->setOptions($options); } private function addExtraOptions(InputDefinition $inputDefinition): void { $inputDefinition->addOption(new InputOption( 'config', null, InputOption::VALUE_REQUIRED, 'Path to config file.', 'easy-coding-standard.(yml|yaml)' )); $inputDefinition->addOption(new InputOption( 'level', null, InputOption::VALUE_REQUIRED, 'Finds config by shortcut name.' )); } }
Fix broken import of socket errors
from sockets.socket_closed_exception import SocketClosedException from sockets.stream_socket import StreamSocket import socket from groundstation import settings import groundstation.logger log = groundstation.logger.getLogger(__name__) class PeerSocket(StreamSocket): """Wrapper for a peer who just connected, or one we've connected to Since the communication protocol should be implicitly bidirectional, the factory methods should be the only instanciation methods""" def __init__(self, conn, peer): self._sock = conn super(PeerSocket, self).__init__() self.peer = peer @classmethod def from_accept(klass, args): return klass(*args) @classmethod def from_connect(klass, args): return klass(*args) def __repr__(self): return "<%s: from %s>" % (self.__class__, self.peer) # Wrap StreamSocket's send and recv in exception handling def send(self, *args, **kwargs): try: return super(PeerSocket, self).send(*args, **kwargs) except socket.error as e: raise PeerSocketClosedException(e) def recv(self, *args, **kwargs): try: return super(PeerSocket, self).send(*args, **kwargs) except socket.error as e: raise PeerSocketClosedException(e) class PeerSocketClosedException(SocketClosedException): """Raised when a peer closes their socket""" pass
from sockets.socket_closed_exception import SocketClosedException from sockets.stream_socket import StreamSocket import socket.error from groundstation import settings import groundstation.logger log = groundstation.logger.getLogger(__name__) class PeerSocket(StreamSocket): """Wrapper for a peer who just connected, or one we've connected to Since the communication protocol should be implicitly bidirectional, the factory methods should be the only instanciation methods""" def __init__(self, conn, peer): self._sock = conn super(PeerSocket, self).__init__() self.peer = peer @classmethod def from_accept(klass, args): return klass(*args) @classmethod def from_connect(klass, args): return klass(*args) def __repr__(self): return "<%s: from %s>" % (self.__class__, self.peer) # Wrap StreamSocket's send and recv in exception handling def send(self, *args, **kwargs): try: return super(PeerSocket, self).send(*args, **kwargs) except socket.error as e: raise PeerSocketClosedException(e) def recv(self, *args, **kwargs): try: return super(PeerSocket, self).send(*args, **kwargs) except socket.error as e: raise PeerSocketClosedException(e) class PeerSocketClosedException(SocketClosedException): """Raised when a peer closes their socket""" pass
Add lint and reformat target. This is part of the ground work to have a consistent style to the template JSON documents. Two targets are defined. * Lint - verify all JSON templates follow the approved style. * Reformat - modify all JSON templates to follow the approved style. The lint target will be used to gate the build in a future commit. If a PR does not meet the approved style it will fail the build The reformat target is for developers. Developers should execute this target before sending a PR to match the approved style.
var grunt = require('grunt'); require('load-grunt-tasks')(grunt); var files = ['test/*.js']; var templates = ['**/*.json']; grunt.initConfig({ mochacli: { options: { reporter: 'spec', bail: false }, all: files }, jshint: { files: files, options: { jshintrc: '.jshintrc' } }, jscs: { files: { src: files }, options: { config: '.jscsrc', esnext: true } }, jsbeautifier: { test: { files: { src: files }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, lint: { files: { src: templates }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, reformat: { files: { src: templates }, options: { mode: 'VERIFY_AND_WRITE', config: '.beautifyrc' } }, write: { files: { src: files }, options: { config: '.beautifyrc' } } } }); grunt.registerTask('test', ['jshint', 'jscs', 'jsbeautifier:test', 'jsbeautifier:write', 'mochacli']);
var grunt = require('grunt'); require('load-grunt-tasks')(grunt); var files = ['test/*.js']; grunt.initConfig({ mochacli: { options: { reporter: 'spec', bail: false }, all: files }, jshint: { files: files, options: { jshintrc: '.jshintrc' } }, jscs: { files: { src: files }, options: { config: '.jscsrc', esnext: true } }, jsbeautifier: { test: { files: { src: files }, options: { mode: 'VERIFY_ONLY', config: '.beautifyrc' } }, write: { files: { src: files }, options: { config: '.beautifyrc' } } } }); grunt.registerTask('test', ['jshint', 'jscs', 'jsbeautifier', 'mochacli']);
Add test gruntfile to jshint checks
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/**/*.js", "test/*.js", "test/enmasse/Gruntfile.js" ] }, jscs: { src: "<%= jshint.all %>", options: { preset: "jquery" } }, nodeunit: { methods: "test/methods.js", enmasse: "test/enmasse.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "test", "nodeunit" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/**/*.js", "test/*.js" ] }, jscs: { src: "<%= jshint.all %>", options: { preset: "jquery" } }, nodeunit: { methods: "test/methods.js", enmasse: "test/enmasse.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "test", "nodeunit" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
Append .jpg to screenshot filename
(function() { 'use strict'; angular.module('chaise.viewer') .controller('OSDController', ['image', '$window', function OSDController(image, $window) { var vm = this; var iframe = $window.frames[0]; var origin = $window.location.origin; vm.image = image; vm.downloadView = downloadView; vm.zoomInView = zoomInView; vm.zoomOutView = zoomOutView; vm.homeView = homeView; function downloadView() { var filename = vm.image.entity.data.slide_id; if (!filename) { filename = 'image'; } iframe.postMessage({ messageType: 'downloadView', content: filename + '.jpg' }, origin); } function zoomInView() { iframe.postMessage({messageType: 'zoomInView'}, origin); } function zoomOutView() { iframe.postMessage({messageType: 'zoomOutView'}, origin); } function homeView() { iframe.postMessage({messageType: 'homeView'}, origin); } }]); })();
(function() { 'use strict'; angular.module('chaise.viewer') .controller('OSDController', ['image', '$window', function OSDController(image, $window) { var vm = this; var iframe = $window.frames[0]; var origin = $window.location.origin; vm.image = image; vm.downloadView = downloadView; vm.zoomInView = zoomInView; vm.zoomOutView = zoomOutView; vm.homeView = homeView; function downloadView() { var filename = vm.image.entity.data.slide_id; if (!filename) { filename = 'image'; } iframe.postMessage({ messageType: 'downloadView', content: filename }, origin); } function zoomInView() { iframe.postMessage({messageType: 'zoomInView'}, origin); } function zoomOutView() { iframe.postMessage({messageType: 'zoomOutView'}, origin); } function homeView() { iframe.postMessage({messageType: 'homeView'}, origin); } }]); })();
Change how GUI and logger is created. Initialize logger after we get console parameters and only then initialize logger.
package com.fatico.winthing; import com.fatico.winthing.gui.WindowGui; import com.fatico.winthing.messaging.Engine; import com.google.inject.Guice; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { private static final Application app = new Application(); private boolean debug = false; private WindowGui gui; private Logger logger; private void parseArgs(String[] args) { for (String arg : args) { if (arg.equals("-debug")) { debug = true; } } } public static boolean debug() { return app.debug; } public static WindowGui getApp() { return app.gui; } public static void quit() { app.logger.info("Application terminated."); System.exit(0); } public static void main(final String[] args) { try { app.parseArgs(args); app.logger = LoggerFactory.getLogger(Application.class); app.gui = new WindowGui(); app.gui.initialize(); final Injector injector = Guice.createInjector(new ApplicationModule()); final Engine engine = injector.getInstance(Engine.class); engine.run(); } catch (final Throwable throwable) { app.logger.error("Critical error.", throwable); System.exit(1); } } }
package com.fatico.winthing; import com.fatico.winthing.gui.WindowGui; import com.fatico.winthing.messaging.Engine; import com.google.inject.Guice; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { private boolean debug = false; private static Application app = new Application(); private static final Logger logger = LoggerFactory.getLogger(Application.class); private void parseArgs(String[] args) { for (String arg : args) { if (arg.equals("-debug")) { debug = true; } } } public static boolean debug() { return app.debug; } public static void quit() { logger.info("Application terminated."); System.exit(0); } public static void main(final String[] args) { try { app.parseArgs(args); WindowGui gui = WindowGui.getInstance(); gui.tray(); final Injector injector = Guice.createInjector(new ApplicationModule()); final Engine engine = injector.getInstance(Engine.class); engine.run(); } catch (final Throwable throwable) { logger.error("Critical error.", throwable); System.exit(1); } } }
Update edit form for StockItem - Disallow direct quantity editing (must perform stocktake) - Add notes field to allow editing
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'batch', 'status', 'notes' ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django import forms from InvenTree.forms import HelperForm from .models import StockLocation, StockItem class EditStockLocationForm(HelperForm): class Meta: model = StockLocation fields = [ 'name', 'parent', 'description' ] class CreateStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'part', 'supplier_part', 'location', 'belongs_to', 'serial', 'batch', 'quantity', 'status', # 'customer', 'URL', ] class MoveStockItemForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'location', ] class StocktakeForm(forms.ModelForm): class Meta: model = StockItem fields = [ 'quantity', ] class EditStockItemForm(HelperForm): class Meta: model = StockItem fields = [ 'quantity', 'batch', 'status', ]
Add any/every, and optimize some functions (knowing it's empty string)
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; @Ignore @Ceylon(major = 1) class StringOfNone extends String implements None<Character> { static StringOfNone instance = new StringOfNone(); private StringOfNone() { super(""); } @Override public long getSize() { return 0; } @Override public boolean getEmpty() { return true; } @Override public Character getFirst() { return null; } @Override @Ignore public Iterable<? extends Character> getSequence() { return Iterable$impl._getSequence(this); } @Override @Ignore public Character find(Callable<? extends Boolean> f) { return Iterable$impl._find(this, f); } @Override @Ignore public Iterable<? extends Character> sorted(Callable<? extends Comparison> f) { return this; } @Override @Ignore public <Result> Iterable<Result> map(Callable<? extends Result> f) { return new MapIterable<Character, Result>(this, f); } @Override @Ignore public Iterable<? extends Character> filter(Callable<? extends Boolean> f) { return this; } @Override @Ignore public <Result> Result fold(Result ini, Callable<? extends Result> f) { return ini; } @Override @Ignore public boolean any(Callable<? extends Boolean> f) { return false; } @Override @Ignore public boolean every(Callable<? extends Boolean> f) { return false; } }
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Ignore; @Ignore @Ceylon(major = 1) class StringOfNone extends String implements None<Character> { static StringOfNone instance = new StringOfNone(); private StringOfNone() { super(""); } @Override public long getSize() { return 0; } @Override public boolean getEmpty() { return true; } @Override public Character getFirst() { return null; } @Override @Ignore public Iterable<? extends Character> getSequence() { return Iterable$impl._getSequence(this); } @Override @Ignore public Character find(Callable<? extends Boolean> f) { return Iterable$impl._find(this, f); } @Override @Ignore public Iterable<? extends Character> sorted(Callable<? extends Comparison> f) { return Iterable$impl._sorted(this, f); } @Override @Ignore public <Result> Iterable<Result> map(Callable<? extends Result> f) { return new MapIterable<Character, Result>(this, f); } @Override @Ignore public Iterable<? extends Character> filter(Callable<? extends Boolean> f) { return new FilterIterable<Character>(this, f); } @Override @Ignore public <Result> Result fold(Result ini, Callable<? extends Result> f) { return Iterable$impl._fold(this, ini, f); } }
Add ResponseInterface return type to request methods
<?php namespace Jsor\HalClient; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\UriInterface; interface HalClientInterface { /** * @return UriInterface */ public function getRootUrl(); /** * @param string * @return string[] */ public function getHeader($name); /** * @param string * @param string|string[] * @return HalClientInterface */ public function withHeader($name, $value); /** * @param array * @return HalResource|ResponseInterface */ public function root(array $options = []); /** * @param string|UriInterface * @param array * @return HalResource|ResponseInterface */ public function get($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource|ResponseInterface */ public function post($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource|ResponseInterface */ public function put($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource|ResponseInterface */ public function delete($uri, array $options = []); /** * @param string * @param string|UriInterface * @param array * @return HalResource|ResponseInterface */ public function request($method, $uri, array $options = []); }
<?php namespace Jsor\HalClient; use Psr\Http\Message\UriInterface; interface HalClientInterface { /** * @return UriInterface */ public function getRootUrl(); /** * @param string * @return string[] */ public function getHeader($name); /** * @param string * @param string|string[] * @return HalClientInterface */ public function withHeader($name, $value); /** * @param array * @return HalResource */ public function root(array $options = []); /** * @param string|UriInterface * @param array * @return HalResource */ public function get($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource */ public function post($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource */ public function put($uri, array $options = []); /** * @param string|UriInterface * @param array * @return HalResource */ public function delete($uri, array $options = []); /** * @param string * @param string|UriInterface * @param array * @return HalResource */ public function request($method, $uri, array $options = []); }
Remove duplicate trove classifier for Python Alphabetize list to help catch potential future duplication.
#!/usr/bin/env python import os from setuptools import setup def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as fp: return fp.read() setup( name='django-decorator-include', version='1.3', license='BSD', description='Include Django URL patterns with decorators.', long_description=read('README.rst'), author='Jeff Kistler', author_email='[email protected]', url='https://github.com/twidi/django-decorator-include/', py_modules=['decorator_include'], install_requires=['Django>=1.8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP', ] )
#!/usr/bin/env python import os from setuptools import setup def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as fp: return fp.read() setup( name='django-decorator-include', version='1.3', license='BSD', description='Include Django URL patterns with decorators.', long_description=read('README.rst'), author='Jeff Kistler', author_email='[email protected]', url='https://github.com/twidi/django-decorator-include/', py_modules=['decorator_include'], install_requires=['Django>=1.8'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.11', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] )
Fix JS error preventing newly created dictionary items from opening automatically (cherry picked from commit 59f90bd08be677817133584fc877f4a53a349359)
/** * @ngdoc controller * @name Umbraco.Editors.Dictionary.CreateController * @function * * @description * The controller for creating dictionary items */ function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) { var vm = this; vm.itemKey = ""; vm.createItem = createItem; function createItem() { if (formHelper.submitForm({ scope: $scope, formCtrl: $scope.createDictionaryForm })) { var node = $scope.currentNode; dictionaryResource.create(node.id, vm.itemKey).then(function (data) { navigationService.hideMenu(); // set new item as active in tree var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true }); // reset form state formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm }); // navigate to edit view var currentSection = appState.getSectionState("currentSection"); $location.path("/" + currentSection + "/dictionary/edit/" + data); }, function (err) { formHelper.resetForm({ scope: $scope, formCtrl: $scope.createDictionaryForm, hasErrors: true }); if (err.data && err.data.message) { notificationsService.error(err.data.message); navigationService.hideMenu(); } }); } } } angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
/** * @ngdoc controller * @name Umbraco.Editors.Dictionary.CreateController * @function * * @description * The controller for creating dictionary items */ function DictionaryCreateController($scope, $location, dictionaryResource, navigationService, notificationsService, formHelper, appState) { var vm = this; vm.itemKey = ""; vm.createItem = createItem; function createItem() { if (formHelper.submitForm({ scope: $scope, formCtrl: this.createDictionaryForm })) { var node = $scope.currentNode; dictionaryResource.create(node.id, vm.itemKey).then(function (data) { navigationService.hideMenu(); // set new item as active in tree var currPath = node.path ? node.path : "-1"; navigationService.syncTree({ tree: "dictionary", path: currPath + "," + data, forceReload: true, activate: true }); // reset form state formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm }); // navigate to edit view var currentSection = appState.getSectionState("currentSection"); $location.path("/" + currentSection + "/dictionary/edit/" + data); }, function (err) { formHelper.resetForm({ scope: $scope, formCtrl: this.createDictionaryForm, hasErrors: true }); if (err.data && err.data.message) { notificationsService.error(err.data.message); navigationService.hideMenu(); } }); } } } angular.module("umbraco").controller("Umbraco.Editors.Dictionary.CreateController", DictionaryCreateController);
Update class name validator implementation.
<?php namespace PhpSpec\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class DescribeCommand extends Command { public function __construct() { parent::__construct('describe'); $this->setDefinition(array( new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'), )); } protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getApplication()->getContainer(); $container->configure(); $classname = $input->getArgument('class'); $pattern = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/'; if (!preg_match($pattern, $classname)) { throw new \InvalidArgumentException( sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL . 'Please see reference document: ' . 'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md' ); } $resource = $container->get('locator.resource_manager')->createResource($classname); $container->get('code_generator')->generate($resource, 'specification'); } }
<?php namespace PhpSpec\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class DescribeCommand extends Command { public function __construct() { parent::__construct('describe'); $this->setDefinition(array( new InputArgument('class', InputArgument::REQUIRED, 'Class to describe'), )); } protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getApplication()->getContainer(); $container->configure(); $classname = $input->getArgument('class'); $pattern = '/^[a-zA-Z_\/\\\\][a-zA-Z0-9_\/\\\\]*$/'; if (!preg_match($pattern, $classname)) { throw new \InvalidArgumentException( sprintf('String "%s" is not a valid class name.', $classname) . PHP_EOL . 'Please see reference document:' . 'https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md' ); } $resource = $container->get('locator.resource_manager')->createResource($classname); $container->get('code_generator')->generate($resource, 'specification'); } }
Add test for signup success
import unittest from unittest import TestCase from user import User from bucketlist import BucketList from flask import url_for, session from app import app class BucketListTest(TestCase): def setUp(self): app.config['SECRET_KEY'] = 'seasasaskrit!' # creates a test client self.client = app.test_client() self.client.testing = True def test_success(self): # sends HTTP GET request to the application # on the specified path result = self.client.get('/login') self.assertEqual(result.status_code, 200) def test_failure(self): # sends HTTP GET request to the application # on the specified path result = self.client.get('/nonexistant.html') self.assertEqual(result.status_code, 404) def test_login_page_loads(self): # assert login page loads correctly result = self.client.get('/login') self.assertTrue(b'The best way to keep track of your dreams and goals' in result.data) def test_sign_page_posts_and_redirects(self): result = self.client.post('signup', data={ 'username': 'hermano', 'email': '[email protected]', 'password': 'hard', 'confirm_password': 'hard' }) self.assertTrue(result.status_code == 302) if __name__ == '__main__': unittest.main()
import unittest from unittest import TestCase from user import User from bucketlist import BucketList from flask import url_for from app import app class BucketListTest(TestCase): def setUp(self): # creates a test client self.client = app.test_client() self.client.testing = True def test_success(self): # sends HTTP GET request to the application # on the specified path result = self.client.get('/login') self.assertEqual(result.status_code, 200) def test_failure(self): # sends HTTP GET request to the application # on the specified path result = self.client.get('/nonexistant.html') self.assertEqual(result.status_code, 404) def test_login_page_loads(self): # assert login page loads correctly result = self.client.get('/login') self.assertTrue(b'The best way to keep track of your dreams and goals' in result.data) ''' def test_signup(self): # register a new account response = self.client.post(url_for('/signup'), data={ 'username': 'hermano', 'email': '[email protected]', 'password': 'hard', 'confirm_password': 'hard' }) self.assertTrue(response.status_code == 302) ''' if __name__ == '__main__': unittest.main()
Clean the variable space by unsetting $data and $shared
<?php /** * This file is part of endobox. * * (c) 2015-2016 YouniS Bensalah <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace endobox; /** * */ class EvalRendererDecorator extends RendererDecorator { /** * */ public function render(Renderable $input, array &$data = null, array $shared = null) : string { $code = parent::render($input, $data, $shared); if (\strpos($code, '<?php') !== false) { return (function (&$_) use (&$data, &$shared) { if ($data !== null) { \extract($data, EXTR_SKIP | EXTR_REFS); unset($data); } if ($shared !== null) { foreach ($shared as &$x) { \extract($x, EXTR_SKIP | EXTR_REFS); } unset($shared); } \ob_start(); eval('?>' . $_); return \ob_get_clean(); })($code); } return $code; } }
<?php /** * This file is part of endobox. * * (c) 2015-2016 YouniS Bensalah <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace endobox; /** * */ class EvalRendererDecorator extends RendererDecorator { /** * */ public function render(Renderable $input, array &$data = null, array $shared = null) : string { $code = parent::render($input, $data, $shared); if (\strpos($code, '<?php') !== false) { return (function (&$_) use (&$data, &$shared) { if ($data !== null) { \extract($data, EXTR_SKIP | EXTR_REFS); } if ($shared !== null) { foreach ($shared as &$x) { \extract($x, EXTR_SKIP | EXTR_REFS); } } \ob_start(); eval('?>' . $_); return \ob_get_clean(); })($code); } return $code; } }
Call an update method to manage incoming jobs
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.jidtree = sconsole.jidtree.JIDView() self.body_frame = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body_frame, header=self.header, footer=self.footer) def body(self): return urwid.Frame(self.jidtree.listbox, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.set_alarm_in(1, self.jidtree.update) loop.run()
# Import third party libs import urwid # Import sconsole libs import sconsole.cmdbar import sconsole.static import sconsole.jidtree FOOTER = [ ('title', 'Salt Console'), ' ', ('key', 'UP'), ' ', ('key', 'DOWN'), ' '] class Manager(object): def __init__(self, opts): self.opts = opts self.cmdbar = sconsole.cmdbar.CommandBar(self.opts) self.header = urwid.LineBox(urwid.Text(('banner', 'Salt Console'), align='center')) self.jidtree = sconsole.jidtree.JIDView() self.body_frame = self.body() self.footer = urwid.AttrMap(urwid.Text(FOOTER), 'banner') self.view = urwid.Frame( body=self.body_frame, header=self.header, footer=self.footer) def body(self): return urwid.Frame(self.jidtree.listbox, header=self.cmdbar.grid) def unhandled_input(self, key): if key in ('q', 'Q'): raise urwid.ExitMainLoop() def start(self): palette = sconsole.static.get_palette( self.opts.get('theme', 'std') ) loop = urwid.MainLoop( self.view, palette=palette, unhandled_input=self.unhandled_input) loop.run()
Add a statement that info search is not currently implemented
<?php namespace App\Repositories; use App\Work; use App\Type; use DB; use Response; class WorksRepository { /** * Queries database for all works based on catID * */ public function getallworks($catID) { return Work::join('types','works.typeID','=','types.typeID') ->select('workID','catID','contentType','expectedFields','url','info','tags') ->where('catID','=',$catID) ->where('approved',true) ->get(); } /** * Will display all works for a category that satisfy query. * * @return Response */ public function retrieve($catID, $infos, $tags) { return $worksfromcat = Work::join('types','works.typeID','=','types.typeID') ->select('workID','catID','contentType','expectedFields','url','info','tags') ->where('catID','=',$catID) ->where('approved',true) ->where(function($query) use ($infos){ // Info search, not currently implemented }) ->where(function($query) use ($tags){ foreach ($tags as $tag) { $query->whereRaw("exist(tags, ?)", array($tag)); } }) ->get(); } /** * Retrieve Tags from parameters. * * @return Response */ public function parsetags($params) { return $params['tags']; } } ?>
<?php namespace App\Repositories; use App\Work; use App\Type; use DB; use Response; class WorksRepository { /** * Queries database for all works based on catID * */ public function getallworks($catID) { return Work::join('types','works.typeID','=','types.typeID') ->select('workID','catID','contentType','expectedFields','url','info','tags') ->where('catID','=',$catID) ->where('approved',true) ->get(); } /** * Will display all works for a category that satisfy query. * * @return Response */ public function retrieve($catID, $infos, $tags) { return $worksfromcat = Work::join('types','works.typeID','=','types.typeID') ->select('workID','catID','contentType','expectedFields','url','info','tags') ->where('catID','=',$catID) ->where('approved',true) ->where(function($query) use ($infos){ }) ->where(function($query) use ($tags){ foreach ($tags as $tag) { $query->whereRaw("exist(tags, ?)", array($tag)); } }) ->get(); } /** * Retrieve Tags from parameters. * * @return Response */ public function parsetags($params) { return $params['tags']; } } ?>
Fix relation from feed to user
"use strict"; var uuid = require('node-uuid'); module.exports = function(sequelize, DataTypes) { var UserFeed = sequelize.define("UserFeed", { name : { type : DataTypes.STRING, allowNull : false, }, feed_token : { type : DataTypes.STRING, allowNull : false, }, type : { type : DataTypes.ENUM('calendar', 'wallchart', 'company'), allowNull : false, }, }, { classMethods: { associate : function( models ) { UserFeed.belongsTo(models.User, {as : 'user', foreignKey : 'userId'}); }, promise_new_feed : function(args){ var self = this, user = args.user, type = args.type; return self .find({ where : {userId : user.id, type : type} }) .then(function(feed){ if ( feed ) { feed.feed_token = uuid.v4(); return feed.save(); } else { return self.create({ name : "Calendar Feed", feed_token : uuid.v4(), type : type, userId : user.id, }); } }) }, }, instanceMethods : { }, }); return UserFeed; };
"use strict"; var uuid = require('node-uuid'); module.exports = function(sequelize, DataTypes) { var UserFeed = sequelize.define("UserFeed", { name : { type : DataTypes.STRING, allowNull : false, }, feed_token : { type : DataTypes.STRING, allowNull : false, }, type : { type : DataTypes.ENUM('calendar', 'wallchart', 'company'), allowNull : false, }, }, { classMethods: { associate : function( models ) { UserFeed.belongsTo(models.User, {as : 'user'}); }, promise_new_feed : function(args){ var self = this, user = args.user, type = args.type; return self .find({ where : {userId : user.id, type : type} }) .then(function(feed){ if ( feed ) { feed.feed_token = uuid.v4(); return feed.save(); } else { return self.create({ name : "Calendar Feed", feed_token : uuid.v4(), type : type, userId : user.id, }); } }) }, }, instanceMethods : { }, }); return UserFeed; };
Fix typo in stream_get_contents() call
<?php namespace MongoDB\Tests\GridFS; use MongoDB\Collection; use MongoDB\GridFS\Bucket; use MongoDB\Tests\FunctionalTestCase as BaseFunctionalTestCase; /** * Base class for GridFS functional tests. */ abstract class FunctionalTestCase extends BaseFunctionalTestCase { protected $bucket; protected $chunksCollection; protected $filesCollection; public function setUp() { parent::setUp(); $this->bucket = new Bucket($this->manager, $this->getDatabaseName()); $this->bucket->drop(); $this->chunksCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.chunks'); $this->filesCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.files'); } /** * Asserts that a variable is a stream containing the expected data. * * Note: this will seek to the beginning of the stream before reading. * * @param string $expectedContents * @param resource $stream */ protected function assertStreamContents($expectedContents, $stream) { $this->assertInternalType('resource', $stream); $this->assertSame('stream', get_resource_type($stream)); $this->assertEquals($expectedContents, stream_get_contents($stream, -1, 0)); } /** * Creates an in-memory stream with the given data. * * @param string $data * @return resource */ protected function createStream($data = '') { $stream = fopen('php://temp', 'w+b'); fwrite($stream, $data); rewind($stream); return $stream; } }
<?php namespace MongoDB\Tests\GridFS; use MongoDB\Collection; use MongoDB\GridFS\Bucket; use MongoDB\Tests\FunctionalTestCase as BaseFunctionalTestCase; /** * Base class for GridFS functional tests. */ abstract class FunctionalTestCase extends BaseFunctionalTestCase { protected $bucket; protected $chunksCollection; protected $filesCollection; public function setUp() { parent::setUp(); $this->bucket = new Bucket($this->manager, $this->getDatabaseName()); $this->bucket->drop(); $this->chunksCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.chunks'); $this->filesCollection = new Collection($this->manager, $this->getDatabaseName(), 'fs.files'); } /** * Asserts that a variable is a stream containing the expected data. * * Note: this will seek to the beginning of the stream before reading. * * @param string $expectedContents * @param resource $stream */ protected function assertStreamContents($expectedContents, $stream) { $this->assertInternalType('resource', $stream); $this->assertSame('stream', get_resource_type($stream)); $this->assertEquals($expectedContents, stream_get_contents($stream, -1,.0)); } /** * Creates an in-memory stream with the given data. * * @param string $data * @return resource */ protected function createStream($data = '') { $stream = fopen('php://temp', 'w+b'); fwrite($stream, $data); rewind($stream); return $stream; } }
Fix junit utf-8 output to file
# -*- coding: utf-8 -*- import json from junit_xml import TestSuite, TestCase class JunitFormatter(object): def __init__(self, project_cfg, project_result): """Initialize the stuff""" self.testcases = { unicode(item["id"]): item for item in project_cfg["testcases"] } test_cases = [] for case in project_result["results"]: tc = TestCase( u"{0}".format(self.testcases[str(case["testcase_id"])]["name"]), elapsed_sec=case["duration_sec"] ) if case["status"] == "failed": # Last error and first error message tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"]) test_cases.append(tc) self.test_suite = TestSuite( name=u"Project {0}".format(project_cfg["project_name"]), test_cases=test_cases ) def to_file(self, filename): """ Output project results to specified filename """ with open(filename, 'w') as f: f.write( TestSuite.to_xml_string( [self.test_suite], prettyprint=True, encoding="utf-8" ).encode("utf-8") )
import json from junit_xml import TestSuite, TestCase class JunitFormatter(object): def __init__(self, project_cfg, project_result): """Initialize the stuff""" self.testcases = { str(item["id"]): item for item in project_cfg["testcases"] } test_cases = [] for case in project_result["results"]: tc = TestCase( self.testcases[str(case["testcase_id"])]["name"], elapsed_sec=case["duration_sec"] ) if case["status"] == "failed": # Last error and first error message tc.add_error_info(case["steps_results"][-1]["errors"][0]["message"]) test_cases.append(tc) self.test_suite = TestSuite( name="Project {0}".format(project_cfg["project_name"]), test_cases=test_cases ) def to_file(self, filename): """ Output project results to specified filename """ with open(filename, 'w') as f: TestSuite.to_file(f, [self.test_suite], prettyprint=True)
Change 'jpg' to be the default extension type for 'image/jpeg'
<?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 Imbo\Image\OutputConverter; /** * Basic output converter that supports gif/png/jpg. * * @author Mats Lindh <[email protected]> * @package Image\OutputConverters */ class Basic implements OutputConverterInterface { public function getSupportedFormatsWithCallbacks() { return [ [ 'mime' => 'image/png', 'extension' => 'png', 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/jpeg', 'extension' => ['jpg', 'jpeg'], 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/gif', 'extension' => 'gif', 'callback' => [$this, 'convert'], ], ]; } public function convert($imagick, $image, $extension, $mime = null) { try { $imagick->setImageFormat($extension); } catch (ImagickException $e) { throw new OutputConversionException($e->getMessage(), 400, $e); } } }
<?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 Imbo\Image\OutputConverter; /** * Basic output converter that supports gif/png/jpg. * * @author Mats Lindh <[email protected]> * @package Image\OutputConverters */ class Basic implements OutputConverterInterface { public function getSupportedFormatsWithCallbacks() { return [ [ 'mime' => 'image/png', 'extension' => 'png', 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/jpeg', 'extension' => ['jpeg', 'jpg'], 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/gif', 'extension' => 'gif', 'callback' => [$this, 'convert'], ], ]; } public function convert($imagick, $image, $extension, $mime = null) { try { $imagick->setImageFormat($extension); } catch (ImagickException $e) { throw new OutputConversionException($e->getMessage(), 400, $e); } } }
Improve ParseableFormatter to be more like pylint Add an E in front of the rule ID so that pylint detects it as an error. Fixes #154
class Formatter(object): def format(self, match): formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n" return formatstr.format(match.rule.id, match.message, match.filename, match.linenumber, match.line) class QuietFormatter(object): def format(self, match): formatstr = u"[{0}] {1}:{2}" return formatstr.format(match.rule.id, match.filename, match.linenumber) class ParseableFormatter(object): def format(self, match): formatstr = u"{0}:{1}: [{2}] {3}" return formatstr.format(match.filename, match.linenumber, "E" + match.rule.id, match.message, )
class Formatter(object): def format(self, match): formatstr = u"[{0}] {1}\n{2}:{3}\n{4}\n" return formatstr.format(match.rule.id, match.message, match.filename, match.linenumber, match.line) class QuietFormatter(object): def format(self, match): formatstr = u"[{0}] {1}:{2}" return formatstr.format(match.rule.id, match.filename, match.linenumber) class ParseableFormatter(object): def format(self, match): formatstr = u"{0}:{1}: [{2}] {3}" return formatstr.format(match.filename, match.linenumber, match.rule.id, match.message, )
Use new bucket that has properly sized SVG assets
import React from "react"; // eslint-disable-line no-unused-vars class CountryMap extends React.Component { constructor(props) { super(props); this.state = { SVG: "" }; } componentWillMount() { let component = this; // TODO move to country-specific bucket or at least folder if (this.props.countrycode && this.props.countrycode !== null) { fetch( process.env.REACT_APP_ASSETS_URL + "countries/fullname/" + this.props.countrycode + ".svg?" ) .then(function(response) { return response.text(); }) .then(function(SVGtext) { component.setState({ SVG: SVGtext }); }); } } render() { return this.props.countrycode ? <div className="case-map"> <div dangerouslySetInnerHTML={{ __html: this.state.SVG }} /> {this.props.city ? <p className="case-location"> {this.props.city}, {this.props.countrycode} </p> : <p className="case-location">{this.props.countrycode}</p>} </div> : <div />; } } export default CountryMap;
import React from "react"; // eslint-disable-line no-unused-vars class CountryMap extends React.Component { constructor(props) { super(props); this.state = { SVG: "" }; } componentWillMount() { let component = this; // TODO move to country-specific bucket or at least folder if (this.props.countrycode && this.props.countrycode !== null) { fetch(process.env.REACT_APP_ASSETS_URL + this.props.countrycode + ".svg") .then(function(response) { return response.text(); }) .then(function(SVGtext) { let svg = '<svg class="country-map" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><style type="text/css"><![CDATA[.country-map path {stroke: none;fill: #d8382c;}]]></style></defs>' + SVGtext + "</svg>"; component.setState({ SVG: svg }); }); } } render() { return this.props.countrycode ? <div> <div dangerouslySetInnerHTML={{ __html: this.state.SVG }} /> {this.props.city ? <p className="case-location"> {this.props.city}, {this.props.countrycode} </p> : <p className="case-location">{this.props.countrycode}</p>} </div> : <div />; } } export default CountryMap;
Check existence of the user with appropriate email address
from django.core.management.base import BaseCommand from utils.create_random_data import create_items, create_users, create_orders from saleor.userprofile.models import User class Command(BaseCommand): help = 'Populate database with test objects' placeholders_dir = r'saleor/static/placeholders/' def add_arguments(self, parser): parser.add_argument( '--createsuperuser', action='store_true', dest='createsuperuser', default=False, help='Create admin account') def handle(self, *args, **options): for msg in create_items(self.placeholders_dir, 10): self.stdout.write(msg) for msg in create_users(10): self.stdout.write(msg) for msg in create_orders(20): self.stdout.write(msg) if options['createsuperuser']: credentials = {'email': '[email protected]', 'password': 'admin'} user, created = User.objects.get_or_create( email=credentials['email'], defaults={ 'is_active': True, 'is_staff': True, 'is_superuser': True}) if created: user.set_password(credentials['password']) user.save() self.stdout.write( 'Superuser - %(email)s/%(password)s' % credentials) else: self.stdout.write( 'Superuser already exists - %(email)s' % credentials)
from django.core.management.base import BaseCommand from utils.create_random_data import create_items, create_users, create_orders from saleor.userprofile.models import User class Command(BaseCommand): help = 'Populate database with test objects' placeholders_dir = r'saleor/static/placeholders/' def add_arguments(self, parser): parser.add_argument( '--createsuperuser', action='store_true', dest='createsuperuser', default=False, help='Create admin account') def handle(self, *args, **options): for msg in create_items(self.placeholders_dir, 10): self.stdout.write(msg) for msg in create_users(10): self.stdout.write(msg) for msg in create_orders(20): self.stdout.write(msg) if options['createsuperuser']: credentials = {'email': '[email protected]', 'password': 'admin'} user, created = User.objects.get_or_create( email=credentials['email'], is_active=True, is_staff=True, is_superuser=True) if created: user.set_password(credentials['password']) user.save() self.stdout.write( 'Superuser - %(email)s/%(password)s' % credentials) else: self.stdout.write( 'Superuser already exists - %(email)s' % credentials)
Fix Meta init and from_dict
from collections import OrderedDict from malcolm.core.serializable import Serializable @Serializable.register("malcolm:core/Meta:1.0") class Meta(Serializable): """Meta class for describing Blocks""" def __init__(self, name, description, *args): super(Meta, self).__init__(name, *args) self.description = description self.tags = [] def update(self, change): """Update meta state Args: change [[element], new_value]: change to make to meta """ if len(change[0]) != 1: raise ValueError( "Change %s specifies substructure that can not exist in Meta" % change) if change[0][0] == "description": self.set_description(change[1], notify=True) elif change[0][0] == "tags": self.set_tags(change[1], notify=True) else: raise ValueError( "Change %s refers to unknown meta attribute" % change) def set_description(self, description, notify=True): self.description = description self.on_changed([["description"], description], notify) def set_tags(self, tags, notify=True): self.tags = tags self.on_changed([["tags"], tags], notify) def to_dict(self): d = OrderedDict() d["description"] = self.description d["tags"] = self.tags d["typeid"] = self.typeid return d @classmethod def from_dict(cls, name, d, *args): meta = cls(name, d["description"], *args) meta.tags = d["tags"] return meta
from collections import OrderedDict from malcolm.core.serializable import Serializable @Serializable.register("malcolm:core/Meta:1.0") class Meta(Serializable): """Meta class for describing Blocks""" def __init__(self, name, description): super(Meta, self).__init__(name) self.description = description self.tags = [] def update(self, change): """Update meta state Args: change [[element], new_value]: change to make to meta """ if len(change[0]) != 1: raise ValueError( "Change %s specifies substructure that can not exist in Meta" % change) if change[0][0] == "description": self.set_description(change[1], notify=True) elif change[0][0] == "tags": self.set_tags(change[1], notify=True) else: raise ValueError( "Change %s refers to unknown meta attribute" % change) def set_description(self, description, notify=True): self.description = description self.on_changed([["description"], description], notify) def set_tags(self, tags, notify=True): self.tags = tags self.on_changed([["tags"], tags], notify) def to_dict(self): d = OrderedDict() d["description"] = self.description d["tags"] = self.tags d["typeid"] = self.typeid return d @classmethod def from_dict(cls, name, d): meta = Meta(name, d["description"]) meta.tags = d["tags"] return meta
Add not enough characters condition
# coding: utf8 from io import StringIO from collections import deque class StreamReader: def __init__(self, *args, stream_class=StringIO, **kwargs): self.streamClass = stream_class self.args = args self.kwargs = kwargs def read(self, parsing_pipeline): parsing_pipeline.reset() min_position = parsing_pipeline.get_min_position() max_position = parsing_pipeline.get_max_position() length = max_position - min_position + 1 stream = self.streamClass(*self.args, **self.kwargs) current_position = -min_position ar_index = list() element = deque(stream.read(length)) if len(element) == length: while True: result = parsing_pipeline.check(element, ref_position=-min_position) if result is not None and result[0]: ar_index.append((current_position, element[-min_position])) next_character = stream.read(1) current_position += 1 if next_character and result is not None: element.popleft() element.append(next_character) else: break stream.close() return ar_index else: stream.close() raise ValueError("Not enough characters to parse : " + str(len(element)))
# coding: utf8 from io import StringIO from collections import deque class StreamReader: def __init__(self, *args, stream_class=StringIO, **kwargs): self.streamClass = stream_class self.args = args self.kwargs = kwargs def read(self, parsing_pipeline): parsing_pipeline.reset() stream = self.streamClass(*self.args, **self.kwargs) min_position = parsing_pipeline.get_min_position() max_position = parsing_pipeline.get_max_position() length = max_position - min_position + 1 current_position = -min_position ar_index = list() element = deque(stream.read(length)) while True: result = parsing_pipeline.check(element, ref_position=-min_position) if result is not None and result[0]: ar_index.append((current_position, element[-min_position])) next_character = stream.read(1) current_position += 1 if next_character and result is not None: element.popleft() element.append(next_character) else: break stream.close() return ar_index
Update nl2br to work with None as input
from jinja2 import escape, Markup, evalcontextfilter from radar.lib.utils import date_to_datetime, is_date def strftime(dt, dt_format): if dt is None: return '' else: return dt.strftime(dt_format) def year_format(dt): if dt is None: return '' else: return '%04d' % dt.year def date_format(dt): if dt is None: return '' else: return '%02d/%02d/%04d' % (dt.day, dt.month, dt.year) def datetime_format(dt, seconds=False): if dt is None: return '' else: if is_date(dt): dt = date_to_datetime(dt) output = '%02d/%02d/%04d %02d:%02d' % (dt.day, dt.month, dt.year, dt.hour, dt.minute) if seconds: output += ':%02d' % dt.second return output @evalcontextfilter def nl2br(eval_ctx, value): if value is None: return '' value = escape(value) value = value.replace('\n', Markup('<br />\n')) if eval_ctx.autoescape: value = Markup(value) return value def missing(value): if value is None or value == '': return '-' else: return value def yn(value): if value is None: return '-' elif value: return 'Yes' else: return 'No'
from jinja2 import escape, Markup, evalcontextfilter from radar.lib.utils import date_to_datetime, is_date def strftime(dt, dt_format): if dt is None: return '' else: return dt.strftime(dt_format) def year_format(dt): if dt is None: return '' else: return '%04d' % dt.year def date_format(dt): if dt is None: return '' else: return '%02d/%02d/%04d' % (dt.day, dt.month, dt.year) def datetime_format(dt, seconds=False): if dt is None: return '' else: if is_date(dt): dt = date_to_datetime(dt) output = '%02d/%02d/%04d %02d:%02d' % (dt.day, dt.month, dt.year, dt.hour, dt.minute) if seconds: output += ':%02d' % dt.second return output @evalcontextfilter def nl2br(eval_ctx, value): value = escape(value) value = value.replace('\n', Markup('<br />\n')) if eval_ctx.autoescape: value = Markup(value) return value def missing(value): if value is None or value == '': return '-' else: return value def yn(value): if value is None: return '-' elif value: return 'Yes' else: return 'No'
Change sort of cars and add aditional params to query
define(["underscore", "jquery", "app"], function(_, $, app) { return function () { var public = {}; var private = {}; private.createObject = function (averageCartype) { var queryObject = { c: [], ecol: [], sc: null, p: null, psz: 100, ll: null, dam: 0, ao: "PICTURES", sb: "ml", rtd: 1 }; // Cartypes for (var carclass in averageCartype.get("carclass")) queryObject.c.push(carclass); // Colors for (var color in averageCartype.get("colors")) queryObject.ecol.push(color); // Seats var seatsRange = averageCartype.get("min_seats") + ":" + averageCartype.get("max_seats"); queryObject.sc = seatsRange; // Price var priceRange = averageCartype.get("min_price") + ":" + averageCartype.get("max_price"); queryObject.p = priceRange; // Location queryObject.ll = app.userProfile.get("point"); return queryObject; }; private.createURL = function (queryObject) { var url = "http://m.mobile.de/svc/s/?"; var params = $.param(queryObject); url = url.concat(params); return url; }; public.getResults = function (averageCartype) { var queryObject = private.createObject(averageCartype); var url = private.createURL(queryObject); return $.getJSON(url); }; return public; }; });
define(["underscore", "jquery", "app"], function(_, $, app) { return function () { var public = {}; var private = {}; private.createObject = function (averageCartype) { var queryObject = { c: [], ecol: [], sc: null, p: null, psz: 100, ll: null, dam: 0, ao: "PICTURES" }; // Cartypes for (var carclass in averageCartype.get("carclass")) queryObject.c.push(carclass); // Colors for (var color in averageCartype.get("colors")) queryObject.ecol.push(color); // Seats var seatsRange = averageCartype.get("min_seats") + ":" + averageCartype.get("max_seats"); queryObject.sc = seatsRange; // Price var priceRange = averageCartype.get("min_price") + ":" + averageCartype.get("max_price"); queryObject.p = priceRange; // Location queryObject.ll = app.userProfile.get("point"); return queryObject; }; private.createURL = function (queryObject) { var url = "http://m.mobile.de/svc/s/?"; var params = $.param(queryObject); url = url.concat(params); return url; }; public.getResults = function (averageCartype) { var queryObject = private.createObject(averageCartype); var url = private.createURL(queryObject); return $.getJSON(url); }; return public; }; });
Fix an issue with the tetris max level
/** * The Level Class */ class Level { /** * The Level constructor * @param {Number} maxLevels */ constructor(maxLevels) { this.levelerElem = document.querySelector(".leveler"); this.maxLevels = maxLevels; this.level = 1; } /** * Returns the initial level * @returns {Number} */ get() { return this.level; } /** * Increases the initial level */ inc() { Utils.unselect(); if (this.level < this.maxLevels) { this.level += 1; this.show(); } } /** * Decreases the initial level */ dec() { Utils.unselect(); if (this.level > 1) { this.level -= 1; this.show(); } } /** * Sets the initial level * @param {Number} */ choose(level) { if (level > 0 && level <= this.maxLevels) { this.level = level; this.show(); } } /** * Sets the initial level */ show() { this.levelerElem.innerHTML = this.level; } }
/** * The Level Class */ class Level { /** * The Level constructor * @param {Number} maxLevels */ constructor(maxLevels) { this.levelerElem = document.querySelector(".leveler"); this.maxLevels = maxLevels; this.level = 1; } /** * Returns the initial level * @returns {Number} */ get() { return this.level; } /** * Increases the initial level */ inc() { Utils.unselect(); if (this.level < this.maxLevels) { this.level += 1; this.show(); } } /** * Decreases the initial level */ dec() { Utils.unselect(); if (this.level > 1) { this.level -= 1; this.show(); } } /** * Sets the initial level * @param {Number} */ choose(level) { if (level > 0 && level <= this.maxInitialLevel) { this.level = level; this.show(); } } /** * Sets the initial level */ show() { this.levelerElem.innerHTML = this.level; } }
Replace method getName() in form types with "getBlockPrefix()".
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\Blank; /** * Anti-spam form type */ class AntiSpamType extends AbstractType { const ANTI_SPAM_TYPE_CLASS = __CLASS__; /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'label' => false, 'attr' => array( 'class' => 'title_field', ), 'constraints' => new Blank(), 'mapped' => false, 'required' => false, )); } /** * {@inheritdoc} */ public function getParent() { return 'text'; } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'darvin_utils_anti_spam'; } }
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Validator\Constraints\Blank; /** * Anti-spam form type */ class AntiSpamType extends AbstractType { const ANTI_SPAM_TYPE_CLASS = __CLASS__; /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'label' => false, 'attr' => array( 'class' => 'title_field', ), 'constraints' => new Blank(), 'mapped' => false, 'required' => false, )); } /** * {@inheritdoc} */ public function getParent() { return 'text'; } /** * {@inheritdoc} */ public function getName() { return 'darvin_utils_anti_spam'; } }
Support for anonymous saved versions This fixes a case when de API sends a version without user. There was a bug allowing to create anonymous versions in the application and we have to support the old data. The problem here is that SnapshotInfo classes are inflated from json via Gson. This method does not call any constructor and, since the json does not include the ‘user’ key, the bridge crashes because we’re not expecting null users. I’m not happy with this fix, but is the minimum solution that does not affect anything else.
package uk.ac.ic.wlgitbridge.snapshot.getsavedvers; import uk.ac.ic.wlgitbridge.util.Util; /** * Created by Winston on 06/11/14. */ public class SnapshotInfo implements Comparable<SnapshotInfo> { private int versionId; private String comment; private WLUser user; private String createdAt; public SnapshotInfo(int versionID, String createdAt, String name, String email) { this(versionID, "Update on " + Util.getServiceName() + ".", email, name, createdAt); } public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) { versionId = versionID; this.comment = comment; user = new WLUser(name, email); this.createdAt = createdAt; } public int getVersionId() { return versionId; } public String getComment() { return comment; } public WLUser getUser() { return user != null ? user : new WLUser(); } public String getCreatedAt() { return createdAt; } @Override public boolean equals(Object obj) { if (!(obj instanceof SnapshotInfo)) { return false; } SnapshotInfo that = (SnapshotInfo) obj; return versionId == that.versionId; } @Override public int compareTo(SnapshotInfo o) { return Integer.compare(versionId, o.versionId); } }
package uk.ac.ic.wlgitbridge.snapshot.getsavedvers; import uk.ac.ic.wlgitbridge.util.Util; /** * Created by Winston on 06/11/14. */ public class SnapshotInfo implements Comparable<SnapshotInfo> { private int versionId; private String comment; private WLUser user; private String createdAt; public SnapshotInfo(int versionID, String createdAt, String name, String email) { this(versionID, "Update on " + Util.getServiceName() + ".", email, name, createdAt); } public SnapshotInfo(int versionID, String comment, String email, String name, String createdAt) { versionId = versionID; this.comment = comment; user = new WLUser(name, email); this.createdAt = createdAt; } public int getVersionId() { return versionId; } public String getComment() { return comment; } public WLUser getUser() { return user; } public String getCreatedAt() { return createdAt; } @Override public boolean equals(Object obj) { if (!(obj instanceof SnapshotInfo)) { return false; } SnapshotInfo that = (SnapshotInfo) obj; return versionId == that.versionId; } @Override public int compareTo(SnapshotInfo o) { return Integer.compare(versionId, o.versionId); } }
Truncate Log messages to 4000 chars.
<?php namespace LiteCQRS\Plugin\Monolog; use LiteCQRS\Bus\MessageHandlerInterface; use LiteCQRS\Bus\MessageInterface; use LiteCQRS\DomainEvent; use LiteCQRS\Command; use Exception; use Monolog\Logger; /** * Logs all commands or events and their sucess/failure status * into a logger. The input data is json serialized during that process. */ class MonologDebugLogger implements MessageHandlerInterface { private $logger; private $next; public function __construct(MessageHandlerInterface $next, Logger $logger) { $this->next = $next; $this->logger = $logger; } public function handle(MessageInterface $message) { if ($message instanceof Command) { $parts = explode("\\", get_class($message)); $log = "Command[%s]: "; $info = substr(end($parts) . ": " . json_encode($message), 0, 4000); } else if ($message instanceof DomainEvent) { $log = "Event[%s]: "; $info = substr($message->getEventName() . ": " . json_encode($message), 0, 4000); } try { $this->logger->debug(sprintf($log, 'STARTING') . $info); $this->next->handle($message); $this->logger->err(sprintf($log, 'SUCCESS') . $info); } catch(Exception $e) { $this->logger->err(sprintf($log, 'FAIL') . ' - ' . $e->getMessage()); throw $e; } } }
<?php namespace LiteCQRS\Plugin\Monolog; use LiteCQRS\Bus\MessageHandlerInterface; use LiteCQRS\Bus\MessageInterface; use LiteCQRS\DomainEvent; use LiteCQRS\Command; use Exception; use Monolog\Logger; /** * Logs all commands or events and their sucess/failure status * into a logger. The input data is json serialized during that process. */ class MonologDebugLogger implements MessageHandlerInterface { private $logger; private $next; public function __construct(MessageHandlerInterface $next, Logger $logger) { $this->next = $next; $this->logger = $logger; } public function handle(MessageInterface $message) { if ($message instanceof Command) { $parts = explode("\\", get_class($message)); $log = "Command[%s]: "; $info = end($parts) . ": " . json_encode($message); } else if ($message instanceof DomainEvent) { $log = "Event[%s]: "; $info = $message->getEventName() . ": " . json_encode($message); } try { $this->logger->debug(sprintf($log, 'STARTING') . $info); $this->next->handle($message); $this->logger->debug(sprintf($log, 'SUCCESS') . $info); } catch(Exception $e) { $this->logger->err(sprintf($log, 'FAIL') . ' - ' . $e->getMessage()); throw $e; } } }
Fix nullable username in user integrations table
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersIntegrationsTable extends AbstractMigration { public function change(): void { $table = $this->table('nl2_users_integrations'); $table ->addColumn('user_id', 'integer', ['length' => 11]) ->addColumn('integration_id', 'integer', ['length' => 11]) ->addColumn('identifier', 'string', ['length' => 64, 'null' => true, 'default' => null]) ->addColumn('username', 'string', ['length' => 32, 'null' => true, 'default' => null]) ->addColumn('verified', 'boolean', ['default' => false]) ->addColumn('date', 'integer', ['length' => 11]) ->addColumn('code', 'string', ['length' => 64, 'null' => true, 'default' => null]) ->addColumn('show_publicly', 'boolean', ['default' => true]) ->addColumn('last_sync', 'integer', ['length' => 11, 'default' => 0]); $table ->addForeignKey('user_id', 'nl2_users', 'id', ['delete' => 'CASCADE']) ->addForeignKey('integration_id', 'nl2_integrations', 'id', ['delete' => 'CASCADE']); $table ->addIndex(['user_id', 'integration_id'], ['unique' => true]); $table->create(); } }
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateUsersIntegrationsTable extends AbstractMigration { public function change(): void { $table = $this->table('nl2_users_integrations'); $table ->addColumn('user_id', 'integer', ['length' => 11]) ->addColumn('integration_id', 'integer', ['length' => 11]) ->addColumn('identifier', 'string', ['length' => 64, 'null' => true, 'default' => null]) ->addColumn('username', 'string', ['length' => 32]) ->addColumn('verified', 'boolean', ['default' => false]) ->addColumn('date', 'integer', ['length' => 11]) ->addColumn('code', 'string', ['length' => 64, 'null' => true, 'default' => null]) ->addColumn('show_publicly', 'boolean', ['default' => true]) ->addColumn('last_sync', 'integer', ['length' => 11, 'default' => 0]); $table ->addForeignKey('user_id', 'nl2_users', 'id', ['delete' => 'CASCADE']) ->addForeignKey('integration_id', 'nl2_integrations', 'id', ['delete' => 'CASCADE']); $table ->addIndex(['user_id', 'integration_id'], ['unique' => true]); $table->create(); } }
Exclude libraries as object (eg. _.find())
'use strict'; module.exports = { meta: { docs: { description: 'Forbid methods added in ES6' }, schema: [] }, create(context) { return { CallExpression(node) { const objectExceptions = ['_']; if(node.callee && node.callee.property && objectExceptions.indexOf(node.callee.object.name) === -1) { const functionName = node.callee.property.name; const es6ArrayFunctions = [ 'find', 'findIndex', 'copyWithin', 'values', 'fill' ]; const es6StringFunctions = [ 'startsWith', 'endsWith', 'includes', 'repeat' ]; const es6Functions = [].concat( es6ArrayFunctions, es6StringFunctions ); if(es6Functions.indexOf(functionName) > -1) { context.report({ node: node.callee.property, message: 'ES6 methods not allowed: ' + functionName }); } } } }; } };
'use strict'; module.exports = { meta: { docs: { description: 'Forbid methods added in ES6' }, schema: [] }, create(context) { return { CallExpression(node) { if(node.callee && node.callee.property) { const functionName = node.callee.property.name; const es6ArrayFunctions = [ 'find', 'findIndex', 'copyWithin', 'values', 'fill' ]; const es6StringFunctions = [ 'startsWith', 'endsWith', 'includes', 'repeat' ]; const es6Functions = [].concat( es6ArrayFunctions, es6StringFunctions ); if(es6Functions.indexOf(functionName) > -1) { context.report({ node: node.callee.property, message: 'ES6 methods not allowed: ' + functionName }); } } } }; } };
Revert "Last codestyle fix (I hope)" This reverts commit 79c42c9bff7390fbc649578b89dcbef93633f33c.
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Util\Test as TestUtil; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class DataProviderTestSuite extends TestSuite { /** * @var string[] */ private $dependencies = []; /** * @param string[] $dependencies */ public function setDependencies(array $dependencies): void { $this->dependencies = $dependencies; foreach ($this->tests as $test) { if (!$test instanceof TestCase) { continue; } $test->setDependencies($dependencies); } } public function getDependencies(): array { return $this->dependencies; } public function hasDependencies(): bool { return \count($this->dependencies) > 0; } /** * Returns the size of the each test created using the data provider(s) * * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function getSize(): int { [$className, $methodName] = \explode('::', $this->getName()); /** @psalm-suppress ArgumentTypeCoercion */ return TestUtil::getSize($className, $methodName); } }
<?php declare(strict_types=1); /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPUnit\Framework; use PHPUnit\Util\Test as TestUtil; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ final class DataProviderTestSuite extends TestSuite { /** * @var string[] */ private $dependencies = []; /** * @param string[] $dependencies */ public function setDependencies(array $dependencies): void { $this->dependencies = $dependencies; foreach ($this->tests as $test) { if (!$test instanceof TestCase) { continue; } $test->setDependencies($dependencies); } } public function getDependencies(): array { return $this->dependencies; } public function hasDependencies(): bool { return \count($this->dependencies) > 0; } /** * Returns the size of the each test created using the data provider(s) * * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public function getSize(): int { [$className, $methodName] = \explode('::', $this->getName()); /* @psalm-suppress ArgumentTypeCoercion */ return TestUtil::getSize($className, $methodName); } }
Refactor login code to handle JSON return values for api_key method.
package com.humbughq.android; import org.json.JSONException; import org.json.JSONObject; import android.content.SharedPreferences.Editor; import android.util.Log; import android.widget.TextView; class AsyncLogin extends HumbugAsyncPushTask { public AsyncLogin(HumbugActivity humbugActivity, String username, String password) { super(humbugActivity); context = humbugActivity; this.context.email = username; this.setProperty("username", username); this.setProperty("password", password); } public final void execute() { execute("api/v1/fetch_api_key"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { try { JSONObject obj = new JSONObject(result); if (obj.getString("result").equals("success")) { this.context.api_key = obj.getString("api_key"); Log.i("login", "Logged in as " + this.context.api_key); Editor ed = this.context.settings.edit(); ed.putString("email", this.context.email); ed.putString("api_key", this.context.api_key); ed.commit(); this.context.openLogin(); return; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } TextView errorText = (TextView) this.context .findViewById(R.id.error_text); errorText.setText("Login failed"); } }
package com.humbughq.android; import android.content.SharedPreferences.Editor; import android.util.Log; import android.widget.TextView; class AsyncLogin extends HumbugAsyncPushTask { public AsyncLogin(HumbugActivity humbugActivity, String username, String password) { super(humbugActivity); context = humbugActivity; this.context.email = username; this.setProperty("username", username); this.setProperty("password", password); } public final void execute() { execute("api/v1/fetch_api_key"); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != null) { this.context.api_key = result.toString(); Log.i("login", "Logged in as " + this.context.api_key); Editor ed = this.context.settings.edit(); ed.putString("email", this.context.email); ed.putString("api_key", this.context.api_key); ed.commit(); this.context.openLogin(); } else { TextView errorText = (TextView) this.context .findViewById(R.id.error_text); errorText.setText("Login failed"); } } }
Update mock Account in tests.
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None sync_state = 'running' def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
""" Test that the All Mail folder is enabled for Gmail. """ import pytest from inbox.auth.gmail import GmailAuthHandler from inbox.basicauth import GmailSettingError from inbox.crispin import GmailCrispinClient class AccountStub(object): id = 0 email_address = '[email protected]' access_token = None imap_endpoint = None def new_token(self): return ('foo', 22) def validate_token(self, new_token): return True class ConnectionStub(object): def logout(self): pass def get_auth_handler(monkeypatch, folders): g = GmailAuthHandler('gmail') def mock_connect(a): return ConnectionStub() g.connect_account = mock_connect monkeypatch.setattr(GmailCrispinClient, 'folder_names', lambda x: folders) return g def test_all_mail_missing(monkeypatch): """ Test that validate_folders throws a GmailSettingError if All Mail is not in the list of folders. """ g = get_auth_handler(monkeypatch, {'inbox': 'INBOX'}) with pytest.raises(GmailSettingError): g.verify_account(AccountStub()) def test_all_mail_present(monkeypatch): """ Test that the validate_folders passes if All Mail is present. """ g = get_auth_handler(monkeypatch, {'all': 'ALL', 'inbox': 'INBOX', 'trash': 'TRASH'}) assert g.verify_account(AccountStub())
Fix referencing of oauth flow. @gtrogers @robyoung
import httplib2 import json import itertools from collections import defaultdict from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run class Locations(object): CLIENT_SECRETS_FILE = 'client_secrets.json' FLOW = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope = "https://www.googleapis.com/auth/analytics.readonly", message = "Something seems to have gone wrong, check the client secrets file") def __init__(self): storage = Storage("tokens.dat") credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(self.FLOW, storage) http = httplib2.Http() http = credentials.authorize(http) service = build("analytics","v3", http = http) query = service.data().ga().get( metrics = "ga:visits", dimensions = "ga:pagePath,ga:country", max_results = "5000", start_date = "2013-01-01", end_date = "2013-02-01", ids = "ga:63654109", filters = "ga:pagePath=~^/apply-for-a-licence/.*/form$") response = query.execute()['rows'] self.results = response
import httplib2 import json import itertools from collections import defaultdict from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run class Locations(object): CLIENT_SECRETS_FILE = 'client_secrets.json' FLOW = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope = "https://www.googleapis.com/auth/analytics.readonly", message = "Something seems to have gone wrong, check the client secrets file") def __init__(self): storage = Storage("tokens.dat") credentials = storage.get() if credentials is None or credentials.invalid: credentials = run(FLOW, storage) http = httplib2.Http() http = credentials.authorize(http) service = build("analytics","v3", http = http) query = service.data().ga().get( metrics = "ga:visits", dimensions = "ga:pagePath,ga:country", max_results = "5000", start_date = "2013-01-01", end_date = "2013-02-01", ids = "ga:63654109", filters = "ga:pagePath=~^/apply-for-a-licence/.*/form$") response = query.execute()['rows'] self.results = response
Fix a display bug when two dates are the same day.
(function init() { var input1 = document.getElementById("input1"); var input2 = document.getElementById("input2"); var searchParams = new URLSearchParams(window.location.search); if (input1.value === "") { input1.value = searchParams.get("startDate"); } if (input2.value === "") { input2.value = searchParams.get("endDate"); } input1.addEventListener("input", calc); input2.addEventListener("input", calc); calc(); })(); function calc() { var str1 = document.getElementById("input1").value; var str2 = document.getElementById("input2").value; var period = DateCalc.between(str1, str2); var days = period.getDays(); if (isNaN(days)) { document.getElementById("prompt").innerHTML = "Error:"; document.getElementById("output").value = "Please enter valid inputs."; } else { var daysString; if (days === 1) { daysString = days + " day"; } else { daysString = days + " days"; } var periodString = period.toString(); var resultString; if (periodString === "" || daysString === periodString) { resultString = daysString; } else { resultString = daysString + " (" + periodString + ")"; } document.getElementById("prompt").innerHTML = "Between " + period.startDate.toString() + " and " + period.endDate.toString() + ":"; document.getElementById("output").value = resultString; } }
(function init() { var input1 = document.getElementById("input1"); var input2 = document.getElementById("input2"); var searchParams = new URLSearchParams(window.location.search); if (input1.value === "") { input1.value = searchParams.get("startDate"); } if (input2.value === "") { input2.value = searchParams.get("endDate"); } input1.addEventListener("input", calc); input2.addEventListener("input", calc); calc(); })(); function calc() { var str1 = document.getElementById("input1").value; var str2 = document.getElementById("input2").value; var period = DateCalc.between(str1, str2); var days = period.getDays(); if (isNaN(days)) { document.getElementById("prompt").innerHTML = "Error:"; document.getElementById("output").value = "Please enter valid inputs."; } else { var daysString; if (days === 1) { daysString = days + " day"; } else { daysString = days + " days"; } var periodString = period.toString(); var resultString; if (daysString === periodString) { resultString = daysString; } else { resultString = daysString + " (" + periodString + ")"; } document.getElementById("prompt").innerHTML = "Between " + period.startDate.toString() + " and " + period.endDate.toString() + ":"; document.getElementById("output").value = resultString; } }
Add pycurl as an extras
import setuptools CLASSIFIERS = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Communications', 'Topic :: Internet', 'Topic :: Software Development :: Libraries'] DESC = 'A low-level Amazon Web Services API client for Tornado' setuptools.setup(name='tornado-aws', version='0.6.0', description=DESC, long_description=open('README.rst').read(), author='Gavin M. Roy', author_email='[email protected]', url='http://tornado-aws.readthedocs.org', packages=['tornado_aws'], package_data={'': ['LICENSE', 'README.rst', 'requires/installation.txt']}, include_package_data=True, install_requires=open('requires/installation.txt').read(), extras_require={'curl': ['pycurl']}, tests_require=open('requires/testing.txt').read(), license='BSD', classifiers=CLASSIFIERS, zip_safe=True)
import setuptools CLASSIFIERS = ['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Communications', 'Topic :: Internet', 'Topic :: Software Development :: Libraries'] DESC = 'A low-level Amazon Web Services API client for Tornado' setuptools.setup(name='tornado-aws', version='0.5.0', description=DESC, long_description=open('README.rst').read(), author='Gavin M. Roy', author_email='[email protected]', url='http://tornado-aws.readthedocs.org', packages=['tornado_aws'], package_data={'': ['LICENSE', 'README.rst', 'requires/installation.txt']}, include_package_data=True, install_requires=open('requires/installation.txt').read(), tests_require=open('requires/testing.txt').read(), license='BSD', classifiers=CLASSIFIERS, zip_safe=True)
Tweak stars size on retina devices
(function () { function initTwinklingStars(devicePixelRatio) { particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5 / devicePixelRatio, random: true, anim: { enable: true, speed: 1, size_min: 0.5 / devicePixelRatio, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = function () { initTwinklingStars(window.devicePixelRatio / 1.5 || 1); document.body.className = ''; } window.onresize = function () { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = function () { return false; } window.onorientationchange = function () { document.body.scrollTop = 0; } }());
(function () { function initTwinklingStars() { particlesJS('stars', { particles: { number: { value: 180, density: { enable: true, value_area: 600 } }, color: { value: '#ffffff' }, shape: { type: 'circle' }, opacity: { value: 1, random: true, anim: { enable: true, speed: 3, opacity_min: 0 } }, size: { value: 1.5, random: true, anim: { enable: true, speed: 1, size_min: 0.5, sync: false } }, line_linked: { enable: false }, move: { enable: true, speed: 50, direction: 'none', random: true, straight: true, out_mode: 'bounce' } }, retina_detect: true }); } window.onload = function () { document.body.className = ''; initTwinklingStars(); } window.onresize = function () { clearTimeout(window.onResizeEnd); window.onResizeEnd = setTimeout(initTwinklingStars, 250); } window.ontouchmove = function () { return false; } window.onorientationchange = function () { document.body.scrollTop = 0; } }());
Use unique identifier name for ASGIApp type Due to collision with ASGIApp class decorator
__all__ = ["ASGIMiddleware"] import rollbar try: from starlette.types import ASGIApp as ASGIAppType, Receive, Scope, Send except ImportError: STARLETTE_INSTALLED = False else: STARLETTE_INSTALLED = True # Optional class annotations must be statically declared because # IDEs cannot infer type hinting for arbitrary dynamic code def ASGIApp(cls): async def _asgi_app(self, scope, receive, send): try: await self.app(scope, receive, send) except Exception: if scope["type"] == "http": rollbar.report_exc_info() raise cls._asgi_app = _asgi_app return cls if STARLETTE_INSTALLED is True: @ASGIApp class ASGIMiddleware: def __init__(self, app: ASGIAppType) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self._asgi_app(scope, receive, send) else: @ASGIApp class ASGIMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): await self._asgi_app(scope, receive, send) def _hook(request, data): data["framework"] = "asgi" rollbar.BASE_DATA_HOOK = _hook
__all__ = ["ASGIMiddleware"] import rollbar try: from starlette.types import ASGIApp, Receive, Scope, Send except ImportError: STARLETTE_INSTALLED = False else: STARLETTE_INSTALLED = True # Optional class annotations must be statically declared because # IDEs cannot infer type hinting for arbitrary dynamic code def ASGIApp(cls): async def _asgi_app(self, scope, receive, send): try: await self.app(scope, receive, send) except Exception: if scope["type"] == "http": rollbar.report_exc_info() raise cls._asgi_app = _asgi_app return cls if STARLETTE_INSTALLED is True: @ASGIApp class ASGIMiddleware: def __init__(self, app: ASGIApp) -> None: self.app = app async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await self._asgi_app(scope, receive, send) else: @ASGIApp class ASGIMiddleware: def __init__(self, app): self.app = app async def __call__(self, scope, receive, send): await self._asgi_app(scope, receive, send) def _hook(request, data): data["framework"] = "asgi" rollbar.BASE_DATA_HOOK = _hook
Fix wrong serviceLocator property name
<?php /** * @author Evgeny Shpilevsky <[email protected]> */ namespace EnliteMonolog\Service; use Monolog\Logger; use RuntimeException; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceLocatorInterface; trait MonologServiceAwareTrait { /** * @var Logger */ protected $monologService; /** * @var string */ protected $monologLoggerName = 'EnliteMonologService'; /** * @param Logger $monologService */ public function setMonologService(Logger $monologService) { $this->monologService = $monologService; } /** * @throws \RuntimeException * @return Logger */ public function getMonologService() { if (null === $this->monologService) { if ($this instanceof ServiceLocatorAwareInterface || method_exists($this, 'getServiceLocator')) { $this->monologService = $this->getServiceLocator()->get($this->monologLoggerName); } else { if (property_exists($this, 'serviceLocator') && $this->serviceLocator instanceof ServiceLocatorInterface ) { $this->monologService = $this->serviceLocator->get($this->monologLoggerName); } else { throw new RuntimeException('Service locator not found'); } } } return $this->monologService; } }
<?php /** * @author Evgeny Shpilevsky <[email protected]> */ namespace EnliteMonolog\Service; use Monolog\Logger; use RuntimeException; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceLocatorInterface; trait MonologServiceAwareTrait { /** * @var Logger */ protected $monologService; /** * @var string */ protected $monologLoggerName = 'EnliteMonologService'; /** * @param Logger $monologService */ public function setMonologService(Logger $monologService) { $this->monologService = $monologService; } /** * @throws \RuntimeException * @return Logger */ public function getMonologService() { if (null === $this->monologService) { if ($this instanceof ServiceLocatorAwareInterface || method_exists($this, 'getServiceLocator')) { $this->monologService = $this->getServiceLocator()->get($this->monologLoggerName); } else { if (property_exists($this, 'serviceLocator') && $this->monologService instanceof ServiceLocatorInterface ) { $this->monologService = $this->serviceLocator->get($this->monologLoggerName); } else { throw new RuntimeException('Service locator not found'); } } } return $this->monologService; } }
Allow parallelNode to accept cases of textual
package io.digdag.util; import com.fasterxml.jackson.databind.JsonNode; import io.digdag.client.config.Config; import io.digdag.client.config.ConfigException; public class ParallelControl { public static ParallelControl of(Config config) { return new ParallelControl(config); } private final boolean isParallel; private final int parallelLimit; private ParallelControl(Config config) { final JsonNode parallelNode = config.getInternalObjectNode().get("_parallel"); if (parallelNode == null) { // not specified, default this.isParallel = false; this.parallelLimit = 0; } else if (parallelNode.isBoolean() || parallelNode.isTextual()) { // _parallel: true/false // If _parallel is specified in subtasks (e.g. loop operators with parallel), // a variable ${..} is available, if set as variable ${..}, the value become text so that needs to accept here this.isParallel = config.get("_parallel", boolean.class, false); this.parallelLimit = 0; // no limit } else if (parallelNode.isObject()) { // _parallel: {limit: N} Config parallel = config.getNested("_parallel"); this.isParallel = true; // always true this.parallelLimit = parallel.get("limit", int.class); } else { // unknown format throw new ConfigException(String.format("Invalid _parallel format: %s", parallelNode.toString())); } } public boolean isParallel() { return isParallel; } public int getParallelLimit() { return parallelLimit; } }
package io.digdag.util; import com.fasterxml.jackson.databind.JsonNode; import io.digdag.client.config.Config; import io.digdag.client.config.ConfigException; public class ParallelControl { public static ParallelControl of(Config config) { return new ParallelControl(config); } private final boolean isParallel; private final int parallelLimit; private ParallelControl(Config config) { final JsonNode parallelNode = config.getInternalObjectNode().get("_parallel"); if (parallelNode == null) { // not specified, default this.isParallel = false; this.parallelLimit = 0; } else if (parallelNode.isBoolean()) { // _parallel: true/false this.isParallel = config.get("_parallel", boolean.class, false); this.parallelLimit = 0; // no limit } else if (parallelNode.isObject()) { // _parallel: {limit: N} Config parallel = config.getNested("_parallel"); this.isParallel = true; // always true this.parallelLimit = parallel.get("limit", int.class); } else { // unknown format throw new ConfigException(String.format("Invalid _parallel format: %s", parallelNode.toString())); } } public boolean isParallel() { return isParallel; } public int getParallelLimit() { return parallelLimit; } }
Add option to forcefully delete task and scale app
var qajaxWrapper = require("../helpers/qajaxWrapper"); var config = require("../config/config"); var AppDispatcher = require("../AppDispatcher"); var TasksEvents = require("../events/TasksEvents"); var TasksActions = { deleteTasks: function (appId, taskIds = []) { this.request({ method: "POST", data: { "ids": taskIds }, url: `${config.apiURL}v2/tasks/delete` }) .success(function () { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE, appId: appId, taskIds: taskIds }); }) .error(function (error) { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE_ERROR, data: error }); }); }, deleteTasksAndScale: function (appId, taskIds = [], force = false) { var url = `${config.apiURL}v2/tasks/delete?scale=true`; if (force) { url = url + "&force=true"; } this.request({ method: "POST", data: { "ids": taskIds }, url: url }) .success(function () { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE, appId: appId, taskIds: taskIds }); }) .error(function (error) { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE_ERROR, data: error }); }); }, request: qajaxWrapper }; module.exports = TasksActions;
var qajaxWrapper = require("../helpers/qajaxWrapper"); var config = require("../config/config"); var AppDispatcher = require("../AppDispatcher"); var TasksEvents = require("../events/TasksEvents"); var TasksActions = { deleteTasks: function (appId, taskIds = []) { this.request({ method: "POST", data: { "ids": taskIds }, url: `${config.apiURL}v2/tasks/delete` }) .success(function () { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE, appId: appId, taskIds: taskIds }); }) .error(function (error) { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE_ERROR, data: error }); }); }, deleteTasksAndScale: function (appId, taskIds = []) { this.request({ method: "POST", data: { "ids": taskIds }, url: `${config.apiURL}v2/tasks/delete?scale=true` }) .success(function () { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE, appId: appId, taskIds: taskIds }); }) .error(function (error) { AppDispatcher.dispatch({ actionType: TasksEvents.DELETE_ERROR, data: error }); }); }, request: qajaxWrapper }; module.exports = TasksActions;
Remove monkey patching in favor of inheritance for SpatialReference
"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
"""Spatial reference systems""" from osgeo import osr # Monkey patch SpatialReference since inheriting from SWIG classes is a hack def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return osr.SpatialReference.srid = property(srid) def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() osr.SpatialReference.wkt = property(wkt) def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() osr.SpatialReference.proj4 = property(proj4) def __repr__(self): return self.wkt osr.SpatialReference.__repr__ = __repr__ class SpatialReference(object): def __new__(cls, sref): sr = osr.SpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
Add pagination support for api('groups')->members
<?php namespace Gitlab\Api; class Groups extends AbstractApi { public function all($page = 1, $per_page = self::PER_PAGE) { return $this->get('groups', array( 'page' => $page, 'per_page' => $per_page )); } public function show($id) { return $this->get('groups/'.urlencode($id)); } public function create($name, $path) { return $this->post('groups', array( 'name' => $name, 'path' => $path )); } public function transfer($group_id, $project_id) { return $this->post('groups/'.urlencode($group_id).'/projects/'.urlencode($project_id)); } public function members($id, $page = 1, $per_page = self::PER_PAGE) { return $this->get('groups/'.urlencode($id).'/members', array( 'page=' => $page, 'per_page' => $per_page )); } public function addMember($group_id, $user_id, $access_level) { return $this->post('groups/'.urlencode($group_id).'/members', array( 'user_id' => $user_id, 'access_level' => $access_level )); } public function removeMember($group_id, $user_id) { return $this->delete('groups/'.urlencode($group_id).'/members/'.urlencode($user_id)); } }
<?php namespace Gitlab\Api; class Groups extends AbstractApi { public function all($page = 1, $per_page = self::PER_PAGE) { return $this->get('groups', array( 'page' => $page, 'per_page' => $per_page )); } public function show($id) { return $this->get('groups/'.urlencode($id)); } public function create($name, $path) { return $this->post('groups', array( 'name' => $name, 'path' => $path )); } public function transfer($group_id, $project_id) { return $this->post('groups/'.urlencode($group_id).'/projects/'.urlencode($project_id)); } public function members($id) { return $this->get('groups/'.urlencode($id).'/members'); } public function addMember($group_id, $user_id, $access_level) { return $this->post('groups/'.urlencode($group_id).'/members', array( 'user_id' => $user_id, 'access_level' => $access_level )); } public function removeMember($group_id, $user_id) { return $this->delete('groups/'.urlencode($group_id).'/members/'.urlencode($user_id)); } }
Set session variables, cleaned up code
Template.body.events({ "submit .results": function (event) { Session.set('searchingresults', false); Session.set('resultsloaded', false); var movie = document.querySelector('input[name="movie"]:checked').value; var id = document.querySelector('input[name="movie"]:checked').id; if (Movies.findOne({text: movie}) === undefined) { document.getElementById("info").setAttribute("class", "alert alert-success"); document.getElementById("info").innerHTML = '<p>Movie was successfully requested! Want to <a href="javascript:document.getElementById(\'search\').focus()" class="alert-link">search again?</a></p>'; document.getElementById("overview").innerHTML = ""; Meteor.call('addMovie', movie, id); Meteor.call('pushBullet', movie); return false; } else { document.getElementById("info").setAttribute("class", "alert alert-warning"); document.getElementById("info").innerHTML = '<p>Movie has alrady been requested! <a href="javascript:document.getElementById(\'search\').focus()" class="alert-link">Request another movie?</a></p>'; document.getElementById("overview").innerHTML = ""; return false; } } });
Template.results.events({ 'submit form': function(event){ var movie = document.querySelector('input[name="movie"]:checked').value; var id = document.querySelector('input[name="movie"]:checked').id; if (Movies.findOne({text: movie}) == undefined) { var mg = '<p>Movie was successfully requested! Want to <a href="javascript:document.getElementById(\'search\').focus()" class="alert-link">search again?</a></p>' document.getElementById("info").setAttribute("class", "alert alert-success"); document.getElementById("info").innerHTML = mg; var mg = "" document.getElementById("overview").innerHTML = mg; var list = document.getElementById("results"); while (list.firstChild) { list.removeChild(list.firstChild); } Meteor.call('addMovie', movie); Meteor.call('pushBullet', movie); return false; } else { var mg = '<p>Movie has alrady been requested! <a href="javascript:document.getElementById(\'search\').focus()" class="alert-link">Request another movie?</a></p>'; document.getElementById("info").setAttribute("class", "alert alert-warning"); document.getElementById("info").innerHTML = mg; var mg = "" document.getElementById("overview").innerHTML = mg; var list = document.getElementById("results"); while (list.firstChild) { list.removeChild(list.firstChild); } return false } }})
Add the declaration for the should cache class service
<?php namespace EdpSuperluminal; use Zend\Console\Request as ConsoleRequest; use Zend\Mvc\MvcEvent; /** * Create a class cache of all classes used. * * @package EdpSuperluminal */ class Module { /** * Attach the cache event listener * * @param MvcEvent $e */ public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); /** @var CacheBuilder $cacheBuilder */ $cacheBuilder = $serviceManager->get('EdpSuperluminal\CacheBuilder'); $eventManager = $e->getApplication()->getEventManager()->getSharedManager(); $eventManager->attach('Zend\Mvc\Application', 'finish', function (MvcEvent $e) use ($cacheBuilder) { $request = $e->getRequest(); if ($request instanceof ConsoleRequest || $request->getQuery()->get('EDPSUPERLUMINAL_CACHE', null) === null) { return; } $cacheBuilder->cache(ZF_CLASS_CACHE); }); } public function getServiceConfig() { return array( 'factories' => array( 'EdpSuperluminal\CacheCodeGenerator' => 'EdpSuperluminal\CacheCodeGeneratorFactory', 'EdpSuperluminal\CacheBuilder' => 'EdpSuperluminal\CacheBuilderFactory', 'EdpSuperluminal\ShouldCacheClass' => 'EdpSuperluminal\ShouldCacheClass\ShouldCacheClassSpecificationFactory', ) ); } }
<?php namespace EdpSuperluminal; use Zend\Console\Request as ConsoleRequest; use Zend\Mvc\MvcEvent; /** * Create a class cache of all classes used. * * @package EdpSuperluminal */ class Module { /** * Attach the cache event listener * * @param MvcEvent $e */ public function onBootstrap(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); /** @var CacheBuilder $cacheBuilder */ $cacheBuilder = $serviceManager->get('EdpSuperluminal\CacheBuilder'); $eventManager = $e->getApplication()->getEventManager()->getSharedManager(); $eventManager->attach('Zend\Mvc\Application', 'finish', function (MvcEvent $e) use ($cacheBuilder) { $request = $e->getRequest(); if ($request instanceof ConsoleRequest || $request->getQuery()->get('EDPSUPERLUMINAL_CACHE', null) === null) { return; } $cacheBuilder->cache(ZF_CLASS_CACHE); }); } public function getServiceConfig() { return array( 'factories' => array( 'EdpSuperluminal\CacheCodeGenerator' => 'EdpSuperluminal\CacheCodeGeneratorFactory', 'EdpSuperluminal\CacheBuilder' => 'EdpSuperluminal\CacheBuilderFactory', ) ); } }
Remove empty string from requirements list When we moved to Python 3 we used this simpler method to read the requirements file. However we need to remove the empty/Falsey elements from the list. This fixes the error: ``` Failed building wheel for molo.commenting ```
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst')) as f: readme = f.read() with open(os.path.join(here, 'requirements.txt')) as f: requires = [req for req in f.read().split('\n') if req] with open(os.path.join(here, 'requirements-dev.txt')) as f: requires_dev = [req for req in f.read().split('\n') if req] with open(os.path.join(here, 'VERSION')) as f: version = f.read().strip() setup(name='molo.commenting', version=version, description=('Comments helpers for sites built with Molo.'), long_description=readme, classifiers=[ "Programming Language :: Python", "Framework :: Django", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='Praekelt Foundation', author_email='[email protected]', url='http://github.com/praekelt/molo.commenting', license='BSD', keywords='praekelt, mobi, web, django', packages=find_packages(), include_package_data=True, zip_safe=False, namespace_packages=['molo'], install_requires=requires, tests_require=requires_dev, entry_points={})
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst')) as f: readme = f.read() with open(os.path.join(here, 'requirements.txt')) as f: requires = f.read().split('\n') with open(os.path.join(here, 'requirements-dev.txt')) as f: requires_dev = f.read().split('\n') with open(os.path.join(here, 'VERSION')) as f: version = f.read().strip() setup(name='molo.commenting', version=version, description=('Comments helpers for sites built with Molo.'), long_description=readme, classifiers=[ "Programming Language :: Python", "Framework :: Django", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='Praekelt Foundation', author_email='[email protected]', url='http://github.com/praekelt/molo.commenting', license='BSD', keywords='praekelt, mobi, web, django', packages=find_packages(), include_package_data=True, zip_safe=False, namespace_packages=['molo'], install_requires=requires, tests_require=requires_dev, entry_points={})
Comment out some boilerplate code, to prevent failures
"""" Boilerplate Adventure Author: Ignacio Avas ([email protected]) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): """Variables Adventure test""" def __init__(self, candidate_code, file_name='<inline>'): """Init the test""" super(TestOutput, self).__init__() self.candidate_code = candidate_code self.file_name = file_name def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() def runTest(self): """Makes a simple test of the output""" #code = compile(self.candidate_code, self.file_name, 'exec', optimize=0) #exec(code) self.fail("Test not implemented") class Adventure(BaseAdventure): """Boilerplate Adventure""" title = '<Insert Title Here>' @classmethod def test(cls, sourcefile): """Test against the provided file""" suite = unittest.TestSuite() raw_program = codecs.open(sourcefile).read() suite.addTest(TestOutput(raw_program, sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError()
"""" Boilerplate Adventure Author: Ignacio Avas ([email protected]) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): """Variables Adventure test""" def __init__(self, candidate_code, file_name='<inline>'): """Init the test""" super(TestOutput, self).__init__() self.candidate_code = candidate_code self.file_name = file_name def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() def runTest(self): """Makes a simple test of the output""" code = compile(self.candidate_code, self.file_name, 'exec', optimize=0) exec(code) class Adventure(BaseAdventure): """Boilerplate Adventure""" title = '<Insert Title Here>' @classmethod def test(cls, sourcefile): """Test against the provided file""" suite = unittest.TestSuite() raw_program = codecs.open(sourcefile).read() suite.addTest(TestOutput(raw_program, sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError()
Fix the registration page redirection
<?php function getReferralID() { global $_GET; if (empty($_GET['r'])) { return null; } return intval($_GET['r']); } function hasValidReferralData() { $referralID = getReferralID(); return ($referralID > 0); } function hasReferralCookie() { global $_COOKIE; $referralCookieKey = REFERING_COOKIENAME; return (!empty($_COOKIE[$referralCookieKey])); } function onValidReferralDataProvided($referralID) { global $_COOKIE; define('INSIDE', true); $_EnginePath = './'; include($_EnginePath . 'includes/constants.php'); if (hasReferralCookie()) { return; } $nowTimestamp = time(); $referralCookieTTLDays = 14; $referralCookieTTL = ($referralCookieTTLDays * TIME_DAY); setcookie( REFERING_COOKIENAME, $referralID, $nowTimestamp + $referralCookieTTL, '', GAMEURL_DOMAIN ); } function renderPage() { if (!hasValidReferralData()) { header('Location: login.php'); return; } $referralID = getReferralID(); onValidReferralDataProvided($referralID); header('Location: reg_mainpage.php'); } renderPage(); ?>
<?php function getReferralID() { global $_GET; if (empty($_GET['r'])) { return null; } return intval($_GET['r']); } function hasValidReferralData() { $referralID = getReferralID(); return ($referralID > 0); } function hasReferralCookie() { global $_COOKIE; $referralCookieKey = REFERING_COOKIENAME; return (!empty($_COOKIE[$referralCookieKey])); } function onValidReferralDataProvided($referralID) { global $_COOKIE; define('INSIDE', true); $_EnginePath = './'; include($_EnginePath . 'includes/constants.php'); if (hasReferralCookie()) { return; } $nowTimestamp = time(); $referralCookieTTLDays = 14; $referralCookieTTL = ($referralCookieTTLDays * TIME_DAY); setcookie( REFERING_COOKIENAME, $referralID, $nowTimestamp + $referralCookieTTL, '', GAMEURL_DOMAIN ); } function renderPage() { if (!hasValidReferralData()) { header('Location: login.php'); return; } $referralID = getReferralID(); onValidReferralDataProvided($referralID); header('Location: reg.php'); } renderPage(); ?>
Change JecpApllication class in JECP-SE
package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements WindowListener { private final ApplicationListener listener; private final JecpPaintPanel panel; public JecpApplication(ApplicationListener listener, int width, int height) { this.listener = listener; addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); listener.onStartApp(width, height); panel = new JecpPaintPanel(listener, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { listener.onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { listener.onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }
package com.annimon.jecp.se; import com.annimon.jecp.ApplicationListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.WindowConstants; /** * * @author aNNiMON */ public abstract class JecpApplication extends JFrame implements ApplicationListener, WindowListener { private final JecpPaintPanel panel; public JecpApplication(int width, int height) { addWindowListener(JecpApplication.this); setLocationByPlatform(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); onStartApp(width, height); panel = new JecpPaintPanel(this, width, height); add(panel); pack(); setVisible(true); } @Override public void windowClosing(WindowEvent e) { onDestroyApp(); } @Override public void windowDeactivated(WindowEvent e) { onPauseApp(); } @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }
Update spec to take in account null fields in context model
define(['backbone', 'cilantro', 'text!/mock/fields.json'], function (Backbone, c, fieldsJSON) { var fields = new Backbone.Collection(JSON.parse(fieldsJSON)); describe('FieldControl', function() { var control; describe('Base', function() { beforeEach(function() { control = new c.ui.FieldControl({ model: fields.models[0] }); control.render(); }); it('should have an field by default', function() { expect(control.get()).toEqual({ field: 30, value: null, operator: null }); }); it('should never clear the field attr', function() { control.clear(); expect(control.get()).toEqual({ field: 30, value: null, operator: null }); }); }); describe('w/ Number', function() { beforeEach(function() { control = new c.ui.FieldControl({ model: fields.models[0] }); control.render(); }); it('should coerce the value to a number', function() { control.set('value', '30'); expect(control.get('value')).toEqual(30); }); }); }); });
define(['backbone', 'cilantro', 'text!/mock/fields.json'], function (Backbone, c, fieldsJSON) { var fields = new Backbone.Collection(JSON.parse(fieldsJSON)); describe('FieldControl', function() { var control; describe('Base', function() { beforeEach(function() { control = new c.ui.FieldControl({ model: fields.models[0] }); control.render(); }); it('should have an field by default', function() { expect(control.get()).toEqual({field: 30}); }); it('should never clear the field attr', function() { control.clear(); expect(control.get()).toEqual({field: 30}); }); }); describe('w/ Number', function() { beforeEach(function() { control = new c.ui.FieldControl({ model: fields.models[0] }); control.render(); }); it('should coerce the value to a number', function() { control.set('value', '30'); expect(control.get('value')).toEqual(30); }); }); }); });
Add constraint from name method
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': DifferentConstraint # register your constraint here } # yapf: disable @classmethod def get_constraint(cls, constraint_data): if constraint_data['name'] in cls.CONSTRAINTS: return cls.CONSTRAINTS[constraint_data['name']]( param_dict=constraint_data['params'], params_checking=False ) raise UnsupportedConstraintTypeError(constraint_data) @classmethod def constraint_from_name(cls, constraint_name): return cls.CONSTRAINTS.get(constraint_name) class ConstraintManager(object): """ there should be one such object per rule being verified """ def __init__(self): self._actual_constraints = {} def __getitem__(self, constraint_data): constraint = self._actual_constraints.get(constraint_data['name']) if constraint is None: constraint_verifier = ConstraintRegistry.get_constraint(constraint_data) self._actual_constraints[constraint_data['name']] = constraint_verifier return self._actual_constraints[constraint_data['name']]
from whylog.constraints import DifferentConstraint, IdenticalConstraint, TimeConstraint from whylog.constraints.exceptions import UnsupportedConstraintTypeError class ConstraintRegistry(object): CONSTRAINTS = { 'identical': IdenticalConstraint, 'time': TimeConstraint, 'different': DifferentConstraint # register your constraint here } # yapf: disable @classmethod def get_constraint(cls, constraint_data): if constraint_data['name'] in cls.CONSTRAINTS: return cls.CONSTRAINTS[constraint_data['name']]( param_dict=constraint_data['params'], params_checking=False ) raise UnsupportedConstraintTypeError(constraint_data) class ConstraintManager(object): """ there should be one such object per rule being verified """ def __init__(self): self._actual_constraints = {} def __getitem__(self, constraint_data): constraint = self._actual_constraints.get(constraint_data['name']) if constraint is None: constraint_verifier = ConstraintRegistry.get_constraint(constraint_data) self._actual_constraints[constraint_data['name']] = constraint_verifier return self._actual_constraints[constraint_data['name']]
Handle a non-existent field in an array This was giving me an error, since I had several records for which a particular field was not defined. Since I use a schema-less DB (MongoDB), this field doesn't even exist with a null value. `data_get` performs an `array_key_exists` check before attempting to use `$part` as an index for the `$res` array. This entire method could actually be replaced with data_get for simplicity, since this is what Laravel uses internally to retrieve values in dot notation. ```php protected function extractCellValue($fieldName) { try { return data_get($this->src, $fieldName); } catch (Exception $e) { throw new RuntimeException( "Can't read '$fieldName' property from DataRow", 0, $e ); } } ```
<?php namespace Nayjest\Grids; use Exception; use RuntimeException; class ObjectDataRow extends DataRow { /** * @param string $fieldName * @return mixed * @throws Exception */ protected function extractCellValue($fieldName) { if (strpos($fieldName, '.') !== false) { $parts = explode('.', $fieldName); $res = $this->src; foreach ($parts as $part) { $res = data_get($res, $part); if ($res === null) { return $res; } } return $res; } else { try { return $this->src->{$fieldName}; } catch(Exception $e) { throw new RuntimeException( "Can't read '$fieldName' property from DataRow", 0, $e ); } } } }
<?php namespace Nayjest\Grids; use Exception; use RuntimeException; class ObjectDataRow extends DataRow { /** * @param string $fieldName * @return mixed * @throws Exception */ protected function extractCellValue($fieldName) { if (strpos($fieldName, '.') !== false) { $parts = explode('.', $fieldName); $res = $this->src; foreach ($parts as $part) { $res = is_object($res) ? $res->{$part} : $res[$part]; if ($res === null) { return $res; } } return $res; } else { try { return $this->src->{$fieldName}; } catch(Exception $e) { throw new RuntimeException( "Can't read '$fieldName' property from DataRow", 0, $e ); } } } }
Add hasSidebar to LoggedInView to use the drag gesture to reveal the menu
import { View, __, Sidebar, ViewManager, NavBar } from 'erste'; import MainView from '../main-view'; class LoggedInView extends View { constructor() { super(); this.navBar = new NavBar({ title: __('Welcome to beveteran'), hasMenuButton: true, hasBackButton: true }); this.hasSidebar = true; } onActivation() { if (cfg.PLATFORM == 'device') StatusBar.styleDefault(); } finderButtonTap(e) { var finderView = new FinderView(); finderView.vm = this.vm; this.vm.pull(finderView, true); }; hiderButtonTap(e) { var hinderView = new HinderView(); hinderView.vm = this.vm; this.vm.pull(hinderView, true); }; get events() { return { 'tap': { '.finder': this.finderButtonTap, '.hider': this.hiderButtonTap, } } } template() { return ` <view> ${this.navBar} <div class="logedin"> <div class="imgcontainer"> <img src="static/img/logo.png" alt="Avatar" class="logo"> </div> <div class="buttons"> <button type="button" class="hider"> be a hider verteran</button> <button type="button" class="finder"> be a finder verteran</button> </div> </div> </view> `; } } module.exports = LoggedInView;
import { View, __, Sidebar, ViewManager, NavBar } from 'erste'; import MainView from '../main-view'; class LoggedInView extends View { constructor() { super(); this.navBar = new NavBar({ title: __('Welcome to beveteran'), hasMenuButton: true, hasBackButton: true }); } onActivation() { if (cfg.PLATFORM == 'device') StatusBar.styleDefault(); } finderButtonTap(e) { var finderView = new FinderView(); finderView.vm = this.vm; this.vm.pull(finderView, true); }; hiderButtonTap(e) { var hinderView = new HinderView(); hinderView.vm = this.vm; this.vm.pull(hinderView, true); }; get events() { return { 'tap': { '.finder': this.finderButtonTap, '.hider': this.hiderButtonTap, } } } template() { return ` <view> ${this.navBar} <div class="logedin"> <div class="imgcontainer"> <img src="static/img/logo.png" alt="Avatar" class="logo"> </div> <div class="buttons"> <button type="button" class="hider"> be a hider verteran</button> <button type="button" class="finder"> be a finder verteran</button> </div> </div> </view> `; } } module.exports = LoggedInView;
Add x and y field for laralytics_custme table migration
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** * Class CreateLaralyticsCustomTable */ class CreateLaralyticsCustomTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('laralytics_custom', function (Blueprint $table) { $engine = Config::get('database.default'); $table->increments('id'); $table->integer('user_id')->index()->nullable(); $table->string('session', 250)->nullable(); $table->string('hash', 64)->index(); $table->string('host', 255)->index(); $table->string('path', 255); $table->string('version', 255)->index()->nullable(); $table->string('event', 64)->index(); $table->integer('x'); $table->integer('y'); $table->string('element', 255)->index()->nullable(); // Auto timestamp for postgreSQL and others if ($engine === 'pgsql') { $table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)')); } else { $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('laralytics_custom'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** * Class CreateLaralyticsCustomTable */ class CreateLaralyticsCustomTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('laralytics_custom', function (Blueprint $table) { $engine = Config::get('database.default'); $table->increments('id'); $table->integer('user_id')->index()->nullable(); $table->string('session', 250)->nullable(); $table->string('hash', 64)->index(); $table->string('host', 255)->index(); $table->string('path', 255); $table->string('version', 255)->index()->nullable(); $table->string('event', 64)->index(); $table->string('element', 255)->index()->nullable(); $table->text('data'); // Auto timestamp for postgreSQL and others if ($engine === 'pgsql') { $table->timestamp('created_at')->default(DB::raw('now()::timestamp(0)')); } else { $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP')); } }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('laralytics_custom'); } }
Change TerminalNotifier's test image to be a URL
<?php use BryanCrowe\Growl\Builder\TerminalNotifierBuilder; class TerminalNotifierBuilderTest extends PHPUnit_Framework_TestCase { public function setUp() { parent::setUp(); $this->TerminalNotifierBuilder = new TerminalNotifierBuilder(); } public function tearDown() { unset($this->TerminalNotifierBuilder); parent::tearDown(); } public function testBuild() { $options = [ 'title' => 'Hello', 'subtitle' => 'World', 'message' => 'Welcome', 'image' => 'http://www.example.com/example.jpg', 'contentImage' => 'http://www.example.com/hello.jpg', 'open' => 'http://www.example.com' ]; $expected = 'terminal-notifier -title Hello -subtitle World -message Welcome' . ' -appIcon http://www.example.com/example.jpg' . ' -contentImage http://www.example.com/hello.jpg' . ' -open http://www.example.com'; $result = $this->TerminalNotifierBuilder->build($options); $this->assertSame($expected, $result); $options = [ 'title' => 'Hello', 'message' => 'Welcome' ]; $expected = 'terminal-notifier -title Hello -message Welcome'; $result = $this->TerminalNotifierBuilder->build($options); $this->assertSame($expected, $result); } }
<?php use BryanCrowe\Growl\Builder\TerminalNotifierBuilder; class TerminalNotifierBuilderTest extends PHPUnit_Framework_TestCase { public function setUp() { parent::setUp(); $this->TerminalNotifierBuilder = new TerminalNotifierBuilder(); } public function tearDown() { unset($this->TerminalNotifierBuilder); parent::tearDown(); } public function testBuild() { $options = [ 'title' => 'Hello', 'subtitle' => 'World', 'message' => 'Welcome', 'image' => 'Mail', 'contentImage' => 'http://www.example.com/hello.jpg', 'open' => 'http://www.example.com' ]; $expected = 'terminal-notifier -title Hello -subtitle World -message Welcome' . ' -appIcon Mail -contentImage http://www.example.com/hello.jpg' . ' -open http://www.example.com'; $result = $this->TerminalNotifierBuilder->build($options); $this->assertSame($expected, $result); $options = [ 'title' => 'Hello', 'message' => 'Welcome' ]; $expected = 'terminal-notifier -title Hello -message Welcome'; $result = $this->TerminalNotifierBuilder->build($options); $this->assertSame($expected, $result); } }
Add timeout for requests to jenkins masters
var request = require('request').defaults({ timeout: 1000 }); var async = require('async'); function SuperMaster(masters){ this.cache = {}; this.masters = masters; // Initialize cache with empty list for each master masters.forEach((master) => { this.cache[master.name] = [] }); } SuperMaster.prototype.getJobs = function(callback){ var self = this; async.map(self.masters, (master, callback) => { // Issue request against each master request.get(master.endpoint + "/api/json", (err, res, body) => { var jobs; if(err || res.statusCode != 200 ){ if(res && res.statusCode != 200) err = new Error(res.statusMessage); console.warn("Request to", master.name, "failed.\nMessage:", err.message); jobs = self.cache[master.name]; // Set jobs from cache jobs.forEach((job) => { job.cached = true; }); }else{ jobs = JSON.parse(body).jobs; jobs.forEach((job) => { job.master = master.name; job.icon = master.icon || ""; }); // Update cached job list for master self.cache[master.name] = jobs; } callback(null, jobs); }); }, (err, jobs) => { callback(err, [].concat.apply([], jobs) || []); }); } module.exports = SuperMaster;
var request = require('request'); var async = require('async'); function SuperMaster(masters){ this.cache = {}; this.masters = masters; // Initialize cache with empty list for each master masters.forEach((master) => { this.cache[master.name] = [] }); } SuperMaster.prototype.getJobs = function(callback){ var self = this; async.map(self.masters, (master, callback) => { // Issue request against each master request.get(master.endpoint + "/api/json", (err, res, body) => { var jobs; if(err || res.statusCode != 200 ){ if(res && res.statusCode != 200) err = new Error(res.statusMessage); console.warn("Request to", master.name, "failed.\nMessage:", err.message); jobs = self.cache[master.name]; // Set jobs from cache jobs.forEach((job) => { job.cached = true; }); }else{ jobs = JSON.parse(body).jobs; jobs.forEach((job) => { job.master = master.name; job.icon = master.icon || ""; }); // Update cached job list for master self.cache[master.name] = jobs; } callback(null, jobs); }); }, (err, jobs) => { callback(err, [].concat.apply([], jobs) || []); }); } module.exports = SuperMaster;
Fix date parsing having wrong offset
from datetime import datetime import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') UTC = pytz.timezone('UTC') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return ELVIS_TIMEZONE.localize(datetime.fromtimestamp(seconds).astimezone( pytz.FixedOffset(-timezone_offset) ).replace(tzinfo=None)) return timestamp
from datetime import datetime, timedelta import pytz DATE_PREFIX = '/Date(' DATE_SUFFIX = ')/' ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn') def decode_elvis_timestamp(timestamp: str): """Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible""" str_timestamp = str(timestamp).strip() if str_timestamp.startswith(DATE_PREFIX) and str_timestamp.endswith(DATE_SUFFIX): milliseconds = str_timestamp[len(DATE_PREFIX):-len(DATE_SUFFIX)] timezone_offset = 0 try: if "+" in milliseconds: timezone_offset_string = milliseconds[milliseconds.index("+")+1:] milliseconds = milliseconds[:milliseconds.index("+")] if len(timezone_offset_string) == 4: timezone_offset = int(timezone_offset_string[:2])*60+int(timezone_offset_string[2:]) seconds = int(milliseconds) / 1000 except ValueError: return timestamp # Elvis Timezone offsets are relevant to Elvis natural timezone (Tallinn) return datetime.fromtimestamp(seconds).astimezone( ELVIS_TIMEZONE ) + timedelta(minutes=timezone_offset) return timestamp
Remove NipypeTester from doc generation. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1373 ead46cd0-7350-4e37-8683-fc4c6f79bf00
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from interfacedocgen import InterfaceHelpWriter package = 'nipype' outdir = os.path.join('interfaces','generated') docwriter = InterfaceHelpWriter(package) # Packages that should not be included in generated API docs. docwriter.package_skip_patterns += ['\.externals$', '\.utils$', '\.pipeline', '.\testing', ] # Modules that should not be included in generated API docs. docwriter.module_skip_patterns += ['\.version$', '\.interfaces\.afni$', '\.interfaces\.base$', '\.interfaces\.matlab$', '\.interfaces\.rest$', '\.interfaces\.pymvpa$', '\.interfaces\.traits', '\.pipeline\.alloy$', '\.pipeline\.s3_node_wrapper$', '.\testing', ] docwriter.class_skip_patterns += ['FSL', 'FS', 'Spm', 'Tester', 'Spec$', 'afni', 'Numpy' # NipypeTester raises an # exception when instantiated in # InterfaceHelpWriter.generate_api_doc 'NipypeTester', ] docwriter.write_api_docs(outdir) docwriter.write_index(outdir, 'gen', relative_to='interfaces') print '%d files written' % len(docwriter.written_modules)
#!/usr/bin/env python """Script to auto-generate interface docs. """ # stdlib imports import os import sys #***************************************************************************** if __name__ == '__main__': nipypepath = os.path.abspath('..') sys.path.insert(1,nipypepath) # local imports from interfacedocgen import InterfaceHelpWriter package = 'nipype' outdir = os.path.join('interfaces','generated') docwriter = InterfaceHelpWriter(package) # Packages that should not be included in generated API docs. docwriter.package_skip_patterns += ['\.externals$', '\.utils$', '\.pipeline', '.\testing', ] # Modules that should not be included in generated API docs. docwriter.module_skip_patterns += ['\.version$', '\.interfaces\.afni$', '\.interfaces\.base$', '\.interfaces\.matlab$', '\.interfaces\.rest$', '\.interfaces\.pymvpa$', '\.interfaces\.traits', '\.pipeline\.alloy$', '\.pipeline\.s3_node_wrapper$', '.\testing', ] docwriter.class_skip_patterns += ['FSL', 'FS', 'Spm', 'Tester', 'Spec$', 'afni', 'Numpy' ] docwriter.write_api_docs(outdir) docwriter.write_index(outdir, 'gen', relative_to='interfaces') print '%d files written' % len(docwriter.written_modules)
Use try-with-resources to close as application code should.
package com.paritytrading.nassau.binaryfile; import static com.paritytrading.nassau.binaryfile.BinaryFILEStatus.*; import static java.util.Arrays.*; import static org.junit.Assert.*; import com.paritytrading.nassau.Messages; import com.paritytrading.nassau.Strings; import java.io.InputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BinaryFILEReaderTest { private InputStream stream; private Messages<String> messages; @Before public void setUp() throws Exception { stream = getClass().getResourceAsStream("/binaryfile.dat"); messages = new Messages<>(Strings.MESSAGE_PARSER); } @After public void tearDown() throws Exception { stream.close(); } @Test public void readStream() throws Exception { try (BinaryFILEReader reader = new BinaryFILEReader(stream, messages)) { while (reader.read() >= 0); } assertEquals(asList("foo", "bar", "baz", "quux", ""), messages.collect()); } @Test public void readStreamWithStatusListener() throws Exception { BinaryFILEStatus status = new BinaryFILEStatus(); BinaryFILEStatusParser parser = new BinaryFILEStatusParser(messages, status); try (BinaryFILEReader reader = new BinaryFILEReader(stream, parser)) { while (reader.read() >= 0); } assertEquals(asList("foo", "bar", "baz", "quux"), messages.collect()); assertEquals(asList(new EndOfSession()), status.collect()); } }
package com.paritytrading.nassau.binaryfile; import static com.paritytrading.nassau.binaryfile.BinaryFILEStatus.*; import static java.util.Arrays.*; import static org.junit.Assert.*; import com.paritytrading.nassau.Messages; import com.paritytrading.nassau.Strings; import java.io.InputStream; import org.junit.After; import org.junit.Before; import org.junit.Test; public class BinaryFILEReaderTest { private InputStream stream; private Messages<String> messages; @Before public void setUp() throws Exception { stream = getClass().getResourceAsStream("/binaryfile.dat"); messages = new Messages<>(Strings.MESSAGE_PARSER); } @After public void tearDown() throws Exception { stream.close(); } @Test public void readStream() throws Exception { BinaryFILEReader reader = new BinaryFILEReader(stream, messages); while (reader.read() >= 0); assertEquals(asList("foo", "bar", "baz", "quux", ""), messages.collect()); } @Test public void readStreamWithStatusListener() throws Exception { BinaryFILEStatus status = new BinaryFILEStatus(); BinaryFILEStatusParser parser = new BinaryFILEStatusParser(messages, status); BinaryFILEReader reader = new BinaryFILEReader(stream, parser); while (reader.read() >= 0); assertEquals(asList("foo", "bar", "baz", "quux"), messages.collect()); assertEquals(asList(new EndOfSession()), status.collect()); } }
Update flake8 requirement from <3.6.0,>=3.5.0 to >=3.5.0,<3.8.0 Updates the requirements on [flake8](https://gitlab.com/pycqa/flake8) to permit the latest version. - [Release notes](https://gitlab.com/pycqa/flake8/tags) - [Commits](https://gitlab.com/pycqa/flake8/compare/3.5.0...3.7.7) Signed-off-by: dependabot[bot] <[email protected]>
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.9.1", author = "OpenFisca Team", author_email = "[email protected]", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >=27.0,<32.0", ], extras_require = { "dev": [ "autopep8 == 1.4.0", "flake8 >=3.5.0,<3.8.0", "flake8-print", "pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name = "OpenFisca-Country-Template", version = "3.9.1", author = "OpenFisca Team", author_email = "[email protected]", classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description = "OpenFisca tax and benefit system for Country-Template", keywords = "benefit microsimulation social tax", license ="http://www.fsf.org/licensing/licenses/agpl-3.0.html", url = "https://github.com/openfisca/country-template", include_package_data = True, # Will read MANIFEST.in data_files = [ ("share/openfisca/openfisca-country-template", ["CHANGELOG.md", "LICENSE", "README.md"]), ], install_requires = [ "OpenFisca-Core[web-api] >=27.0,<32.0", ], extras_require = { "dev": [ "autopep8 == 1.4.0", "flake8 >= 3.5.0, < 3.6.0", "flake8-print", "pycodestyle >= 2.3.0, < 2.4.0", # To avoid incompatibility with flake ] }, packages=find_packages(), )
Fix breaking changes regarding symfony 5
<?php namespace App\Exceptions; use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * @param \Throwable $exception * @return void * * @throws \Exception */ public function report(Throwable $exception) { parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Throwable $exception * @return \Symfony\Component\HttpFoundation\Response * * @throws \Throwable */ public function render($request, Throwable $exception) { return parent::render($request, $exception); } /** * Convert an authentication exception into a response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response */ protected function unauthenticated($request, AuthenticationException $exception) { return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(url('/login')); } }
<?php namespace App\Exceptions; use Exception; use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $exception * @return void */ public function report(Exception $exception) { parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return parent::render($request, $exception); } /** * Convert an authentication exception into a response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response */ protected function unauthenticated($request, AuthenticationException $exception) { return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(url('/login')); } }
Fix traceback because outputter expects data in {'host', data.. } format
''' Execute overstate functions ''' # Import salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' stage_num = 0 overstate = salt.overstate.OverState(__opts__, env, os_fn) for stage in overstate.stages_iter(): if isinstance(stage, dict): # This is highstate data print('Stage execution results:') for key, val in stage.items(): salt.output.display_output( {'local': {key: val}}, 'highstate', opts=__opts__) elif isinstance(stage, list): # This is a stage if stage_num == 0: print('Executing the following Over State:') else: print('Executed Stage:') salt.output.display_output(stage, 'overstatestage', opts=__opts__) stage_num += 1 return overstate.over_run def show_stages(env='base', os_fn=None): ''' Display the stage data to be executed ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) salt.output.display_output( overstate.over, 'overstatestage', opts=__opts__) return overstate.over
''' Execute overstate functions ''' # Import salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' stage_num = 0 overstate = salt.overstate.OverState(__opts__, env, os_fn) for stage in overstate.stages_iter(): if isinstance(stage, dict): # This is highstate data print('Stage execution results:') for key, val in stage.items(): salt.output.display_output( {key: val}, 'highstate', opts=__opts__) elif isinstance(stage, list): # This is a stage if stage_num == 0: print('Executing the following Over State:') else: print('Executed Stage:') salt.output.display_output(stage, 'overstatestage', opts=__opts__) stage_num += 1 return overstate.over_run def show_stages(env='base', os_fn=None): ''' Display the stage data to be executed ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) salt.output.display_output( overstate.over, 'overstatestage', opts=__opts__) return overstate.over
Change JS parser to only look for 200 success code not the actual "OK". Oddly, in production, Chrome returns request.status as 'parsererror' rather than "OK", which is what we get when running against a dev server. The 'parseerror' is actually fairly reasonable -- we send back JSON with our script-buster prefix of })]. Change on 2016/09/23 by mgainer <[email protected]> ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=134080221
var XSSI_PREFIX = ")]}'"; function parseJson(s) { return JSON.parse(s.replace(XSSI_PREFIX, "")); } $(function(){ $('div[data-delete-url]').each(function(index, element){ var groupName = $(element).data('group-name'); var button = $('<button id="delete-' + groupName + '" ' + 'class="gcb-list__icon gcb-delete-student-group ' + 'delete-button gcb-list__icon--rowhover material-icons">' + 'delete</button>') var deleteUrl = $(element).data('delete-url'); button.click(function(){ if (confirm('You are about to delete this group. Really proceed?')) { $.ajax({ url: deleteUrl, method: 'DELETE', error: function(response) { // Here, we are re-using the OEditor style delete handler, so // we need to cope with a CB-encoded response style. if (response.status == 200) { var payload = parseJson(response.responseText); if (payload.status == 200 && payload.message == "Deleted.") { location.reload(); } else { cbShowMsgAutoHide('Deletion failed: ' + payload.message); } } else { cbShowMsgAutoHide('Deletion failed: ' + response.responseText) } }, success: function() { location.reload(); } }); } }); $(element).append(button) }); });
var XSSI_PREFIX = ")]}'"; function parseJson(s) { return JSON.parse(s.replace(XSSI_PREFIX, "")); } $(function(){ $('div[data-delete-url]').each(function(index, element){ var groupName = $(element).data('group-name'); var button = $('<button id="delete-' + groupName + '" ' + 'class="gcb-list__icon gcb-delete-student-group ' + 'delete-button gcb-list__icon--rowhover material-icons">' + 'delete</button>') var deleteUrl = $(element).data('delete-url'); button.click(function(){ if (confirm('You are about to delete this group. Really proceed?')) { $.ajax({ url: deleteUrl, method: 'DELETE', error: function(response) { // Here, we are re-using the OEditor style delete handler, so // we need to cope with a CB-encoded response style. if (response.status == 200 && response.statusText == "OK") { var payload = parseJson(response.responseText); if (payload.status == 200 && payload.message == "Deleted.") { location.reload(); } else { cbShowMsgAutoHide('Deletion failed: ' + payload.message); } } else { cbShowMsgAutoHide('Deletion failed: ' + response.responseText) } }, success: function() { location.reload(); } }); } }); $(element).append(button) }); });
Fix React missing key iterator warning
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { logoutUser } from '../../redux/actions'; const NavBar = ({ isAuthenticated, logoutUser }) => ( <ul className="navbar"> <li key={0} className="navbar__link"><Link to="/">Home</Link></li> { isAuthenticated && [ <li key={1} className="navbar__link"><Link to="/history">History</Link></li>, <li key={2} className="navbar__link"><Link to="/history/april">April</Link></li>, <li key={3} className="navbar__link"><Link to="/stopwatch">Stopwatch</Link></li> ] } { !isAuthenticated && [ <li key={4} className="navbar__link"><Link to="/signup">Signup</Link></li>, <li key={5} className="navbar__link"> <Link to="/login">Login</Link> </li> ] } { isAuthenticated && <li key={6} className="navbar__link"> <button onClick={ logoutUser }>Logout</button> </li> } </ul> ); export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }), { logoutUser } )(NavBar);
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { logoutUser } from '../../redux/actions'; const NavBar = ({ isAuthenticated, logoutUser }) => ( <ul className="navbar"> <li className="navbar__link"><Link to="/">Home</Link></li> { isAuthenticated && [ <li className="navbar__link"><Link to="/history">History</Link></li>, <li className="navbar__link"><Link to="/history/april">April</Link></li>, <li className="navbar__link"><Link to="/stopwatch">Stopwatch</Link></li> ] } { !isAuthenticated && [ <li className="navbar__link"><Link to="/signup">Signup</Link></li>, <li className="navbar__link"> <Link to="/login">Login</Link> </li> ] } { isAuthenticated && <li className="navbar__link"> <button onClick={ logoutUser }>Logout</button> </li> } </ul> ); export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }), { logoutUser } )(NavBar);
Remove now unnecessary "load" event listener
export default (shower) => { const { container } = shower; const { fullModeClass, listModeClass } = shower.options; if (container.classList.contains(fullModeClass)) { shower.enterFullMode(); } else { container.classList.add(listModeClass); } const getScale = () => { const maxRatio = Math.max( container.offsetWidth / window.innerWidth, container.offsetHeight / window.innerHeight, ); return `scale(${1 / maxRatio})`; }; const updateScale = () => { container.style.transform = shower.isFullMode ? getScale() : ''; }; const updateModeView = () => { if (shower.isFullMode) { container.classList.remove(listModeClass); container.classList.add(fullModeClass); } else { container.classList.remove(fullModeClass); container.classList.add(listModeClass); } updateScale(); if (shower.isFullMode) return; const slide = shower.activeSlide; if (slide) { slide.element.scrollIntoView({ block: 'center' }); } }; shower.addEventListener('start', updateModeView); shower.addEventListener('modechange', updateModeView); shower.addEventListener('slidechange', () => { if (shower.isFullMode) return; const slide = shower.activeSlide; slide.element.scrollIntoView({ block: 'nearest' }); }); window.addEventListener('resize', updateScale); };
export default (shower) => { const { container } = shower; const { fullModeClass, listModeClass } = shower.options; if (container.classList.contains(fullModeClass)) { shower.enterFullMode(); } else { container.classList.add(listModeClass); } const getScale = () => { const maxRatio = Math.max( container.offsetWidth / window.innerWidth, container.offsetHeight / window.innerHeight, ); return `scale(${1 / maxRatio})`; }; const updateScale = () => { container.style.transform = shower.isFullMode ? getScale() : ''; }; const updateModeView = () => { if (shower.isFullMode) { container.classList.remove(listModeClass); container.classList.add(fullModeClass); } else { container.classList.remove(fullModeClass); container.classList.add(listModeClass); } updateScale(); if (shower.isFullMode) return; const slide = shower.activeSlide; if (slide) { slide.element.scrollIntoView({ block: 'center' }); } }; shower.addEventListener('start', updateModeView); shower.addEventListener('modechange', updateModeView); shower.addEventListener('slidechange', () => { if (shower.isFullMode) return; const slide = shower.activeSlide; slide.element.scrollIntoView({ block: 'nearest' }); }); window.addEventListener('resize', updateScale); window.addEventListener('load', updateScale); };
Fix complex case to use syntax "domain.com/test/*": { path: './directory', target: '[1]' }
var nodeStatic = require('node-static'); var DispatchTable = require('../DispatchTable'); var regexpHelper = require('../regexpHelper'); module.exports = { middleware: function(config) { if (!config.static) return; return new DispatchTable({ config: config.static, requestHandler: function(req, res, next, target) { var fileServer = target.server; target = target.target; target = target.replace('[path]', req.url); req.url = regexpHelper(target, req.hostMatch, req.pathMatch); fileServer.serve(req, res, function(e, serveRes) { if (e && (e.status === 404)) { // If the file wasn't found var promise = fileServer.serveFile('/404.html', 404, {}, req, res); promise.on('error', function(err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write(''); res.end(); }); } }); }, entryParser: function(entryKey, entry) { return [entryKey, {server: new nodeStatic.Server(entry.path || entry), target: entry.target || "[path]"}]; }, port: config.port }); } };
var nodeStatic = require('node-static'); var DispatchTable = require('../DispatchTable'); var regexpHelper = require('../regexpHelper'); module.exports = { middleware: function(config) { if (!config.static) return; return new DispatchTable({ config: config.static, requestHandler: function(req, res, next, target) { var fileServer = target.server; console.log(req.url); target = target.target; console.log(target); target = target.replace('[path]', req.url); req.url = regexpHelper(target, req.hostMatch, req.pathMatch); fileServer.serve(req, res, function(e, serveRes) { if (e && (e.status === 404)) { // If the file wasn't found var promise = fileServer.serveFile('/404.html', 404, {}, req, res); promise.on('error', function(err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.write(''); res.end(); }); } }); }, entryParser: function(entryKey, entry) { var entrySplit = entry.split(':'); return [entryKey, {server: new nodeStatic.Server(entrySplit[0]), target: entrySplit[1]||"[path]"}]; }, port: config.port }); } };