text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Switch from csso justDoIt to minify because of deprecation notice
var fs = require('fs'); var path = require('path'); var csso = require('csso'); var autoprefixer = require('autoprefixer'); var UglifyJS = require('uglify-js'); var inlineCSS = function(cssPath) { var css = fs.readFileSync(path.join(__dirname, cssPath), 'utf-8'); css = csso.minify(css, false); css = autoprefixer.process(css).css; return css; }; var inlineJS = function(jsPath) { var result = UglifyJS.minify(path.join(__dirname, jsPath)); return result.code; }; module.exports = { opensans: inlineCSS('../assets/styles/opensans.css'), icomoon: inlineCSS('../assets/styles/icomoon.css'), bootstrap: inlineCSS('../assets/styles/bootstrap.min.css'), global: inlineCSS('../assets/styles/global.css'), profile: inlineCSS('../assets/styles/profile.css'), style: inlineCSS('../assets/styles/style.css'), saveAs: inlineJS('../node_modules/browser-saveas/index.js'), smoothScroll: inlineJS('../node_modules/smooth-scroll/dist/js/smooth-scroll.min.js'), emailScramble: inlineJS('../node_modules/email-scramble/email-scramble.js'), script: inlineJS('../assets/scripts/script.js') };
var fs = require('fs'); var path = require('path'); var csso = require('csso'); var autoprefixer = require('autoprefixer'); var UglifyJS = require('uglify-js'); var inlineCSS = function(cssPath) { var css = fs.readFileSync(path.join(__dirname, cssPath), 'utf-8'); css = csso.justDoIt(css, false); css = autoprefixer.process(css).css; return css; }; var inlineJS = function(jsPath) { var result = UglifyJS.minify(path.join(__dirname, jsPath)); return result.code; }; module.exports = { opensans: inlineCSS('../assets/styles/opensans.css'), icomoon: inlineCSS('../assets/styles/icomoon.css'), bootstrap: inlineCSS('../assets/styles/bootstrap.min.css'), global: inlineCSS('../assets/styles/global.css'), profile: inlineCSS('../assets/styles/profile.css'), style: inlineCSS('../assets/styles/style.css'), saveAs: inlineJS('../node_modules/browser-saveas/index.js'), smoothScroll: inlineJS('../node_modules/smooth-scroll/dist/js/smooth-scroll.min.js'), emailScramble: inlineJS('../node_modules/email-scramble/email-scramble.js'), script: inlineJS('../assets/scripts/script.js') };
Fix a bug introduced by fixing a bug that always execute eventlet's monkey_patch
"""Import a Python object made by compiling a Mochi file. """ import os from mochi.core import init, pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name) init()
"""Import a Python object made by compiling a Mochi file. """ import os from mochi.core import pyc_compile_monkeypatch def get_function(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the imported function. """ return getattr(get_module(name, file_path), name) def get_module(name, file_path): """Python function from Mochi. Compiles a Mochi file to Python bytecode and returns the Python module. """ base_path = os.path.dirname(file_path) mochi_name = os.path.join(base_path, name + '.mochi') py_name = os.path.join(base_path, name + '.pyc') pyc_compile_monkeypatch(mochi_name, py_name) return __import__(name)
Save all opts in this.opts
'use strict'; class Keyv { constructor(opts) { this.opts = opts || {}; this.opts.store = this.opts.store || new Map(); } get(key) { return Promise.resolve(this.opts.store.get(key)).then(data => { if (!data) { return undefined; } if (!this.opts.store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return this.opts.store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { let set; if (this.opts.store.ttlSupport) { set = this.opts.store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = this.opts.store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { return Promise.resolve(this.opts.store.delete(key)); } } module.exports = Keyv;
'use strict'; class Keyv { constructor(opts) { opts = opts || {}; this.store = opts.store || new Map(); } get(key) { return Promise.resolve(this.store.get(key)).then(data => { if (!data) { return undefined; } if (!this.store.ttlSupport && Date.now() > data.expires) { this.delete(key); return undefined; } return this.store.ttlSupport ? data : data.value; }); } set(key, value, ttl) { let set; if (this.store.ttlSupport) { set = this.store.set(key, value, ttl); } else { const expires = (typeof ttl === 'number') ? (Date.now() + ttl) : undefined; const data = { value, expires }; set = this.store.set(key, data); } return Promise.resolve(set).then(() => value); } delete(key) { return Promise.resolve(this.store.delete(key)); } } module.exports = Keyv;
Load react-devtools in dev env only
//electron entry-point var app = require('electron').app; var BrowserWindow = require('electron').BrowserWindow; var path = require( "path" ); if (process.env.NODE_ENV === 'development') { require('electron-debug')(); // eslint-disable-line global-require } app.on('ready',function() { if(process.env.NODE_ENV === 'development') { const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS; var installExtension = require('electron-devtools-installer').default; installExtension(REACT_DEVELOPER_TOOLS) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)); } var mainWindow = new BrowserWindow({ width: 1200, height: 600 }); mainWindow.loadURL('file://' + __dirname + '/src/index-electron.html'); mainWindow.webContents.on('did-finish-load', () => { mainWindow.show(); mainWindow.focus(); }); mainWindow.on('closed', () => { mainWindow = null; }); if (process.env.NODE_ENV === 'development') { mainWindow.openDevTools(); } });
//electron entry-point const REACT_DEVELOPER_TOOLS = require('electron-devtools-installer').REACT_DEVELOPER_TOOLS; var installExtension = require('electron-devtools-installer').default; var app = require('electron').app; var BrowserWindow = require('electron').BrowserWindow; var path = require( "path" ); if (process.env.NODE_ENV === 'development') { require('electron-debug')(); // eslint-disable-line global-require } app.on('ready',function() { installExtension(REACT_DEVELOPER_TOOLS) .then((name) => console.log(`Added Extension: ${name}`)) .catch((err) => console.log('An error occurred: ', err)); var mainWindow = new BrowserWindow({ width: 1200, height: 600 }); mainWindow.loadURL('file://' + __dirname + '/src/index-electron.html'); mainWindow.webContents.on('did-finish-load', () => { mainWindow.show(); mainWindow.focus(); }); mainWindow.on('closed', () => { mainWindow = null; }); if (process.env.NODE_ENV === 'development') { mainWindow.openDevTools(); } });
Revert "Speed up non-existent class detection by not using exceptions" This reverts commit 5f79bf46ceb3644b69bdb100139d537c21b9da85.
<?php class PostgresDbWrapper extends PostgresDb { /** * Execute where method with the specified episode and season numbers * * @param string|int|\DB\Episode $s Season, or array with keys season & episode * @param string|int|null $e Episode, optional if $s is an array * * @return self */ public function whereEp($s, $e = null){ if (!isset($e)){ parent::where('season', $s->season); parent::where('episode', $s->episode); } else { parent::where('season', $s); parent::where('episode', $e); } return $this; } public $query_count = 0; private $_nonexistantClassCache = array(); /** * @param PDOStatement $stmt Statement to execute * * @return bool|array|object[] */ protected function _execStatement($stmt){ $className = $this->tableNameToClassName(); if (isset($className) && empty($this->_nonexistantClassCache[$className])){ try { if (!class_exists("\\DB\\$className")) throw new Exception(); $this->setClass("\\DB\\$className"); } catch (Exception $e){ $this->_nonexistantClassCache[$className] = true; } } $this->query_count++; return parent::_execStatement($stmt); } }
<?php class PostgresDbWrapper extends PostgresDb { /** * Execute where method with the specified episode and season numbers * * @param string|int|\DB\Episode $s Season, or array with keys season & episode * @param string|int|null $e Episode, optional if $s is an array * * @return self */ public function whereEp($s, $e = null){ if (!isset($e)){ parent::where('season', $s->season); parent::where('episode', $s->episode); } else { parent::where('season', $s); parent::where('episode', $e); } return $this; } public $query_count = 0; private $_nonexistantClassCache = array(); /** * @param PDOStatement $stmt Statement to execute * * @return bool|array|object[] */ protected function _execStatement($stmt){ $className = $this->tableNameToClassName(); if (isset($className) && empty($this->_nonexistantClassCache[$className])){ if (!class_exists("\\DB\\$className")) $this->_nonexistantClassCache[$className] = true; else $this->setClass("\\DB\\$className"); } $this->query_count++; return parent::_execStatement($stmt); } }
Sort subtitles and prevent duplicates
const Extractor = remote.require('./browser/index.js'); const Subtitles = remote.require('./browser/model/Subtitle.js'); const shell = remote.shell; app.controller('SubtitleListController', ['$scope', '$routeParams', function ($scope, $routeParams) { function retrieveSubtitles() { return Subtitles .chain() .filter({serieid: $routeParams.serieId}) .sortBy('text') .value(); } $scope.subtitles = retrieveSubtitles(); $scope.loading = true; $scope.open = function(url) { shell.openExternal(url); }; Extractor($routeParams.serieId).then(results => { $scope.loading = false; if(results[0].serie_id != $routeParams.serieId) return; results.forEach(result => { result.subtitles.forEach(function(item) { var existent = Subtitles.find({ text: item.text }); if(!existent) Subtitles.push({ serieid: result.serie_id, text: item.text, url: item.url, source: item.source }); }); }); $scope.subtitles = retrieveSubtitles(); $scope.$apply(); }).catch(error => { console.log(error); }); }]);
const Extractor = remote.require('./browser/index.js'); const Subtitles = remote.require('./browser/model/Subtitle.js'); const shell = remote.shell; app.controller('SubtitleListController', ['$scope', '$routeParams', function ($scope, $routeParams) { $scope.subtitles = Subtitles.filter({serieid: $routeParams.serieId}); $scope.loading = true; $scope.open = function(url) { shell.openExternal(url); }; Extractor($routeParams.serieId).then(results => { $scope.loading = false; if(results[0].serie_id != $routeParams.serieId) return; results.forEach(result => { result.subtitles.forEach(function(item) { var existent = Subtitles.find({ serieid: $routeParams.serieId, text: item.text, url: item.url }); if(!existent) Subtitles.push({ serieid: result.serie_id, text: item.text, url: item.url, source: item.source }); }); }); $scope.subtitles = Subtitles.filter({serieid: $routeParams.serieId}); $scope.$apply(); }).catch(error => { console.log(error); }); }]);
Use the new CuraEngine GCode protocol instead of temp files.
from UM.Mesh.MeshWriter import MeshWriter from UM.Logger import Logger from UM.Application import Application import io class GCodeWriter(MeshWriter): def __init__(self): super().__init__() self._gcode = None def write(self, file_name, storage_device, mesh_data): if 'gcode' in file_name: scene = Application.getInstance().getController().getScene() gcode_list = getattr(scene, 'gcode_list') if gcode_list: f = storage_device.openFile(file_name, 'wt') Logger.log('d', "Writing GCode to file %s", file_name) for gcode in gcode_list: f.write(gcode) storage_device.closeFile(f) return True return False
from UM.Mesh.MeshWriter import MeshWriter from UM.Logger import Logger import io class GCodeWriter(MeshWriter): def __init__(self): super().__init__() self._gcode = None def write(self, file_name, storage_device, mesh_data): if 'gcode' in file_name: gcode = getattr(mesh_data, 'gcode', False) if gcode: f = storage_device.openFile(file_name, 'wt') Logger.log('d', "Writing GCode to file %s", file_name) f.write(gcode) storage_device.closeFile(f) return True return False
fix: Make prettier output of logs
import moment from 'moment'; import React, { PropTypes } from 'react'; import { get, map } from 'lodash'; import './ProjectDetails.styl'; const ProjectDetails = ({ project }) => ( <div className="ProjectDetails"> <h1>{get(project.owner, 'name')} / {project.name}</h1> <h2>Last deployment</h2> {project.lastDeploy && <em>{get(project.lastDeploy, 'shortRef')} - {moment(get(project.lastDeploy, 'finishedAt')).fromNow()}</em> } {map(project.lastDeploy.taskResults, task => ( <div> <h3>{task.taskType}</h3> {map(task.result, ({ error, stdout, exitCode }, key) => ( <code> $ <strong>{key}</strong> <span title="Exit code">({exitCode})</span> <pre>{stdout || error}</pre> </code> ))} </div> ))} </div> ); ProjectDetails.propTypes = { project: PropTypes.object.isRequired, }; export default ProjectDetails;
import moment from 'moment'; import React, { PropTypes } from 'react'; import { get, map } from 'lodash'; import './ProjectDetails.styl'; const ProjectDetails = ({ project }) => ( <div className="ProjectDetails"> <h1>{get(project.owner, 'name')} / {project.name}</h1> <h2>Last deployment</h2> {project.lastDeploy && <em>{get(project.lastDeploy, 'shortRef')} - {moment(get(project.lastDeploy, 'finishedAt')).fromNow()}</em> } {map(project.lastDeploy.taskResults, task => ( <div> <h3>{task.taskType}</h3> <pre><code>{JSON.stringify(task.result, null, 2)}</code></pre> </div> ))} </div> ); ProjectDetails.propTypes = { project: PropTypes.object.isRequired, }; export default ProjectDetails;
Complete dependencies, get a hold of db obj
import { ref } from 'config/constants' function saveToDucks (duck) { const duckId = ref.child('ducks').push().key() // not pushing anything, // returns a reference to // specific endpoint // spread operator creates a brand new obj // which has all of the properties of duck // as well as our new duckId on it. // So it adds duckId to the object. const duckPromise = ref.child(`ducks/${duckId}`).set({...duck, duckId}) return { duckId, duckPromise } } function saveToUsersDucks (duck, duckId) {} function saveLikeCount (duckId) {} function saveDuck (duck) { const { duckId, duckPromise } = saveToDucks(duck) return Promise.all([ duckPromise, saveToUsersDucks(duck, duckId), saveLikeCount(duckId), ]).then(() => ({...duck, duckId})) }
import { ref } from 'config/constants' function saveToDucks (duck) { const duckId = ref.child('ducks').push().key() // not pushing anything, // returns a reference to // specific endpoint } function saveToUsersDucks (duck, duckId) {} function saveLikeCount (duckId) {} function saveDuck (duck) { const { duckId, duckPromise } = saveToDucks(duck) return Promise.all([ duckPromise, saveToUsersDucks(duck, duckId), saveLikeCount(duckId), ]).then(() => ({...duck, duckId})) }
Reformat "Command not found" error output.
<?php /** * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Request; /** * Generic command */ class GenericCommand extends SystemCommand { /**#@+ * {@inheritdoc} */ protected $name = 'Generic'; protected $description = 'Handles generic commands or is executed by default when a command is not found'; protected $version = '1.0.1'; /**#@-*/ /** * Execute command * * @return boolean */ public function execute() { $message = $this->getMessage(); //You can use $command as param $command = $message->getCommand(); $chat_id = $message->getChat()->getId(); $data = [ 'chat_id' => $chat_id, 'text' => 'Command /' . $command . ' not found.. :(', ]; return Request::sendMessage($data)->isOk(); } }
<?php /** * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <akalongman@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Commands\SystemCommands; use Longman\TelegramBot\Commands\SystemCommand; use Longman\TelegramBot\Request; /** * Generic command */ class GenericCommand extends SystemCommand { /**#@+ * {@inheritdoc} */ protected $name = 'Generic'; protected $description = 'Handles generic commands or is executed by default when a command is not found'; protected $version = '1.0.1'; /**#@-*/ /** * Execute command * * @todo This can't be right, as it always returns "Command: xyz not found.. :(" * * @return boolean */ public function execute() { $message = $this->getMessage(); //You can use $command as param $command = $message->getCommand(); $chat_id = $message->getChat()->getId(); $data = [ 'chat_id' => $chat_id, 'text' => 'Command: ' . $command . ' not found.. :(', ]; return Request::sendMessage($data)->isOk(); } }
Clear error on successful login
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Written with help from Stephen Grider's Advanced React and Redux Udemy Course * @module * reducer_auth */ import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types' export default (state = {}, action) => { switch(action.type) { case AUTH_USER: return { ...state, authenticated: true, userId: action.payload.userId, error: null } case UNAUTH_USER: return { ...state, authenticated: false } case AUTH_ERROR: return { ...state, error: action.payload } default: return { ...state } } }
/* * Copyright (c) 2017 Bonnie Schulkin. All Rights Reserved. * * This file is part of BoxCharter. * * BoxCharter is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * BoxCharter is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with BoxCharter. If not, see <http://www.gnu.org/licenses/>. * */ /** * Written with help from Stephen Grider's Advanced React and Redux Udemy Course * @module * reducer_auth */ import { AUTH_USER, UNAUTH_USER, AUTH_ERROR } from '../actions/types' export default (state = {}, action) => { switch(action.type) { case AUTH_USER: return { ...state, authenticated: true, userId: action.payload.userId } case UNAUTH_USER: return { ...state, authenticated: false } case AUTH_ERROR: return { ...state, error: action.payload } default: return { ...state } } }
Set controller result as response if already a response
<?php namespace Alchemy\RestBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; use Symfony\Component\HttpKernel\KernelEvents; class EncodeJsonResponseListener implements EventSubscriberInterface { public function onKernelView(GetResponseForControllerResultEvent $event) { if (! $event->getRequest()->attributes->get('_rest[encode_response]', false, true)) { return; } $result = $event->getControllerResult(); if (! $result instanceof Response) { if (!is_array($result)) { throw new \LogicException('Invalid controller result: array was expected.'); } $result = new JsonResponse($result); } $event->setResponse($result); } public static function getSubscribedEvents() { return array(KernelEvents::VIEW => 'onKernelView'); } }
<?php namespace Alchemy\RestBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; use Symfony\Component\HttpKernel\KernelEvents; class EncodeJsonResponseListener implements EventSubscriberInterface { public function onKernelView(GetResponseForControllerResultEvent $event) { if (! $event->getRequest()->attributes->get('_rest[encode_response]', false, true)) { return; } $result = $event->getControllerResult(); if (! is_array($result)) { throw new \LogicException('Invalid controller result: array was expected.'); } $event->setResponse(new JsonResponse($result)); } public static function getSubscribedEvents() { return array(KernelEvents::VIEW => 'onKernelView'); } }
Fix background color transparencies to match new vibrancy behaviour
module.exports.onWindow = browserWindow => browserWindow.setVibrancy('dark'); const foregroundColor = '#fff'; const backgroundColor = 'rgba(31, 43, 49, .40)'; const overlap = 'rgba(28, 40, 46, .20)'; const red = '#ff5c57'; const green = '#5af78e'; const yellow = '#fefe7a'; const blue = '#57b7ff'; const magenta = '#ff6ac1'; const cyan = '#98edff'; const white = '#fff'; exports.decorateConfig = (config) => Object.assign({}, config, { backgroundColor, foregroundColor, borderColor: overlap, cursorColor: white, colors: { black: backgroundColor, red, green, yellow, blue, magenta, cyan, white, lightBlack: '#686868', lightRed: red, lightGreen: green, lightYellow: yellow, lightBlue: blue, lightMagenta: magenta, lightCyan: cyan, lightWhite: foregroundColor }, css: ` ${config.css} .hyper_main { border: none !important; } .header_header { background-color: ${overlap} !important; } .tabs_borderShim { border-color: transparent !important; } .tab_tab { border: 0; } .tab_textActive { border-bottom: 2px solid ${green}; } ` });
module.exports.onWindow = browserWindow => browserWindow.setVibrancy('dark'); const foregroundColor = '#fff'; const backgroundColor = 'rgba(31, 43, 49, .96)'; const darkerBackgroundColor = 'rgba(28, 40, 46, .30)'; const red = '#ff5c57'; const green = '#5af78e'; const yellow = '#fefe7a'; const blue = '#57b7ff'; const magenta = '#ff6ac1'; const cyan = '#98edff'; const white = '#fff'; exports.decorateConfig = (config) => Object.assign({}, config, { backgroundColor, foregroundColor, borderColor: darkerBackgroundColor, cursorColor: white, colors: { black: backgroundColor, red, green, yellow, blue, magenta, cyan, white, lightBlack: '#686868', lightRed: red, lightGreen: green, lightYellow: yellow, lightBlue: blue, lightMagenta: magenta, lightCyan: cyan, lightWhite: foregroundColor }, css: ` ${config.css} .hyper_main { border: none !important; } .header_header { background-color: ${darkerBackgroundColor} !important; } .tabs_borderShim { border-color: transparent !important; } .tab_tab { border: 0; } .tab_textActive { border-bottom: 2px solid ${green}; } ` });
Use singular guard names for email verification brokers
<?php declare(strict_types=1); return [ /* |-------------------------------------------------------------------------- | Email Verification |-------------------------------------------------------------------------- | | The broker option controls the default email verification broker for | your application. You may change this default as required, | but they're a perfect start for most applications. | | You may need to specify multiple email verification configurations if you have | more than one user table or model in the application and you want to have | separate email verification settings based on the specific user types. | | The expire time is the number of minutes that the email verification token | should be considered valid. This security feature keeps tokens short-lived | so they have less time to be guessed. You may change this as needed. | */ 'emailverification' => [ 'broker' => 'member', 'admin' => [ 'provider' => 'admins', 'expire' => 60, ], 'member' => [ 'provider' => 'members', 'expire' => 60, ], 'manager' => [ 'provider' => 'managers', 'expire' => 60, ], ], ];
<?php declare(strict_types=1); return [ /* |-------------------------------------------------------------------------- | Email Verification |-------------------------------------------------------------------------- | | The broker option controls the default email verification broker for | your application. You may change this default as required, | but they're a perfect start for most applications. | | You may need to specify multiple email verification configurations if you have | more than one user table or model in the application and you want to have | separate email verification settings based on the specific user types. | | The expire time is the number of minutes that the email verification token | should be considered valid. This security feature keeps tokens short-lived | so they have less time to be guessed. You may change this as needed. | */ 'emailverification' => [ 'broker' => 'members', 'admins' => [ 'provider' => 'admins', 'expire' => 60, ], 'members' => [ 'provider' => 'members', 'expire' => 60, ], 'managers' => [ 'provider' => 'managers', 'expire' => 60, ], ], ];
Update resolver tests to match new resolver
import gflags import unittest2 from mlabns.util import constants from mlabns.util import message from mlabns.util import resolver class ResolverTestCase(unittest2.TestCase): def testDefaultConstructor(self): query = resolver.LookupQuery(); self.assertEqual(None, query.tool_id) self.assertEqual(None, query.policy) self.assertEqual(None, query.metro) self.assertEqual(None, query.ip_address) self.assertEqual(None, query.address_family) self.assertEqual(None, query.city) self.assertEqual(None, query.country) self.assertEqual(None, query.latitude) self.assertEqual(None, query.longitude) self.assertEqual(constants.GEOLOCATION_APP_ENGINE, query.geolocation_type) self.assertEqual(None, query.response_format) def testInitializeFromDictionary(self): # TODO pass if __name__ == '__main__': unittest2.main()
import gflags import unittest2 from mlabns.util import message from mlabns.util import resolver class ResolverTestCase(unittest2.TestCase): def testDefaultConstructor(self): query = resolver.LookupQuery(); self.assertEqual(None, query.tool_id) self.assertEqual(message.POLICY_GEO, query.policy) self.assertEqual(None, query.metro) self.assertEqual(None, query.ip_address) self.assertEqual(message.ADDRESS_FAMILY_IPv4, query.address_family) self.assertEqual(None, query.city) self.assertEqual(None, query.country) self.assertEqual(None, query.latitude) self.assertEqual(None, query.longitude) self.assertEqual(None, query.response_format) def testInitializeFromDictionary(self): # TODO pass if __name__ == '__main__': unittest2.main()
Remove deprecated calls to prepare for 3.0
<?php /** * This file is part of the Clastic package. * * (c) Dries De Peuter <dries@nousefreak.be> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Clastic\TextBundle\Form\Module; use Clastic\BackofficeBundle\Form\Type\WysiwygType; use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension; use Symfony\Component\Form\FormBuilderInterface; /** * NodeTypeExtension. * * @author Dries De Peuter <dries@nousefreak.be> */ class TextFormExtension extends AbstractNodeTypeExtension { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->getTabHelper($builder)->findTab('general') ->add('body', WysiwygType::class, array( 'label' => 'text.form.tab.general.field.body', )); } }
<?php /** * This file is part of the Clastic package. * * (c) Dries De Peuter <dries@nousefreak.be> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Clastic\TextBundle\Form\Module; use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension; use Symfony\Component\Form\FormBuilderInterface; /** * NodeTypeExtension. * * @author Dries De Peuter <dries@nousefreak.be> */ class TextFormExtension extends AbstractNodeTypeExtension { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->getTabHelper($builder)->findTab('general') ->add('body', 'wysiwyg', array( 'label' => 'text.form.tab.general.field.body', )); } }
Fix test for extra mouse manifest
/* * Copyright (c) 2014. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.reference; import java.io.IOException; import junit.framework.TestCase; /** * */ public class ReferenceManifestTest extends TestCase { public void test() throws IOException { assertEquals(5, ReferenceManifest.getReferenceDetectors().size()); } }
/* * Copyright (c) 2014. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.reference; import java.io.IOException; import junit.framework.TestCase; /** * */ public class ReferenceManifestTest extends TestCase { public void test() throws IOException { assertEquals(4, ReferenceManifest.getReferenceDetectors().size()); } }
Fix arrangement of argument list.
''' test_deltaprel - Test functions for deltaprel module Author: Ian Huston For license and copyright information see LICENSE.txt which was distributed with this file. ''' import numpy as np from numpy.testing import assert_, assert_raises from pyflation.analysis import deltaprel import nose class TestSoundSpeeds(): def setup(self): self.Vphi = np.arange(24).reshape((4,3,2)) self.phidot = self.Vphi self.H = np.arange(8).reshape((4,1,2)) def test_shape(self): """Test whether the soundspeeds are shaped correctly.""" arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H) assert_(arr.shape == self.Vphi.shape) def test_scalar(self): """Test results of 1x1x1 calculation.""" arr = deltaprel.soundspeeds(3, 0.5, 2) assert_(arr == 2) def test_wrongshape(self): """Test that wrong shapes raise exception.""" self.H = np.arange(8).reshape((4,2)) assert_raises(ValueError, deltaprel.soundspeeds, self.Vphi, self.phidot, self.H)
''' test_deltaprel - Test functions for deltaprel module Author: Ian Huston For license and copyright information see LICENSE.txt which was distributed with this file. ''' import numpy as np from numpy.testing import assert_, assert_raises from pyflation.analysis import deltaprel import nose class TestSoundSpeeds(): def setup(self): self.Vphi = np.arange(24).reshape((4,3,2)) self.phidot = self.Vphi self.H = np.arange(8).reshape((4,1,2)) def test_shape(self): """Test whether the soundspeeds are shaped correctly.""" arr = deltaprel.soundspeeds(self.Vphi, self.phidot, self.H) assert_(arr.shape == self.Vphi.shape) def test_scalar(self): """Test results of 1x1x1 calculation.""" arr = deltaprel.soundspeeds(3, 2, 0.5) assert_(arr == 2) def test_wrongshape(self): """Test that wrong shapes raise exception.""" self.H = np.arange(8).reshape((4,2)) assert_raises(ValueError, deltaprel.soundspeeds, self.Vphi, self.phidot, self.H)
Add link of an author to the credit section
<?php if(!defined('MEDIAWIKI')) die; $dir = __DIR__; $ext = 'ShortenUrlEasily'; $wgExtensionCredits['other'][] = array( 'path' => __FILE__, 'name' => $ext, 'version' => '0.1', 'author' => '[https://github.com/uta uta]', 'url' => 'https://github.com/uta/ShortenUrlEasily', 'descriptionmsg' => 'shorten-url-easily-desc', 'license-name' => 'MIT-License', ); $wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php"; $wgMessagesDirs[$ext] = "$dir/i18n"; require_once("$dir/classes/${ext}Util.php");
<?php if(!defined('MEDIAWIKI')) die; $dir = __DIR__; $ext = 'ShortenUrlEasily'; $wgExtensionCredits['other'][] = array( 'path' => __FILE__, 'name' => $ext, 'version' => '0.1', 'author' => 'uta', 'url' => 'https://github.com/uta/ShortenUrlEasily', 'descriptionmsg' => 'shorten-url-easily-desc', 'license-name' => 'MIT-License', ); $wgExtensionMessagesFiles[$ext] = "$dir/i18n/_backward_compatibility.php"; $wgMessagesDirs[$ext] = "$dir/i18n"; require_once("$dir/classes/${ext}Util.php");
Test against dictionary, not a string
import hashlib import json from unittest.mock import Mock from unittest.mock import ANY from queue_functions import do_work from server import handle_post from uploaders.s3 import get_url from uploaders.s3 import upload def test_post(): q = Mock() filename = 'afakefilename' files = {'file': [{'body': b'a-fake-file-body', 'filename': filename}]} hash_object = hashlib.md5(filename.encode()) audio_filename = hash_object.hexdigest() + "-" + filename analysis_filename = audio_filename + '.analysis.json' expected = {'analysis': get_url(analysis_filename), 'audio': get_url(audio_filename)} actual = json.loads(handle_post(q, files, get_url, upload)) q.enqueue.assert_called_with(do_work, (ANY, audio_filename, analysis_filename, upload)) assert expected == actual
import hashlib import json from unittest.mock import Mock from unittest.mock import ANY from queue_functions import do_work from server import handle_post from uploaders.s3 import get_url from uploaders.s3 import upload def test_post(): q = Mock() filename = 'afakefilename' files = {'file': [{'body': b'a-fake-file-body', 'filename': filename}]} hash_object = hashlib.md5(filename.encode()) audio_filename = hash_object.hexdigest() + "-" + filename analysis_filename = audio_filename + '.analysis.json' expected = {'analysis': get_url(analysis_filename), 'audio': get_url(audio_filename)} actual = json.reads(handle_post(q, files, get_url, upload)) q.enqueue.assert_called_with(do_work, (ANY, audio_filename, analysis_filename, upload)) assert expected == actual
Fix MinGW build on Appveyor by changing search path order C:\MinGW\bin should go first to prevent executables from older version of MinGW in C:\MinGW\mingw32 being picked up.
#!/usr/bin/env python # Build the project on AppVeyor. import os from subprocess import check_call build = os.environ['BUILD'] config = os.environ['CONFIG'] path = os.environ['PATH'] cmake_command = ['cmake', '-DFMT_PEDANTIC=ON', '-DCMAKE_BUILD_TYPE=' + config] if build == 'mingw': cmake_command.append('-GMinGW Makefiles') build_command = ['mingw32-make', '-j4'] test_command = ['mingw32-make', 'test'] # Remove the path to Git bin directory from $PATH because it breaks MinGW config. path = path.replace(r'C:\Program Files (x86)\Git\bin', '') os.environ['PATH'] = r'C:\MinGW\bin;' + path else: # Add MSBuild 14.0 to PATH as described in # http://help.appveyor.com/discussions/problems/2229-v140-not-found-on-vs2105rc. os.environ['PATH'] = r'C:\Program Files (x86)\MSBuild\14.0\Bin;' + path build_command = ['msbuild', '/m:4', '/p:Config=' + config, 'FORMAT.sln'] test_command = ['msbuild', 'RUN_TESTS.vcxproj'] check_call(cmake_command) check_call(build_command) check_call(test_command)
#!/usr/bin/env python # Build the project on AppVeyor. import os from subprocess import check_call build = os.environ['BUILD'] config = os.environ['CONFIG'] path = os.environ['PATH'] cmake_command = ['cmake', '-DFMT_PEDANTIC=ON', '-DCMAKE_BUILD_TYPE=' + config] if build == 'mingw': cmake_command.append('-GMinGW Makefiles') build_command = ['mingw32-make', '-j4'] test_command = ['mingw32-make', 'test'] # Remove the path to Git bin directory from $PATH because it breaks MinGW config. path = path.replace(r'C:\Program Files (x86)\Git\bin', '') os.environ['PATH'] = path + r';C:\MinGW\bin' else: # Add MSBuild 14.0 to PATH as described in # http://help.appveyor.com/discussions/problems/2229-v140-not-found-on-vs2105rc. os.environ['PATH'] = r'C:\Program Files (x86)\MSBuild\14.0\Bin;' + path build_command = ['msbuild', '/m:4', '/p:Config=' + config, 'FORMAT.sln'] test_command = ['msbuild', 'RUN_TESTS.vcxproj'] check_call(cmake_command) check_call(build_command) check_call(test_command)
Fix the onboarding communities picker.
import React from 'react' import classNames from 'classnames' import { loadCommunities } from '../../actions/onboarding' import StreamComponent from '../streams/StreamComponent' import Picker from '../pickers/Picker' class CommunityPicker extends Picker { getRelationshipButton(refs) { const userContainer = refs.wrappedInstance if (userContainer) { return userContainer.refs.RelationshipImageButton } return null } render() { const klassNames = classNames( 'CommunityPicker', 'Panel', { isFollowingAll: this.isFollowingAll() }, ) return ( <div className={klassNames}> <button className="PickerButton" ref="followAllButton" onClick={::this.followAll}> <span>{this.renderBigButtonText()}</span> </button> <StreamComponent ref="streamComponent" action={loadCommunities()} /> </div> ) } } export default CommunityPicker
import React from 'react' import classNames from 'classnames' import { loadCommunities } from '../../actions/onboarding' import StreamComponent from '../streams/StreamComponent' import Picker from '../pickers/Picker' class CommunityPicker extends Picker { getRelationshipButton(refs) { const userContainer = refs.wrappedInstance if (userContainer) { return userContainer.refs.RelationshipImageButton } return null } render() { const klassNames = classNames( 'CommunityPicker', 'Panel', { isFollowingAll: this.isFollowingAll() }, ) return ( <div className={klassNames}> <button className="PickerButton" ref="followAllButton" onClick={::this.followAll}> <span>{::this.renderBigButtonText}</span> </button> <StreamComponent ref="streamComponent" action={loadCommunities()} /> </div> ) } } export default CommunityPicker
Fix CORS issue with React App
<?php /** * Public store inforamtion in JSON format * * @author Chris Rogers * @since 2019-02-22 */ class NaturalRemedyCo_NRCLayout_IndexController extends Mage_Core_Controller_Front_Action { /** * @var Mage_Core_Model_Store */ protected $_store; /** * Magento's specific construtor (notice the single underscore) */ public function _construct() { header("Access-Control-Allow-Origin: *"); $this->_store = Mage::app()->getStore(); } /** * Return store info as JSON using layout file <info_index_index> * @return JSON * @see Useful debugging: "Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); exit;" */ public function indexAction() { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->loadLayout(); // $this->getResponse()->setBody(); $this->renderLayout(); } } ?>
<?php /** * Public store inforamtion in JSON format * * @author Chris Rogers * @since 2019-02-22 */ class NaturalRemedyCo_NRCLayout_IndexController extends Mage_Core_Controller_Front_Action { /** * @var Mage_Core_Model_Store */ protected $_store; /** * Magento's specific construtor (notice the single underscore) */ public function _construct() { $this->_store = Mage::app()->getStore(); } /** * Return store info as JSON using layout file <info_index_index> * @return JSON * @see Useful debugging: "Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles()); exit;" */ public function indexAction() { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->loadLayout(); // $this->getResponse()->setBody(); $this->renderLayout(); } } ?>
[ADD] Add checks list on tests init file
# -*- coding: utf-8 -*- # # # Authors: Adrien Peiffer # Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu) # All Rights Reserved # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsibility of assessing all potential # consequences resulting from its eventual inadequacies and bugs. # End users who are looking for a ready-to-use solution with commercial # guarantees and support are strongly advised to contact a Free Software # Service Company. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # from . import test_account_journal_period_close checks = [ test_account_journal_period_close, ]
# -*- coding: utf-8 -*- # # # Authors: Adrien Peiffer # Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu) # All Rights Reserved # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsibility of assessing all potential # consequences resulting from its eventual inadequacies and bugs. # End users who are looking for a ready-to-use solution with commercial # guarantees and support are strongly advised to contact a Free Software # Service Company. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # from . import test_account_journal_period_close
Use named urls for get_post_url(). The helper should not assume knowledge of the post url structure.
from models import Post from django.core.urlresolvers import reverse def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title #url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' url = reverse('blog_post', kwargs={'post_year': post_year, 'post_month': post_month, 'post_title': post_title}) return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
from models import Post def get_post_url(post): post_year = str(post.publication_date.year) post_month = '%02d' % post.publication_date.month post_title = post.title url = u'/blog/' + post_year + '/' + post_month + '/' + post_title + '/' return url def post_as_components(post_text): ''' This function returns the components of a blog post for use with other functions. Given a Markdown formatted post, it returns a three-tuple. The first element is the blog title (not markdowned), the second is the first paragraph (in Markdown format) and the third is the entire post body (in Markdown format). ''' post_content = post_text.split('\n\n') title = post_content[0].strip('# ') first_para = post_content[1] body = u'\n\n'.join(post_content[1:]) return (title, first_para, body)
Add indentation fix on htmlbar loader.
var path = require('path') var loaderUtils = require('loader-utils') var HtmlbarsCompiler = require('ember-cli-htmlbars') var DEFAULT_TEMPLATE_COMPILER = 'components-ember/ember-template-compiler.js' var templateTree var appPath /* * options: * - appPath: default assuming webpack.config.js in root folder + ./app * - templateCompiler: default 'components-ember/ember-template-compiler.js' */ module.exports = function(source) { this.cacheable && this.cacheable() var options = loaderUtils.getOptions(this); var appPath = (options.appPath || 'app').replace(/\/$/, '') var templatesFolder = path.join(appPath, 'templates') templateTree = templateTree || new HtmlbarsCompiler(templatesFolder, { isHTMLBars: true, templateCompiler: require(options.templateCompiler || DEFAULT_TEMPLATE_COMPILER) }); var resourcePathMatcher = new RegExp(templatesFolder + '/(.*)\.hbs$') var templateMatch = this.resourcePath.match(resourcePathMatcher) var templatePath = templateMatch.pop() var fullTemplate = templateTree.processString(source, templatePath) var templateString = fullTemplate.replace(/^export default Ember\./, 'Ember.') return 'Ember.TEMPLATES["' + templatePath + '"] = ' + templateString }
var path = require('path') var loaderUtils = require('loader-utils') var HtmlbarsCompiler = require('ember-cli-htmlbars') var DEFAULT_TEMPLATE_COMPILER = 'components-ember/ember-template-compiler.js' var templateTree var appPath /* * options: * - appPath: default assuming webpack.config.js in root folder + ./app * - templateCompiler: default 'components-ember/ember-template-compiler.js' */ module.exports = function(source) { this.cacheable && this.cacheable() var options = loaderUtils.getOptions(this); var appPath = (options.appPath || 'app').replace(/\/$/, '') var templatesFolder = path.join(appPath, 'templates') templateTree = templateTree || new HtmlbarsCompiler(templatesFolder, { isHTMLBars: true, templateCompiler: require(options.templateCompiler || DEFAULT_TEMPLATE_COMPILER) }); var resourcePathMatcher = new RegExp(templatesFolder + '/(.*)\.hbs$') var templateMatch = this.resourcePath.match(resourcePathMatcher) var templatePath = templateMatch.pop() var fullTemplate = templateTree.processString(source, templatePath) var templateString = fullTemplate.replace(/^export default Ember\./, 'Ember.') return 'Ember.TEMPLATES["' + templatePath + '"] = ' + templateString }
Add ListUtilsTest to Core Suite
package jpower.core.test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AlphabetTest.class, ConditionTest.class, ConfigurationTest.class, FactoryTest.class, InternalTest.class, IOUtilsTest.class, LoadTest.class, MultiMapTest.class, PowerLoaderTest.class, RandomTest.class, ThreadUtilsTest.class, ByteUtilsTest.class, WorkerTest.class, GenericSnifferTest.class, OperatingSystemTest.class, CallUtilsTest.class, ServiceTest.class, WrapperTest.class, RepeaterTest.class, ConditionalAdapterTest.class, StringUtilsTest.class, ListUtilsTest.class }) public class CoreTestSuite { }
package jpower.core.test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AlphabetTest.class, ConditionTest.class, ConfigurationTest.class, FactoryTest.class, InternalTest.class, IOUtilsTest.class, LoadTest.class, MultiMapTest.class, PowerLoaderTest.class, RandomTest.class, ThreadUtilsTest.class, ByteUtilsTest.class, WorkerTest.class, GenericSnifferTest.class, OperatingSystemTest.class, CallUtilsTest.class, ServiceTest.class, WrapperTest.class, RepeaterTest.class, ConditionalAdapterTest.class, StringUtilsTest.class }) public class CoreTestSuite { }
Address feedback, reformat, simplify, fix bugs and typo
"""Show this help""" import pkgutil import sys from setuptools import find_packages from pkgutil import iter_modules import fontTools import importlib def describe(pkg): try: description = __import__( "fontTools." + pkg + ".__main__", globals(), locals(), ["__doc__"] ).__doc__ print("fonttools %-10s %s" % (pkg, description), file=sys.stderr) except Exception as e: return None def show_help_list(): path = fontTools.__path__[0] for pkg in find_packages(path): qualifiedPkg = "fontTools." + pkg describe(pkg) pkgpath = path + "/" + qualifiedPkg.replace(".", "/") for info in iter_modules([pkgpath]): describe(pkg + "." + info.name) if __name__ == "__main__": print("fonttools v%s\n" % fontTools.__version__, file=sys.stderr) show_help_list()
"""Show this help""" import pkgutil import sys from setuptools import find_packages from pkgutil import iter_modules import fontTools import importlib def get_description(pkg): try: return __import__(pkg+".__main__",globals(),locals(),["__doc__"]).__doc__ except Exception as e: return None def show_help_list(): path = fontTools.__path__[0] for pkg in find_packages(path): qualifiedPkg = "fontTools."+pkg description = get_description(qualifiedPkg) if description: print("fontools %-10s %s" % (pkg, description)) pkgpath = path + '/' + qualifiedPkg.replace('.', '/') if (sys.version_info.major == 3 and sys.version_info.minor < 6): for _, name, ispkg in iter_modules([pkgpath]): if get_description(pkg+ '.' + name): modules.add(pkg + '.' + name) else: for info in iter_modules([pkgpath]): if get_description(pkg+ '.' + info.name): modules.add(pkg + '.' + info.name) if __name__ == '__main__': print("fonttools v%s\n" % fontTools.__version__) show_help_list()
WatLobby: Fix for hiding text field based on model type.
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ CLASS({ package: 'com.google.watlobby', name: 'TopicDetailView', extends: 'foam.ui.md.DetailView', methods: [ function initHTML() { this.SUPER(); this.data.model$.addListener(this.onModelChange); this.onModelChange(); } ], listeners: [ { name: 'onModelChange', isFramed: true, code: function() { var model = this.data.model; this.videoView.$.style.display = model === 'Video' ? 'block' : 'none'; this.textView.$.style.display = ( model === 'Video' || model === 'Background' ) ? 'none' : 'block'; } } ] });
/** * @license * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ CLASS({ package: 'com.google.watlobby', name: 'TopicDetailView', extends: 'foam.ui.md.DetailView', methods: [ function initHTML() { this.SUPER(); this.data.model$.addListener(this.onModelChange); this.onModelChange(); } ], listeners: [ { name: 'onModelChange', code: function(_, __, ___, model) { if ( this.videoView ) this.videoView.$.style.display = model === 'Video' ? 'block' : 'none'; if ( this.textView ) this.textView.$.style.display = ( model === 'Video' || model === 'Background' ) ? 'none' : 'block'; } } ] });
Update base api to include module and object imports, fix missing import of random subpackage
""" Import the main names to top level. """ try: import numba except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") #-Modules-# from . import quad from . import random #-Objects-# from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from .util import searchsorted, fetch_nb_dependencies #-Add Version Attribute-# from .version import version as __version__
""" Import the main names to top level. """ try: import numba except: raise ImportError("Cannot import numba from current anaconda distribution. Please run `conda install numba` to install the latest version.") from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted, fetch_nb_dependencies #Add Version Attribute from .version import version as __version__
Use generic user name in script.
.pragma library var homePath = "file:///home/user"; var illegalCharacters = /(\(.*\)|\{.*\}|\[.*\]|<.*>|[\(\)_\{\}\[\]\!@#$^&*+=|\/"'?~`])/g var whitespace = /\s+/g function getAlbumArtUrl(artist, title) { if (artist == "") artist = " "; if (title == "") title = " "; return homePath + "/.cache/media-art/album-" + Qt.md5(artist.toLowerCase().replace(illegalCharacters, "").replace(whitespace, " ")) + "-" + Qt.md5(title.toLowerCase().replace(illegalCharacters, "").replace(whitespace, " ")) + ".jpeg"; } function formatDuration(duration) { return Math.floor(duration / 60) + ":" + (duration % 60) }
.pragma library var homePath = "file:///home/denexter"; var illegalCharacters = /(\(.*\)|\{.*\}|\[.*\]|<.*>|[\(\)_\{\}\[\]\!@#$^&*+=|\/"'?~`])/g var whitespace = /\s+/g function getAlbumArtUrl(artist, title) { if (artist == "") artist = " "; if (title == "") title = " "; return homePath + "/.cache/media-art/album-" + Qt.md5(artist.toLowerCase().replace(illegalCharacters, "").replace(whitespace, " ")) + "-" + Qt.md5(title.toLowerCase().replace(illegalCharacters, "").replace(whitespace, " ")) + ".jpeg"; } function formatDuration(duration) { return Math.floor(duration / 60) + ":" + (duration % 60) }
Extend visualisation period to March
var moment = require('moment'); // NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_START_MOMENT = moment([ module.exports.DATA_START_YEAR, module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2016; module.exports.DATA_END_MONTH = 2; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 3, 18]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()]; module.exports.labelShowBreakPoint = 992;
var moment = require('moment'); // NOTE: month indices are zero-based module.exports.DATA_START_YEAR = 2012; module.exports.DATA_START_MONTH = 0; module.exports.DATA_START_MOMENT = moment([ module.exports.DATA_START_YEAR, module.exports.DATA_START_MONTH]).startOf('month'); module.exports.DATA_END_YEAR = 2016; module.exports.DATA_END_MONTH = 1; module.exports.DATA_END_MOMENT = moment([ module.exports.DATA_END_YEAR, module.exports.DATA_END_MONTH]).endOf('month'); module.exports.ASYLUM_APPLICANTS_DATA_UPDATED_MOMENT = moment([2016, 3, 18]); module.exports.disableLabels = ['BIH', 'MKD', 'ALB', 'LUX', 'MNE', 'ARM', 'AZE', 'LBN']; module.exports.fullRange = [module.exports.DATA_START_MOMENT.unix(), module.exports.DATA_END_MOMENT.unix()]; module.exports.labelShowBreakPoint = 992;
Improve default for ip in 'where' event
import os import socket from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.setup() def setup(self): pass @truncated_stdout @with_payload def where(self, role=None): my_role = os.environ.get('ROLE', 'no_role') if my_role == role: print(self.my_info()) def my_info(self): ip = (os.environ.get('ADVERTISE') or socket.gethostbyname(socket.gethostname())) return {'ip': ip}
import os from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.setup() def setup(self): pass @truncated_stdout @with_payload def where(self, role=None): my_role = os.environ.get('ROLE', 'no_role') if my_role == role: print(self.my_info()) def my_info(self): return { 'ip': os.environ.get('ADVERTISE', None) }
Send data in trackChecker callbacks
from threading import Timer from . import track _listeners = [] class TrackChecker(): def __init__(self, interval = 5): self.listeners = [] self.CHECK_INTERVAL = interval self.currentSong = "" self.currentArtist = "" self.currentAlbum = "" self.timer = None def checkSong(self): song = track.getCurrentSong() artist = track.getCurrentArtist() album = track.getCurrentAlbum() if (song != self.currentSong or artist != self.currentArtist or album != self.currentAlbum): self.currentSong = song self.currentArtist = artist self.currentAlbum = album self._callListeners() if self.timer != None: self.startTimer() def registerListener(self, function): _listeners.append(function) def _callListeners(self): data = { "song": track.getCurrentSong(), "artist": track.getCurrentArtist(), "album": track.getCurrentAlbum() } for listener in _listeners: listener(data) def startTimer(self): self.timer = Timer(self.CHECK_INTERVAL, self.checkSong) self.timer.daemon = True self.timer.start() def cancelTimer(self): self.timer.cancel() self.timer = None
from threading import Timer from . import track _listeners = [] class TrackChecker(): def __init__(self, interval = 5): self.listeners = [] self.CHECK_INTERVAL = interval self.currentSong = "" self.currentArtist = "" self.currentAlbum = "" self.timer = None def checkSong(self): song = track.getCurrentSong() artist = track.getCurrentArtist() album = track.getCurrentAlbum() if (song != self.currentSong or artist != self.currentArtist or album != self.currentAlbum): self.currentSong = song self.currentArtist = artist self.currentAlbum = album self._callListeners() if self.timer != None: self.startTimer() def registerListener(self, function): _listeners.append(function) def _callListeners(self): for listener in _listeners: listener() def startTimer(self): self.timer = Timer(self.CHECK_INTERVAL, self.checkSong) self.timer.daemon = True self.timer.start() def cancelTimer(self): self.timer.cancel() self.timer = None
api: Comment out test on /about/ Related fb0bf65356aa6a6fd6cfb6e29122e1f45925d21c
# Copyright (C) 2016 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from nose.tools import istest from .. import test_app class MainViewTestCase(test_app.SWHViewTestCase): render_template = False @istest def homepage(self): # when rv = self.client.get('/') # then self.assertEquals(rv.status_code, 302) self.assertRedirects(rv, '/api/') # @istest # def info(self): # # when # rv = self.client.get('/about/') # self.assertEquals(rv.status_code, 200) # self.assert_template_used('about.html') # self.assertIn(b'About', rv.data)
# Copyright (C) 2016 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from nose.tools import istest from .. import test_app class MainViewTestCase(test_app.SWHViewTestCase): render_template = False @istest def homepage(self): # when rv = self.client.get('/') # then self.assertEquals(rv.status_code, 302) self.assertRedirects(rv, '/api/') @istest def info(self): # when rv = self.client.get('/about/') self.assertEquals(rv.status_code, 200) self.assert_template_used('about.html') self.assertIn(b'About', rv.data)
Add a nice log to the game
package li.seiji.minichess; import li.seiji.minichess.move.Move; import li.seiji.minichess.player.IPlayer; public class Game { private Board state = new Board(); private IPlayer white; private IPlayer black; public Game(IPlayer white, IPlayer black) { state.initialize(); this.white = white; this.black = black; } public void run() throws InvalidMoveException { white.start(); black.start(); while(state.turn != Player.NONE) { IPlayer turnPlayer; IPlayer otherPlayer; if(state.turn == Player.WHITE) { turnPlayer = white; otherPlayer = black; } else { turnPlayer = black; otherPlayer = white; } Move move = turnPlayer.getMove(state); state = state.move(move); otherPlayer.setMove(state, move); state.prettyPrint(); } } }
package li.seiji.minichess; import li.seiji.minichess.move.Move; import li.seiji.minichess.player.IPlayer; public class Game { private Board state = new Board(); private IPlayer white; private IPlayer black; public Game(IPlayer white, IPlayer black) { state.initialize(); this.white = white; this.black = black; } public void run() throws InvalidMoveException { white.start(); black.start(); while(state.turn != Player.NONE) { IPlayer turnPlayer; IPlayer otherPlayer; if(state.turn == Player.WHITE) { turnPlayer = white; otherPlayer = black; } else { turnPlayer = black; otherPlayer = white; } Move move = turnPlayer.getMove(state); state = state.move(move); otherPlayer.setMove(state, move); } } }
Split cert as travis was not instantiating it
const app = require('./server.js'); const http = require('http'); const https = require('https'); const port = process.env.PORT || 8080; const httpsPort = process.env.HTTPS_PORT || 8443; const socketio = require('socket.io'); const chatSockets = require('./sockets/group-chat-sockets.js'); const eventSockets = require('./sockets/event-sockets.js'); const fs = require('fs'); const credentials = {}; if (process.env.HTTPS_CERT) { credentials.key = process.env.HTTPS_KEY; credentials.cert = process.env.HTTPS_CERTl; } else { credentials.key = fs.readFileSync('privkey.pem'); cerdentials.cert = fs.readFileSync('fullchain.pem'); } console.log(typeof process.env.HTTPS_CERT); const httpsServer = https.createServer(credentials, app); const io = socketio(httpsServer); app.io = io; chatSockets(io); eventSockets(io); const httpsRedirect = http.createServer((req, res) => { res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url }).end(); }); httpsRedirect.listen(port, () => console.log('http listening on port:', port, 'to redirect to https')); httpsServer.listen(httpsPort, () => console.log('https listening on port:', httpsPort));
const app = require('./server.js'); const http = require('http'); const https = require('https'); const port = process.env.PORT || 8080; const httpsPort = process.env.HTTPS_PORT || 8443; const socketio = require('socket.io'); const chatSockets = require('./sockets/group-chat-sockets.js'); const eventSockets = require('./sockets/event-sockets.js'); const fs = require('fs'); if (process.env.HTTPS_CERT) { const credentials = { key: process.env.HTTPS_KEY, cert: process.env.HTTPS_CERT }; } else { const credentials = { key: fs.readFileSync('privkey.pem'), cert: fs.readFileSync('fullchain.pem') }; } const httpsServer = https.createServer(credentials, app); const io = socketio(httpsServer); app.io = io; chatSockets(io); eventSockets(io); const httpsRedirect = http.createServer((req, res) => { res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url }).end(); }); httpsRedirect.listen(port, () => console.log('http listening on port:', port, 'to redirect to https')); httpsServer.listen(httpsPort, () => console.log('https listening on port:', httpsPort));
Fix bug with GameModel 'model' object not updating in scope properly
export default class GameModelService { constructor($log, $localStorage, _, gamesApi) { 'ngInject'; this.$log = $log.getInstance(this.constructor.name); this._ = _; this.gamesApi = gamesApi; this.model = {}; } endGame() { let onSuccess = (res => { this.$log.debug('onSuccess()', res, this); this.update(res.data); }), onError = (err => { this.$log.error(err); }); this.$log.debug('endGame()', this); this.gamesApi .update(this.model.id, { isGameStarted: false }) .then(onSuccess, onError); } clear() { angular.copy({}, this.model); } get() { return this.gamesApi.get(); } getByProp(prop) { if (prop) { return this.model[prop]; } return this.model; } isGameStarted() { return this.model.isGameStarted; } update(data) { this.$log.debug('update()', data, this); angular.extend(this.model, data); if (!data.actionCard) { angular.copy(null, this.model.actionCard); } } }
export default class GameModelService { constructor($log, $localStorage, _, gamesApi) { 'ngInject'; this.$log = $log.getInstance(this.constructor.name); this._ = _; this.gamesApi = gamesApi; this.model = { instantAction: false }; } endGame() { let onSuccess = (res => { this.$log.debug('onSuccess()', res, this); this.update(res.data); }), onError = (err => { this.$log.error(err); }); this.$log.debug('endGame()', this); this.gamesApi .update(this.model.id, { isGameStarted: false }) .then(onSuccess, onError); } clear() { angular.copy({}, this.model); } get() { return this.gamesApi.get(); } getByProp(prop) { if (prop) { return this.model[prop]; } return this.model; } isGameStarted() { return this.model.isGameStarted; } update(data) { angular.copy(data, this.model); if (!data.actionCard) { angular.copy(null, this.model.actionCard); } } }
Support floats in numeric constraint
<?php namespace Ayeo\Validator\Constraint; use Ayeo\Validator\Exception\InvalidConstraintParameter; class NumericMin extends AbstractConstraint { private $min; /** * @throws InvalidConstraintParameter */ public function __construct($min = 0) { if (is_numeric($min)) { $this->min = $min; } else { throw new InvalidConstraintParameter; } } public function run($value) { if (is_numeric($value) === false) { $this->addError('must_be_numeric'); } if ($value < $this->min) { $this->addError('must_be_greater_than', $this->min); } } }
<?php namespace Ayeo\Validator\Constraint; use Ayeo\Validator\Exception\InvalidConstraintParameter; class NumericMin extends AbstractConstraint //todo: rename to IntegerMin { /** * @var integer */ private $min; /** * @param int $min * @throws InvalidConstraintParameter */ public function __construct($min = 0) { if (is_integer($min)) { $this->min = $min; } else { throw new InvalidConstraintParameter; } } public function run($value) { if (is_numeric($value) === false) { $this->addError('must_be_numeric'); } if ($value < $this->min) { $this->addError('must_be_greater_than', $this->min); } } }
Add hasNoJsonPath testcase for explicit null
package com.jayway.jsonpath.matchers; import org.junit.Test; import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasNoJsonPath; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; public class HasNoJsonPathTest { private static final String JSON_STRING = "{" + "\"none\": null," + "\"name\": \"Jessie\"" + "}"; @Test public void shouldMatchMissingJsonPath() { assertThat(JSON_STRING, hasNoJsonPath("$.not_there")); } @Test public void shouldNotMatchExistingJsonPath() { assertThat(JSON_STRING, not(hasNoJsonPath("$.name"))); } @Test public void shouldNotMatchExplicitNull() { assertThat(JSON_STRING, not(hasNoJsonPath("$.none"))); } @Test public void shouldBeDescriptive() { assertThat(hasNoJsonPath("$.name"), hasToString(equalTo("is json without json path \"$['name']\""))); } }
package com.jayway.jsonpath.matchers; import org.junit.Test; import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasNoJsonPath; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; public class HasNoJsonPathTest { private static final String JSON_STRING = "{" + "\"name\": \"Jessie\"" + "}"; @Test public void shouldMatchMissingJsonPath() { assertThat(JSON_STRING, hasNoJsonPath("$.not_there")); } @Test public void shouldNotMatchExistingJsonPath() { assertThat(JSON_STRING, not(hasNoJsonPath("$.name"))); } @Test public void shouldBeDescriptive() { assertThat(hasNoJsonPath("$.name"), hasToString(equalTo("is json without json path \"$['name']\""))); } }
Move the App's Routes config file inclusion right before Router's dispatching; this way, the Routes defined by Modules taking precedence
<?php /** * Bootstrap handler - perform the Nova Framework's bootstrap stage. * * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com * @version 3.0 * @date December 15th, 2015 */ use Nova\Modules\Manager as Modules; use Nova\Events\Manager as Events; use Nova\Net\Session; use Nova\Net\Router; use Nova\Config; use Nova\Logger; // The current configuration files directory. $configDir = dirname(__FILE__) .DS; /** * Turn on output buffering. */ ob_start(); require $configDir .'constants.php'; require $configDir .'functions.php'; require $configDir .'config.php'; /** * Turn on custom error handling. */ Logger::initialize(); set_exception_handler('Nova\Logger::ExceptionHandler'); set_error_handler('Nova\Logger::ErrorHandler'); /** * Set timezone. */ date_default_timezone_set(Config::get('timezone')); /** * Start sessions. */ Session::initialize(); /** Get the Router instance. */ $router = Router::getInstance(); /** bootstrap the active modules (and their associated routes) */ Modules::bootstrap(); /** initialize the Events */ Events::initialize(); /** load routes */ require $configDir .'routes.php'; /** Execute matched routes. */ $router->dispatch();
<?php /** * Bootstrap handler - perform the Nova Framework's bootstrap stage. * * @author Virgil-Adrian Teaca - virgil@giulianaeassociati.com * @version 3.0 * @date December 15th, 2015 */ use Nova\Modules\Manager as Modules; use Nova\Events\Manager as Events; use Nova\Net\Session; use Nova\Net\Router; use Nova\Config; use Nova\Logger; // The current configuration files directory. $configDir = dirname(__FILE__) .DS; /** * Turn on output buffering. */ ob_start(); require $configDir .'constants.php'; require $configDir .'functions.php'; require $configDir .'config.php'; /** * Turn on custom error handling. */ Logger::initialize(); set_exception_handler('Nova\Logger::ExceptionHandler'); set_error_handler('Nova\Logger::ErrorHandler'); /** * Set timezone. */ date_default_timezone_set(Config::get('timezone')); /** * Start sessions. */ Session::initialize(); /** Get the Router instance. */ $router = Router::getInstance(); /** load routes */ require $configDir .'routes.php'; /** bootstrap the active modules (and their associated routes) */ Modules::bootstrap(); /** initialize the Events */ Events::initialize(); /** Execute matched routes. */ $router->dispatch();
Update provider registration to add silex version to user agent
<?php /** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Aws\Silex; use Aws\Sdk; use Silex\Application; use Silex\ServiceProviderInterface; /** * AWS SDK for PHP service provider for Silex applications */ class AwsServiceProvider implements ServiceProviderInterface { const VERSION = '2.0.2'; public function register(Application $app) { $app['aws'] = $app->share(function (Application $app) { $config = isset($app['aws.config']) ? $app['aws.config'] : []; return new Sdk($config + ['ua_append' => [ 'Silex/' . Application::VERSION, 'SXMOD/' . self::VERSION, ]]); }); } public function boot(Application $app) { } }
<?php /** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Aws\Silex; use Aws\Sdk; use Silex\Application; use Silex\ServiceProviderInterface; /** * AWS SDK for PHP service provider for Silex applications */ class AwsServiceProvider implements ServiceProviderInterface { const VERSION = '2.0.0'; public function register(Application $app) { $app['aws'] = $app->share(function (Application $app) { $aws = new Sdk(isset($app['aws.config']) ? $app['aws.config'] : []); return $aws; }); } public function boot(Application $app) { } }
NXP-11577: Fix Sonar Major violations: Javadoc Type
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; /** * * Core event related constants for Nuxeo Drive. * * @author Antoine Taillefer */ public final class NuxeoDriveEvents { private NuxeoDriveEvents() { // Utility class } public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; public static final String ROOT_REGISTERED = "rootRegistered"; public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; public static final String ROOT_UNREGISTERED = "rootUnregistered"; public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; public static final Serializable EVENT_CATEGORY = "NuxeoDrive"; public static final String DELETED_EVENT = "deleted"; }
/* * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * Olivier Grisel <ogrisel@nuxeo.com> * Antoine Taillefer <ataillefer@nuxeo.com> */ package org.nuxeo.drive.service; import java.io.Serializable; public final class NuxeoDriveEvents { private NuxeoDriveEvents() { // Utility class } public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot"; public static final String ROOT_REGISTERED = "rootRegistered"; public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot"; public static final String ROOT_UNREGISTERED = "rootUnregistered"; public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName"; public static final Serializable EVENT_CATEGORY = "NuxeoDrive"; public static final String DELETED_EVENT = "deleted"; }
Replace Authentication string with import
import HomeModule from "./home"; import Authentication from "../../common/authentication/authentication"; describe("Home", () => { let $rootScope, $componentController; beforeEach(window.module(Authentication)); //to load hookProvider beforeEach(window.module(HomeModule)); beforeEach(inject(($injector) => { $rootScope = $injector.get("$rootScope"); $componentController = $injector.get("$componentController"); })); describe("Module", () => { // top-level specs: i.e., routes, injection, naming }); describe("Controller", () => { // controller specs let controller; beforeEach(() => { controller = $componentController("home", { $scope: $rootScope.$new() }); }); it("has a name property", () => { // erase if removing this.name from the controller expect(controller).to.have.property("name"); }); }); describe("View", () => { // view layer specs. }); });
import HomeModule from "./home"; describe("Home", () => { let $rootScope, $componentController; beforeEach(window.module("Authentication")); //to load hookProvider beforeEach(window.module(HomeModule)); beforeEach(inject(($injector) => { $rootScope = $injector.get("$rootScope"); $componentController = $injector.get("$componentController"); })); describe("Module", () => { // top-level specs: i.e., routes, injection, naming }); describe("Controller", () => { // controller specs let controller; beforeEach(() => { controller = $componentController("home", { $scope: $rootScope.$new() }); }); it("has a name property", () => { // erase if removing this.name from the controller expect(controller).to.have.property("name"); }); }); describe("View", () => { // view layer specs. }); });
Mark integration tests as xfail
"""This is structurally equivalent to ../unit/test_jasmine.py. The difference is that it runs igtest.html instead of test.html. also, it is located next to acceptance tests, because it has to be allowed to import components other than adhocracy, like adhocracy_core. """ from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmine class TestJasmine: @mark.xfail def test_all(self, browser_igtest): data = browser_igtest.evaluate_script('jsApiReporter.specs()') formatter = Formatter([]) parser = Parser() results = parser.parse(data) formatter.results = results print(formatter.format()) num_failures = len(list(results.failed())) assert num_failures == 0
"""This is structurally equivalent to ../unit/test_jasmine.py. The difference is that it runs igtest.html instead of test.html. also, it is located next to acceptance tests, because it has to be allowed to import components other than adhocracy, like adhocracy_core. """ from pytest import fixture from pytest import mark from adhocracy_frontend.testing import Browser from adhocracy_frontend.testing import browser_test_helper from adhocracy_frontend.tests.unit.console import Parser from adhocracy_frontend.tests.unit.console import Formatter pytestmark = mark.jasmine class TestJasmine: def test_all(self, browser_igtest): data = browser_igtest.evaluate_script('jsApiReporter.specs()') formatter = Formatter([]) parser = Parser() results = parser.parse(data) formatter.results = results print(formatter.format()) num_failures = len(list(results.failed())) assert num_failures == 0
Prepare support for new data source
var Departure = require('./Components/Departure'); var url = 'http://bybussen.api.tmn.io/'; var get = function (path, callback) { return fetch(url + path, { method: 'GET', headers: { 'Content-Type': 'application/json' } }).then(function (response) { return response.json(); }); }; /* * Returns (new_departures, location_id) */ var load_departures = function (location_id) { var promise = new Promise(function (resolve, reject) { get('rt/' + location_id).then(function (responseObject) { var departures = responseObject['next'].map(function (e) { return new Departure(e.l, e.t, e.ts, e.rt, e.d); }); resolve({ departures: departures, location_id: responseObject.locationId ? responseObject.locationId : responseObject.name.match(/(\d+){4}/g)[0] }); }, function (e) { reject({ message: 'Something went wrong' }); }); }); return promise; }; module.exports = { get: get, load_departures: load_departures };
var Departure = require('./Components/Departure'); var url = 'http://bybussen.api.tmn.io/'; var get = function (path, callback) { return fetch(url + path, { method: 'GET', headers: { 'Content-Type': 'application/json' } }).then(function (response) { return response.json(); }); }; /* * Returns (new_departures, location_id) */ var load_departures = function (location_id) { var promise = new Promise(function (resolve, reject) { get('rt/' + location_id).then(function (responseObject) { var departures = responseObject['next'].map(function (e) { return new Departure(e.l, e.t, e.ts, e.rt, e.d); }); resolve({ departures: departures, location_id: responseObject.name.match(/(\d+){4}/g)[0] }); }).catch(function (e) { reject({ message: 'Something went wrong' }); }); }); return promise; }; module.exports = { get: get, load_departures: load_departures };
core: Clean up imports on GetDefaultTimeZoneQuery Replaced * imports with FQCNs. Change-Id: I23ab2fe33408ef7dc05ef4048f7c1418d3e4ef3e
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.queries.VdcQueryParametersBase; import org.ovirt.engine.core.compat.KeyValuePairCompat; import org.ovirt.engine.core.vdsbroker.vdsbroker.SysprepHandler; public class GetDefualtTimeZoneQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> { public GetDefualtTimeZoneQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { String timezone = Config.<String> GetValue(ConfigValues.DefaultTimeZone); getQueryReturnValue().setReturnValue(new KeyValuePairCompat<String, String>(SysprepHandler.getTimezoneKey(timezone), timezone)); } }
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.compat.*; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.queries.*; import org.ovirt.engine.core.vdsbroker.vdsbroker.SysprepHandler; public class GetDefualtTimeZoneQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> { public GetDefualtTimeZoneQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { String timezone = Config.<String> GetValue(ConfigValues.DefaultTimeZone); getQueryReturnValue().setReturnValue(new KeyValuePairCompat<String, String>(SysprepHandler.getTimezoneKey(timezone), timezone)); } }
Set maxZoom = 13 for desktop locate button too.
// GEOSEARCH ///////////////////////////////////////////////////////// window.setupGeosearch = function() { $('#geosearch').keypress(function(e) { if((e.keyCode ? e.keyCode : e.which) != 13) return; var search = $(this).val(); if (!runHooks('geoSearch', search)) { return; } $.getJSON(NOMINATIM + encodeURIComponent(search), function(data) { if(!data || !data[0]) return; var b = data[0].boundingbox; if(!b) return; var southWest = new L.LatLng(b[0], b[2]), northEast = new L.LatLng(b[1], b[3]), bounds = new L.LatLngBounds(southWest, northEast); window.map.fitBounds(bounds); if(window.isSmartphone()) window.smartphone.mapButton.click(); }); e.preventDefault(); }); $('#geosearchwrapper img').click(function(){ map.locate({setView : true, maxZoom: 13});; }); }
// GEOSEARCH ///////////////////////////////////////////////////////// window.setupGeosearch = function() { $('#geosearch').keypress(function(e) { if((e.keyCode ? e.keyCode : e.which) != 13) return; var search = $(this).val(); if (!runHooks('geoSearch', search)) { return; } $.getJSON(NOMINATIM + encodeURIComponent(search), function(data) { if(!data || !data[0]) return; var b = data[0].boundingbox; if(!b) return; var southWest = new L.LatLng(b[0], b[2]), northEast = new L.LatLng(b[1], b[3]), bounds = new L.LatLngBounds(southWest, northEast); window.map.fitBounds(bounds); if(window.isSmartphone()) window.smartphone.mapButton.click(); }); e.preventDefault(); }); $('#geosearchwrapper img').click(function(){ map.locate({setView : true});; }); }
Order by ledger types by name
from openerp.osv import fields, osv from openerp.tools.translate import _ _enum_ledger_type = [ ('ledger_a', _('Ledger A')), ('ledger_b', _('Ledger B')), ('ledger_c', _('Ledger C')), ('ledger_d', _('Ledger D')), ('ledger_e', _('Ledger E')), ] class ledger_type(osv.Model): _name = 'alternate_ledger.ledger_type' _columns = { 'name': fields.char( _('Name'), size=256, required=True), 'type': fields.selection( _enum_ledger_type, _('Ledger Type'), required=True), } _order = 'name' _sql_constraint = [ ('name', "UNIQUE('name')", 'Name has to be unique !'), ]
from openerp.osv import fields, osv from openerp.tools.translate import _ _enum_ledger_type = [ ('ledger_a', _('Ledger A')), ('ledger_b', _('Ledger B')), ('ledger_c', _('Ledger C')), ('ledger_d', _('Ledger D')), ('ledger_e', _('Ledger E')), ] class ledger_type(osv.Model): _name = 'alternate_ledger.ledger_type' _columns = { 'name': fields.char( _('Name'), size=256, required=True), 'type': fields.selection( _enum_ledger_type, _('Ledger Type'), required=True), } _sql_constraint = [ ('name', "UNIQUE('name')", 'Name has to be unique !'), ]
Update and fix some issues updated
<?php namespace phplusir\smsir\Controllers; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Route; use phplusir\smsir\Smsir; use phplusir\smsir\SmsirLogs; class SmsirController extends Controller { // the main index page for administrators public function index() { $credit = Smsir::credit(); $smsir_logs = SmsirLogs::paginate(config('smsir.in-page')); return view('smsir::index',compact('credit','smsir_logs')); } // administrators can delete single log public function delete() { SmsirLogs::where('id',Route::current()->parameters['log'])->delete(); // return the user back to sms-admin after delete the log return back(); } }
<?php namespace phplusir\smsir\Controllers; use App\Http\Controllers\Controller; use phplusir\smsir\Smsir; class SmsirController extends Controller { public function index() { $credit = Smsir::credit(); return view('smsir::index',compact('credit')); } public function send() { $numbers = ['09301240100']; Smsir::send(['تست ارسال علیزاده'],$numbers); } public function addToCustomer() { $send = Smsir::addContactAndSend('آقای','معین','علیزاده','09301240100','این تست برای بخش دوم'); var_dump($send); } public function sendCC() { Smsir::sendToCustomerClub(['سلام'],['09301240100']); } public function verf() { $verf = Smsir::sendVerification('1290839','09301240100'); var_dump($verf); } }
Use new import for napolean
# -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
# -*- coding: utf-8 -*- import sys import os import sphinx_rtd_theme extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinxcontrib.napoleon'] add_module_names = False source_suffix = '.rst' master_doc = 'index' project = u'vspk' copyright = u'2015, Nuage Networks' version = '' release = '' exclude_patterns = ['_build', '../vsdk/autogenerates'] pygments_style = 'sphinx' html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # html_theme = "pyramid" # html_static_path = ['_static'] htmlhelp_basename = '32doc' html_logo = 'nuage-logo.png' autodoc_member_order = "groupwise" autodoc_default_flags = [] napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True
Remove constructor for ContraintViolationException that used DomainEvent to reduce coupling on application layer
/* * Copyright 2014 Click Travel Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.clicktravel.cheddar.domain.model.exception; public class ConstraintViolationException extends IllegalStateException { private static final long serialVersionUID = 3662580310625716490L; public ConstraintViolationException(final String message) { super(message); } public ConstraintViolationException(final String message, final Throwable cause) { super(message, cause); } }
/* * Copyright 2014 Click Travel Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.clicktravel.cheddar.domain.model.exception; import com.clicktravel.cheddar.domain.event.DomainEvent; public class ConstraintViolationException extends IllegalStateException { private static final long serialVersionUID = 3662580310625716490L; private DomainEvent domainEvent; public ConstraintViolationException(final String message) { super(message); } public ConstraintViolationException(final String message, final Throwable cause) { super(message, cause); } public ConstraintViolationException(final DomainEvent domainEvent) { super(domainEvent.type()); this.domainEvent = domainEvent; } public DomainEvent getDomainEvent() { return domainEvent; } }
Replace a video in example because previous one disappeared
// Mithril component which embeds four iframes with HTML videos const MyComponent = { view(controller, args) { return m("div.ba.ma3.pa3.bg-light-purple", [ // The Mother of All Demos, presented by Douglas Engelbart (1968) m("iframe", {src: "//www.youtube.com/embed/yJDv-zdhzMY", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // Alan Kay at OOPSLA 1997 - The computer revolution hasn't happened yet m("iframe", {src: "//www.youtube.com/embed/oKg1hTOQXoY", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // The Lively Kernel presented by Dan Ingalls aa a Google Tech Talks (2008) m("iframe", {src: "//www.youtube.com/embed/gGw09RZjQf8", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // Twirlip Civic Sensemaking Project Overview (2011) m("iframe", {src: "//www.youtube.com/embed/_mRy4sGK7xk", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), ]) } } Twirlip7.show(MyComponent, { title: "Videos on the future, the present, and the past" } )
// Mithril component which embeds four iframes with HTML videos const MyComponent = { view(controller, args) { return m("div.ba.ma3.pa3.bg-light-purple", [ // Passengers 2016 - Starship Avalon Slingshot Around The Red Giant Star Arcturus m("iframe", {src: "//www.youtube.com/embed/1jGRpuzrkpk", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // Alan Kay at OOPSLA 1997 - The computer revolution hasn't happened yet m("iframe", {src: "//www.youtube.com/embed/oKg1hTOQXoY", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // The Mother of All Demos, presented by Douglas Engelbart (1968) m("iframe", {src: "//www.youtube.com/embed/yJDv-zdhzMY", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), // Twirlip Civic Sensemaking Project Overview m("iframe", {src: "//www.youtube.com/embed/_mRy4sGK7xk", width: 800, height: 600, frameborder: "0", allowfullscreen: true}), ]) } } Twirlip7.show(MyComponent, { title: "Videos on the future, the present, and the past" } )
Return out of Pixelator.picker if no keys are provided
var Pixelator = function(data, partner) { this.data = data; this.partner = partner; }; Pixelator.prototype = { defaults: function() { var default_context = this.data.context || {}; default_context.timestamp = new Date().getTime(); return default_context; }, picker: function(key, options) { var self = this; var keys = self.data.pixels[key]; if (!keys) { return; } _.each(keys, function(pixel) { if (pixel.partner && self.partner !== pixel.partner) { return; } var gp = new GenericPixel({ context: options, pixel: pixel }); gp.insert(); }); }, run: function(key, options) { options = _(options || {}).extend(this.defaults()); this.picker(key, options); } }
var Pixelator = function(data, partner) { this.data = data; this.partner = partner; }; Pixelator.prototype = { defaults: function() { var default_context = this.data.context || {}; default_context.timestamp = new Date().getTime(); return default_context; }, picker: function(key, options) { var self = this; _.each(this.data.pixels[key], function(pixel) { if (pixel.partner && self.partner !== pixel.partner) { return; } var gp = new GenericPixel({ context: options, pixel: pixel }); gp.insert(); }); }, run: function(key, options) { options = _(options || {}).extend(this.defaults()); this.picker(key, options); } }
Remove no reset for devicefarm
import os import pytest from appium import webdriver @pytest.fixture(scope='function') def driver(request): return get_driver(request, default_capabilities()) @pytest.fixture(scope='function') def no_reset_driver(request): desired_caps = default_capabilities() desired_caps['noReset'] = (runs_on_aws() == True and False or True) return get_driver(request, desired_caps) def get_driver(request, desired_caps): _driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps) request.addfinalizer(_driver.quit) return _driver def runs_on_aws(): return os.getenv('SCREENSHOT_PATH', False) != False def default_capabilities(): app = os.path.abspath('aws/Build/Products/Release-iphonesimulator/AwesomeProject.app') desired_caps = {} if runs_on_aws() == False: desired_caps['platformName'] = 'iOS' desired_caps['platformVersion'] = '10.3' desired_caps['deviceName'] = 'iPhone Simulator' desired_caps['app'] = app return desired_caps
import os import pytest from appium import webdriver @pytest.fixture(scope='function') def driver(request): return get_driver(request, default_capabilities()) @pytest.fixture(scope='function') def no_reset_driver(request): desired_caps = default_capabilities() desired_caps['noReset'] = True return get_driver(request, desired_caps) def get_driver(request, desired_caps): _driver = webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities=desired_caps) request.addfinalizer(_driver.quit) return _driver def default_capabilities(): app = os.path.abspath('aws/Build/Products/Release-iphonesimulator/AwesomeProject.app') screenshot_folder = os.getenv('SCREENSHOT_PATH', '') desired_caps = {} if screenshot_folder == '': desired_caps['platformName'] = 'iOS' desired_caps['platformVersion'] = '10.3' desired_caps['deviceName'] = 'iPhone Simulator' desired_caps['app'] = app return desired_caps
Fix wrong output stream usage
#!/usr/bin/env python2 # coding=utf-8 """ Implements reused sanity checks """ import os import sys from gitver.termcolors import term, bold from gitver.defines import PRJ_ROOT, CFGDIR, CFGDIRNAME, GITIGNOREFILE def check_project_root(): if len(PRJ_ROOT) == 0: term.err("Couldn't determine your project's root directory, is this " "a valid git repository?") sys.exit(1) def check_config(): # check config directory exists if not os.path.exists(CFGDIR): term.err("Please run " + bold("gitver init") + " first.") sys.exit(1) def check_gitignore(exit_on_error=True): # check .gitignore for .gitver inclusion try: gifile = os.path.join(GITIGNOREFILE) with open(gifile, 'r') as f: if CFGDIRNAME in f.read(): return except IOError: pass term.warn("Warning: it's highly recommended to EXCLUDE the gitver " "configuration from the repository!") term.prn("Please include the following line in your .gitignore file:") term.prn(" " + CFGDIRNAME) if exit_on_error: sys.exit(1) else: print ""
#!/usr/bin/env python2 # coding=utf-8 """ Implements reused sanity checks """ import os import sys from gitver.termcolors import term, bold from gitver.defines import PRJ_ROOT, CFGDIR, CFGDIRNAME, GITIGNOREFILE def check_project_root(): if len(PRJ_ROOT) == 0: term.err("Couldn't determine your project's root directory, is this " "a valid git repository?") sys.exit(1) def check_config(): # check config directory exists if not os.path.exists(CFGDIR): term.prn("Please run " + bold("gitver init") + " first.") sys.exit(1) def check_gitignore(exit_on_error=True): # check .gitignore for .gitver inclusion try: gifile = os.path.join(GITIGNOREFILE) with open(gifile, 'r') as f: if CFGDIRNAME in f.read(): return except IOError: pass term.warn("Warning: it's highly recommended to EXCLUDE the gitver " "configuration from the repository!") term.prn("Please include the following line in your .gitignore file:") term.prn(" " + CFGDIRNAME) if exit_on_error: sys.exit(1) else: print ""
Fix null exception if no ghosts found
package com.pm.server.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.pm.server.datatype.Coordinate; import com.pm.server.player.Ghost; import com.pm.server.player.GhostRepository; @RestController @RequestMapping("/ghost") public class GhostControllerImpl implements GhostController { @Autowired private GhostRepository ghostRepository; @Override @RequestMapping( value="/integer", method=RequestMethod.GET ) public int getInteger() { return 0; } // Returns map of ghost id to location @Override @RequestMapping( value="/locations", method=RequestMethod.GET, produces={ "application/json" } ) public Map<Integer, Coordinate> getAllLocations() { List<Ghost> ghosts = ghostRepository.getAllGhosts(); Map<Integer, Coordinate> ghostsLocations = new HashMap<Integer, Coordinate>(); if(ghosts != null) { for(Ghost ghost : ghosts) { ghostsLocations.put(ghost.getId(), ghost.getLocation()); } } return ghostsLocations; } }
package com.pm.server.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.pm.server.datatype.Coordinate; import com.pm.server.player.Ghost; import com.pm.server.player.GhostRepository; @RestController @RequestMapping("/ghost") public class GhostControllerImpl implements GhostController { @Autowired private GhostRepository ghostRepository; @Override @RequestMapping( value="/integer", method=RequestMethod.GET ) public int getInteger() { return 0; } // Returns map of ghost id to location @Override @RequestMapping( value="/locations", method=RequestMethod.GET ) public Map<Integer, Coordinate> getAllLocations() { List<Ghost> ghosts = ghostRepository.getAllGhosts(); Map<Integer, Coordinate> ghostsLocations = new HashMap<Integer, Coordinate>(); for(Ghost ghost : ghosts) { ghostsLocations.put(ghost.getId(), ghost.getLocation()); } return ghostsLocations; } }
Allow inputs inside forest tables
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a, input').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { if ( e.metaKey || e.ctrlKey ) { window.open( url, '_blank' ); } else if ( e.shiftKey ) { window.open( url, '_blank' ); window.focus(); } else { Turbolinks.visit(url); } } } });
// Forest tables $(document).on('mouseenter', '.forest-table tbody tr', function() { var $row = $(this); $row.addClass('active'); $(document).one('turbolinks:before-cache.forestTables', function() { $row.removeClass('active'); }); }); $(document).on('mouseleave', '.forest-table tbody tr', function() { var $row = $(this); $row.removeClass('active'); }); $(document).on('click', '.forest-table tbody tr', function(e) { var $row = $(this); if ( !$(e.target).closest('a').length ) { var $button = $row.find('a.forest-table__link:first'); if ( !$button.length ) { $button = $row.find('a.btn-primary:first'); } var url = $button.attr('href'); if ( url ) { if ( e.metaKey || e.ctrlKey ) { window.open( url, '_blank' ); } else if ( e.shiftKey ) { window.open( url, '_blank' ); window.focus(); } else { Turbolinks.visit(url); } } } });
tests: Add "Installation finished check" step Step that asks libvirt every minute if VM state is installed. Step fails after specified amount of time, if not. https://bugzilla.gnome.org/show_bug.cgi?id=748006
#!/usr/bin/python from __future__ import unicode_literals import libvirt from time import sleep from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None @step('Installation of "{machine}" is finished in "{max_time}" minutes') def check_finished_installation(context, machine, max_time): minutes = 0 state = None while minutes < max_time: state = libvirt_domain_get_install_state(machine) if state == 'installed': break else: sleep(60) assert state == 'installed', "%s is not installed but still in %s after %s minutes" %(machine, state, max_time)
#!/usr/bin/python from __future__ import unicode_literals import libvirt from general import libvirt_domain_get_val, libvirt_domain_get_context def libvirt_domain_get_install_state(title): state = None conn = libvirt.openReadOnly(None) doms = conn.listAllDomains() for dom in doms: try: dom0 = conn.lookupByName(dom.name()) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % name) ctx = libvirt_domain_get_context(dom0) if libvirt_domain_get_val(ctx, "/domain/title") == title: return libvirt_domain_get_val(ctx, "/domain/metadata/*/os-state") return None
Test if the toList() method is returning the correct array values
<?php use Galahad\LaravelAddressing\Country; use Galahad\LaravelAddressing\CountryCollection; /** * Class CountryCollectionTest * * @author Junior Grossi <juniorgro@gmail.com> */ class CountryCollectionTest extends PHPUnit_Framework_TestCase { public function testCountryCollectionClass() { $collection = new CountryCollection(); $country = new Country; $countries = ['Brazil', 'United States', 'Argentina', 'Canada', 'Chile']; foreach ($countries as $countryName) { $collection->insert($country->findByName($countryName)); } /** @var Country $country */ foreach ($collection as $key => $country) { $this->assertEquals($country->getName(), $countries[$key]); } } public function testToListFeature() { $factory = new Country; $expected = ['BR' => 'Brazil', 'US' => 'United States']; $collection = new CountryCollection(); $collection->insert([ $factory->findByCode('BR'), $factory->findByCode('US'), ]); $this->assertEquals($collection->toList(), $expected); } }
<?php use Galahad\LaravelAddressing\Country; use Galahad\LaravelAddressing\CountryCollection; /** * Class CountryCollectionTest * * @author Junior Grossi <juniorgro@gmail.com> */ class CountryCollectionTest extends PHPUnit_Framework_TestCase { public function testCountryCollectionClass() { $collection = new CountryCollection(); $country = new Country; $countries = ['Brazil', 'United States', 'Argentina', 'Canada', 'Chile']; foreach ($countries as $countryName) { $collection->insert($country->findByName($countryName)); } /** @var Country $country */ foreach ($collection as $key => $country) { $this->assertEquals($country->getName(), $countries[$key]); } } }
Use random starting index for roundrobin
package selector import ( "math/rand" "sync" "time" "github.com/micro/go-micro/registry" ) func init() { rand.Seed(time.Now().UnixNano()) } // Random is a random strategy algorithm for node selection func Random(services []*registry.Service) Next { var nodes []*registry.Node for _, service := range services { nodes = append(nodes, service.Nodes...) } return func() (*registry.Node, error) { if len(nodes) == 0 { return nil, ErrNoneAvailable } i := rand.Int() % len(nodes) return nodes[i], nil } } // RoundRobin is a roundrobin strategy algorithm for node selection func RoundRobin(services []*registry.Service) Next { var nodes []*registry.Node for _, service := range services { nodes = append(nodes, service.Nodes...) } var i = rand.Int() var mtx sync.Mutex return func() (*registry.Node, error) { if len(nodes) == 0 { return nil, ErrNoneAvailable } mtx.Lock() node := nodes[i%len(nodes)] i++ mtx.Unlock() return node, nil } }
package selector import ( "math/rand" "sync" "time" "github.com/micro/go-micro/registry" ) func init() { rand.Seed(time.Now().UnixNano()) } // Random is a random strategy algorithm for node selection func Random(services []*registry.Service) Next { var nodes []*registry.Node for _, service := range services { nodes = append(nodes, service.Nodes...) } return func() (*registry.Node, error) { if len(nodes) == 0 { return nil, ErrNoneAvailable } i := rand.Int() % len(nodes) return nodes[i], nil } } // RoundRobin is a roundrobin strategy algorithm for node selection func RoundRobin(services []*registry.Service) Next { var nodes []*registry.Node for _, service := range services { nodes = append(nodes, service.Nodes...) } var i int var mtx sync.Mutex return func() (*registry.Node, error) { if len(nodes) == 0 { return nil, ErrNoneAvailable } mtx.Lock() node := nodes[i%len(nodes)] i++ mtx.Unlock() return node, nil } }
Add support for prepare statement hardening
<?php // -- include/functions/utilities.php // --------------------------------------------------------------------------------------------- /** * string get_permalink_by_slug( string $slug [, string $post_type = 'post'] ) * Retrieves the permalink of the post with the given slug and post type. * * @param string $slug The post slug. * @param string $post_type The post type (shocking, I know). * * @return string The generated permalink. * ------------------------------------------------------------------------------------------ */ function get_permalink_by_slug( $slug, $post_type = 'post' ) { if ( empty( $slug ) ) return; global $wpdb; $sql = $wpdb->prepare( "SELECT `ID` FROM {$wpdb->posts} WHERE `post_type`='%s' AND `post_name`='%s' AND `post_status`='publish';", $post_type, $slug ); $ID = $wpdb->get_var( $sql ); if ( !empty( $ID ) ) return get_permalink( $ID ); }
<?php // -- include/functions/utilities.php // --------------------------------------------------------------------------------------------- /** * string get_permalink_by_slug( string $slug [, string $post_type = 'post'] ) * Retrieves the permalink of the post with the given slug and post type. * * @param string $slug The post slug. * @param string $post_type The post type (shocking, I know). * * @return string The generated permalink. * ------------------------------------------------------------------------------------------ */ function get_permalink_by_slug( $slug, $post_type = 'post' ) { if ( empty( $slug ) ) return; global $wpdb; $sql = $wpdb->prepare( 'SELECT `ID` FROM `%1$s` WHERE `post_type`="%2$s" AND `post_name`="%3$s" AND `post_status`="publish";', $wpdb->posts, $post_type, $slug ); $ID = $wpdb->get_var( $sql ); if ( !empty( $ID ) ) return get_permalink( $ID ); }
Fix Python 2 compatibility, again
"Common functions that may be used everywhere" from __future__ import print_function import os import sys from distutils.util import strtobool try: input = raw_input except NameError: pass def yes_no_query(question): """Ask the user *question* for 'yes' or 'no'; ask again until user inputs a valid option. Returns: 'True' if user answered 'y', 'yes', 't', 'true', 'on' or '1'. 'False' if user answered 'n', 'no', 'f', 'false', 'off' or '0'. """ print("{} (y/n)".format(question), end=" "), while True: try: return strtobool(input().lower()) except ValueError: print("Please respond with 'y' or 'n'.") def ask_overwrite(dest): """Check if file *dest* exists. If 'True', asks if the user wants to overwrite it (just remove the file for later overwrite). """ msg = "File '{}' already exists. Overwrite file?".format(dest) if os.path.exists(dest): if yes_no_query(msg): os.remove(dest) else: sys.exit("Cancelling operation...")
"Common functions that may be used everywhere" from __future__ import print_function import os import sys from distutils.util import strtobool def yes_no_query(question): """Ask the user *question* for 'yes' or 'no'; ask again until user inputs a valid option. Returns: 'True' if user answered 'y', 'yes', 't', 'true', 'on' or '1'. 'False' if user answered 'n', 'no', 'f', 'false', 'off' or '0'. """ print("{} (y/n)".format(question), end=" "), while True: try: return strtobool(input().lower()) except ValueError: print("Please respond with 'y' or 'n'.") def ask_overwrite(dest): """Check if file *dest* exists. If 'True', asks if the user wants to overwrite it (just remove the file for later overwrite). """ msg = "File '{}' already exists. Overwrite file?".format(dest) if os.path.exists(dest): if yes_no_query(msg): os.remove(dest) else: sys.exit("Cancelling operation...")
Fix: Remove slash at the end of APPLICATION_URL This corrects an issue when trying to navigate links.
package io.katharsis.example.jersey; import com.fasterxml.jackson.databind.ObjectMapper; import io.katharsis.locator.SampleJsonServiceLocator; import io.katharsis.queryParams.DefaultQueryParamsParser; import io.katharsis.queryParams.QueryParamsBuilder; import io.katharsis.rs.KatharsisFeature; import io.katharsis.rs.KatharsisProperties; import org.glassfish.jersey.server.ResourceConfig; import javax.ws.rs.ApplicationPath; @ApplicationPath("/") public class JerseyApplication extends ResourceConfig { public static final String APPLICATION_URL = "http://localhost:8080"; public JerseyApplication() { property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "io.katharsis.example.jersey.domain"); property(KatharsisProperties.RESOURCE_DEFAULT_DOMAIN, APPLICATION_URL); register(new KatharsisFeature(new ObjectMapper(), new QueryParamsBuilder(new DefaultQueryParamsParser()), new SampleJsonServiceLocator())); } }
package io.katharsis.example.jersey; import com.fasterxml.jackson.databind.ObjectMapper; import io.katharsis.locator.SampleJsonServiceLocator; import io.katharsis.queryParams.DefaultQueryParamsParser; import io.katharsis.queryParams.QueryParamsBuilder; import io.katharsis.rs.KatharsisFeature; import io.katharsis.rs.KatharsisProperties; import org.glassfish.jersey.server.ResourceConfig; import javax.ws.rs.ApplicationPath; @ApplicationPath("/") public class JerseyApplication extends ResourceConfig { public static final String APPLICATION_URL = "http://localhost:8080/"; public JerseyApplication() { property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "io.katharsis.example.jersey.domain"); property(KatharsisProperties.RESOURCE_DEFAULT_DOMAIN, APPLICATION_URL); register(new KatharsisFeature(new ObjectMapper(), new QueryParamsBuilder(new DefaultQueryParamsParser()), new SampleJsonServiceLocator())); } }
Fix example uploadr - wrong FieldList import
from flask import Flask, render_template from flask_wtf import Form from flask_wtf.file import FileField from wtforms import FieldList class FileUploadForm(Form): uploads = FieldList(FileField()) DEBUG = True SECRET_KEY = 'secret' app = Flask(__name__) app.config.from_object(__name__) @app.route("/", methods=("GET", "POST",)) def index(): form = FileUploadForm() for i in xrange(5): form.uploads.append_entry() filedata = [] if form.validate_on_submit(): for upload in form.uploads.entries: filedata.append(upload) return render_template("index.html", form=form, filedata=filedata) if __name__ == "__main__": app.run()
from flask import Flask, render_template from flask_wtf import Form from flask_wtf.file import FileField, FieldList class FileUploadForm(Form): uploads = FieldList(FileField()) DEBUG = True SECRET_KEY = 'secret' app = Flask(__name__) app.config.from_object(__name__) @app.route("/", methods=("GET", "POST",)) def index(): form = FileUploadForm() for i in xrange(5): form.uploads.append_entry() filedata = [] if form.validate_on_submit(): for upload in form.uploads.entries: filedata.append(upload) return render_template("index.html", form=form, filedata=filedata) if __name__ == "__main__": app.run()
Update SHOW TYPES command to handle no types being created
from enum import Enum from graphene.commands.command import Command from graphene.utils import PrettyPrinter class ShowCommand(Command): class ShowType(Enum): TYPES = 1 RELATIONS = 2 def __init__(self, show_type): self.show_type = show_type def execute(self, storage_manager): if self.show_type == ShowCommand.ShowType.TYPES: i = 1 type_list = [] while True: cur_type = storage_manager.type_manager.get_item_at_index(i) if cur_type is None: break type_name = storage_manager.type_name_manager \ .read_name_at_index(cur_type.nameId) type_list.append(type_name) i += 1 if len(type_list) == 0: print "No types found." return PrettyPrinter.print_list(type_list, "Type Name")
from enum import Enum from graphene.commands.command import Command from graphene.utils import PrettyPrinter class ShowCommand(Command): class ShowType(Enum): TYPES = 1 RELATIONS = 2 def __init__(self, show_type): self.show_type = show_type def execute(self, storage_manager): if self.show_type == ShowCommand.ShowType.TYPES: i = 1 type_list = [] while True: cur_type = storage_manager.type_manager.get_item_at_index(i) if cur_type is None: break type_name = storage_manager.type_name_manager \ .read_name_at_index(cur_type.nameId) type_list.append(type_name) i += 1 PrettyPrinter.print_list(type_list, "Type Name")
Send timestamps as ISO8601 format
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import datetime import json import re def camelcase(value): """ Convert a module name or string with underscores and periods to camel case. :param value: the string to convert :type value: str :returns: the value converted to camel case. """ return ''.join(x.capitalize() if x else '_' for x in re.split("[._]+", value)) class JsonEncoder(json.JSONEncoder): """ This extends the standard json.JSONEncoder to allow for more types to be sensibly serialized. This is used in Girder's REST layer to serialize route return values when JSON is requested. """ def default(self, obj): if isinstance(obj, set): return tuple(obj) elif isinstance(obj, datetime.datetime): return obj.isoformat() return str(obj)
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### import json import re def camelcase(value): """ Convert a module name or string with underscores and periods to camel case. :param value: the string to convert :type value: str :returns: the value converted to camel case. """ return ''.join(x.capitalize() if x else '_' for x in re.split("[._]+", value)) class JsonEncoder(json.JSONEncoder): """ This extends the standard json.JSONEncoder to allow for more types to be sensibly serialized. This is used in Girder's REST layer to serialize route return values when JSON is requested. """ def default(self, obj): if isinstance(obj, set): return tuple(obj) return str(obj)
Add DOM's `change` event for client-side UJS handlers.
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input', 'change'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); event.preventDefault(); return false; }); }); });
/** * Assigns handlers/listeners for `[data-action]` links. * * Actions associated with a link will be invoked via Wire with the jQuery * event object as an argument. **/ 'use strict'; /*global NodecaLoader, N, window*/ var $ = window.jQuery; $(function () { ['click', 'submit', 'input'].forEach(function (action) { var eventName = action + '.nodeca.data-api' , attribute = '[data-on-' + action + ']'; $('body').on(eventName, attribute, function (event) { var apiPath = $(this).data('on-' + action); NodecaLoader.loadAssets(apiPath.split('.').shift(), function () { if (N.wire.has(apiPath)) { N.wire.emit(apiPath, event); } else { N.logger.error('Unknown client Wire handler: %s', apiPath); } }); event.preventDefault(); return false; }); }); });
Fix module names for pytest. We've shifted the directories but we still have the following horrid code for determining the module name to mock. Eventually we should switch to patch object (much more modern and use the module under test directly).
"""Common testing bits.""" # Copyright (C) 2014 by Alex Brandt <alunduil@alunduil.com> # # etest is freely distributable under the terms of an MIT-style license. # See COPYING or http://www.opensource.org/licenses/mit-license.php. import logging import re import unittest from typing import Set from etest_test import helpers_test logger = logging.getLogger(__name__) class BaseEtestTest(unittest.TestCase): """Base Etest Test.""" mocks_mask: Set = set() mocks: Set = set() @property def real_module(self): """Name of the real module.""" return re.sub(r"\.[^.]+", "", self.__module__.replace("_test", ""), 1) def _patch(self, name): logger.debug("mocking %s", self.real_module + "." + name) _ = unittest.mock.patch(self.real_module + "." + name) setattr(self, "mocked_" + name.replace(".", "_").strip("_"), _.start()) self.addCleanup(_.stop) mocks.add("ebuild") @helpers_test.mock("ebuild") def mock_ebuild(self): """Mock ebuild.""" self._patch("ebuild")
"""Common testing bits.""" # Copyright (C) 2014 by Alex Brandt <alunduil@alunduil.com> # # etest is freely distributable under the terms of an MIT-style license. # See COPYING or http://www.opensource.org/licenses/mit-license.php. import logging import re import unittest from typing import Set from etest_test import helpers_test logger = logging.getLogger(__name__) class BaseEtestTest(unittest.TestCase): """Base Etest Test.""" mocks_mask: Set = set() mocks: Set = set() @property def real_module(self): """Name of the real module.""" return re.sub(r"\.[^.]+", "", self.__module__.replace("test_", ""), 1) def _patch(self, name): logger.debug("mocking %s", self.real_module + "." + name) _ = unittest.mock.patch(self.real_module + "." + name) setattr(self, "mocked_" + name.replace(".", "_").strip("_"), _.start()) self.addCleanup(_.stop) mocks.add("ebuild") @helpers_test.mock("ebuild") def mock_ebuild(self): """Mock ebuild.""" self._patch("ebuild")
Use the tunnel identifier from Travis
const externals = require('./externals.conf.js'); const base = require('./karma.conf.js'); module.exports = function(config) { if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) { console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.') process.exit(1) } // Apply base config base(config); // Then add Sauce Labs setup const customLaunchers = { sl_safari: { base: 'SauceLabs', browserName: 'safari', version: '11', }, sl_firefox: { base: 'SauceLabs', browserName: 'firefox', version: '56', }, }; const reporters = config.reporters; reporters.push('saucelabs'); // Apply additional config config.set({ reporters, customLaunchers, browsers: config.browsers.concat(Object.keys(customLaunchers)), sauceLabs: { startConnect: false, tunnelIdentifier: process.env['TRAVIS_JOB_NUMBER'], testName: 'NoFlo UI browser tests', recordScreenshots: false, connectOptions: { port: 5757, logfile: 'sauce_connect.log' }, public: 'public' }, captureTimeout: 120000, concurrency: 1, }); }
const externals = require('./externals.conf.js'); const base = require('./karma.conf.js'); module.exports = function(config) { if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) { console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.') process.exit(1) } // Apply base config base(config); // Then add Sauce Labs setup const customLaunchers = { sl_safari: { base: 'SauceLabs', browserName: 'safari', version: '11', }, sl_firefox: { base: 'SauceLabs', browserName: 'firefox', version: '56', }, }; const reporters = config.reporters; reporters.push('saucelabs'); // Apply additional config config.set({ reporters, customLaunchers, browsers: config.browsers.concat(Object.keys(customLaunchers)), sauceLabs: { testName: 'NoFlo UI browser tests', recordScreenshots: false, connectOptions: { port: 5757, logfile: 'sauce_connect.log' }, public: 'public' }, captureTimeout: 120000, concurrency: 1, }); }
[FIX] sale_analytic_cost: Change dependency with "mrp_production_project_estimated_cost" by dependecy "mrp_production_estimated_cost".
# -*- coding: utf-8 -*- # (c) 2015 Ainara Galdona - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Sale Analytic Cost', "version": "8.0.1.0.0", "license": 'AGPL-3', "author": 'AvanzOSC,' 'Serv. Tecnol. Avanzados - Pedro M. Baeza', 'website': "http://www.odoomrp.com", "contributors": [ "Ainara Galdona <ainaragaldona@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], 'category': 'Sales', 'depends': ['sale', 'account', 'mrp_production_estimated_cost'], 'data': [], 'installable': True, }
# -*- coding: utf-8 -*- # (c) 2015 Ainara Galdona - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html { 'name': 'Sale Analytic Cost', "version": "8.0.1.0.0", "license": 'AGPL-3', "author": 'AvanzOSC,' 'Serv. Tecnol. Avanzados - Pedro M. Baeza', 'website': "http://www.odoomrp.com", "contributors": [ "Ainara Galdona <ainaragaldona@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>", "Ana Juaristi <anajuaristi@avanzosc.es>", ], 'category': 'Sales', 'depends': ['sale', 'account', 'mrp_production_project_estimated_cost'], 'data': [], 'installable': True, }
Fix allExitsReturnTrue() always returning true itself.
package uk.ac.cam.gpe21.droidssl.analysis.util; import soot.RefType; import soot.Unit; import soot.jimple.IntConstant; import soot.jimple.ReturnStmt; import soot.toolkits.exceptions.ThrowableSet; import soot.toolkits.exceptions.UnitThrowAnalysis; import soot.toolkits.graph.UnitGraph; public final class FlowGraphUtils { public static boolean anyExitThrowsException(UnitGraph graph, RefType exceptionType) { for (Unit unit : graph.getTails()) { ThrowableSet set = UnitThrowAnalysis.v().mightThrow(unit); if (set.catchableAs(exceptionType)) { return true; } } return false; } public static boolean allExitsReturnTrue(UnitGraph graph) { for (Unit unit : graph.getTails()) { if (unit instanceof ReturnStmt) { ReturnStmt stmt = (ReturnStmt) unit; if (!stmt.getOp().equals(IntConstant.v(1))) { return false; } } } return true; } private FlowGraphUtils() { /* to prevent instantiation */ } }
package uk.ac.cam.gpe21.droidssl.analysis.util; import soot.RefType; import soot.Unit; import soot.jimple.IntConstant; import soot.jimple.ReturnStmt; import soot.toolkits.exceptions.ThrowableSet; import soot.toolkits.exceptions.UnitThrowAnalysis; import soot.toolkits.graph.UnitGraph; public final class FlowGraphUtils { public static boolean anyExitThrowsException(UnitGraph graph, RefType exceptionType) { for (Unit unit : graph.getTails()) { ThrowableSet set = UnitThrowAnalysis.v().mightThrow(unit); if (set.catchableAs(exceptionType)) { return true; } } return false; } public static boolean allExitsReturnTrue(UnitGraph graph) { for (Unit unit : graph.getTails()) { if (unit instanceof ReturnStmt) { ReturnStmt stmt = (ReturnStmt) unit; if (!stmt.getOp().equals(IntConstant.v(1))) { return true; } } } return true; } private FlowGraphUtils() { /* to prevent instantiation */ } }
Increase default batch size for align step
from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import Argument from tmlib.workflow import register_batch_args from tmlib.workflow import register_submission_args @register_batch_args('align') class AlignBatchArguments(BatchArguments): ref_cycle = Argument( type=int, required=True, flag='c', help='''zero-based index of the cycle whose sites should be used as reference ''' ) ref_wavelength = Argument( type=str, required=True, flag='w', help='name of the wavelength whose images should be used as reference' ) batch_size = Argument( type=int, default=100, flag='b', help='number of image files that should be processed per job' ) @register_submission_args('align') class AlignSubmissionArguments(SubmissionArguments): pass
from tmlib.workflow.args import BatchArguments from tmlib.workflow.args import SubmissionArguments from tmlib.workflow.args import Argument from tmlib.workflow import register_batch_args from tmlib.workflow import register_submission_args @register_batch_args('align') class AlignBatchArguments(BatchArguments): ref_cycle = Argument( type=int, required=True, flag='c', help='''zero-based index of the cycle whose sites should be used as reference ''' ) ref_wavelength = Argument( type=str, required=True, flag='w', help='name of the wavelength whose images should be used as reference' ) batch_size = Argument( type=int, default=10, flag='b', help='number of image files that should be processed per job' ) @register_submission_args('align') class AlignSubmissionArguments(SubmissionArguments): pass
Use command gateway instead of command bus to generate commands
/* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.gateway.CommandGateway; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private CommandGateway commandGateway; @RequestMapping(value = "/hello") public String say() { commandGateway.send(new CreateAccountCommand("1234", 1000)); commandGateway.send(new WithdrawMoneyCommand("1234", 800)); commandGateway.send(new WithdrawMoneyCommand("1234", 500)); return "Hello!"; } }
/* * Copyright (c) 2017 General Electric Company. All rights reserved. * * The copyright to the computer software herein is the property of General Electric Company. * The software may be used and/or copied only with the written permission of * General Electric Company or in accordance with the terms and conditions stipulated in the * agreement/contract under which the software has been supplied. */ package org.axonframework.sample.axonbank.myaxonbank; import org.axonframework.commandhandling.CommandBus; import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand; import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.axonframework.commandhandling.GenericCommandMessage.asCommandMessage; @RestController public class MyController { @Autowired private CommandBus commandBus; @RequestMapping(value = "/hello") public String say() { System.out.println("Command Bus>>>>" + commandBus); commandBus.dispatch(asCommandMessage(new CreateAccountCommand("1234", 1000))); commandBus.dispatch(asCommandMessage(new WithdrawMoneyCommand("1234", 800))); return "Hello!"; } }
Move retrieving output into method.
import subprocess import unittest class CompareErrorMessages(unittest.TestCase): def test_missing_file_return_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] ret = subprocess.call(args) args2 = ['ls', 'foo'] ret2 = subprocess.call(args2) self.assertEqual(ret == 0, ret2 == 0) def get_output(self, args): try: msg = subprocess.check_output(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg = e.output return msg def test_missing_file_message_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] msg = self.get_output(args) args2 = ['ls', 'foo'] msg2 = self.get_output(args2) self.assertEqual(msg, msg2)
import subprocess import unittest class CompareErrorMessages(unittest.TestCase): def test_missing_file_return_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] ret = subprocess.call(args) args2 = ['ls', 'foo'] ret2 = subprocess.call(args2) self.assertEqual(ret == 0, ret2 == 0) def test_missing_file_message_code_the_same_as_ls(self): args = ['./lss.sh', 'foo'] try: subprocess.check_output(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg = e.output args2 = ['ls', 'foo'] try: subprocess.check_output(args2, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: msg2 = e.output self.assertEqual(msg, msg2)
Add scan_steps wrapper for scan_nd
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh d2scan = hxntools.scans.d2scan a2scan = hxntools.scans.a2scan scan_steps = hxntools.scans.scan_steps gs.DETS = [zebra, sclr1, merlin1, xspress3, lakeshore2] gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch5_calc', 'ssx', 'ssy', 'ssz', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_Cr' gs.OVERPLOT = False gs.BASELINE_DEVICES = [dcm, m1, m2, beamline_status, smll, vmll, hmll, ssa2, zp]
# vim: sw=4 ts=4 sts expandtab smarttab # HXN step-scan configuration import hxntools.scans from bluesky.global_state import get_gs gs = get_gs() hxntools.scans.setup() ct = hxntools.scans.count ascan = hxntools.scans.absolute_scan dscan = hxntools.scans.relative_scan fermat = hxntools.scans.relative_fermat spiral = hxntools.scans.relative_spiral mesh = hxntools.scans.absolute_mesh dmesh = hxntools.scans.relative_mesh d2scan = hxntools.scans.d2scan a2scan = hxntools.scans.a2scan gs.DETS = [zebra, sclr1, merlin1, xspress3, lakeshore2] gs.TABLE_COLS = ['sclr1_ch2','sclr1_ch3', 'sclr1_ch4', 'sclr1_ch5_calc', 'ssx', 'ssy', 'ssz', 't_base', 't_sample', 't_vlens', 't_hlens'] # Plot this by default versus motor position: gs.PLOT_Y = 'Det2_Cr' gs.OVERPLOT = False gs.BASELINE_DEVICES = [smll,vmll, hmll, ssa2, zp]
Make sure that ID will not match the first CartItems rule EVERY time ("//" was in regex).
from django.conf.urls.defaults import url, patterns from shop.views.cart import CartDetails, CartItemDetail urlpatterns = patterns('', url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE name='cart_delete'), url('^item/$', CartDetails.as_view(action='post'), # POST name='cart_item_add'), url(r'^$', CartDetails.as_view(), name='cart'), # GET url(r'^update/$', CartDetails.as_view(action='put'), name='cart_update'), # CartItems url('^item/(?P<id>[0-9]+)$', CartItemDetail.as_view(), name='cart_item'), url('^item/(?P<id>[0-9]+)/delete$', CartItemDetail.as_view(action='delete'), name='cart_item_delete'), )
from django.conf.urls.defaults import url, patterns from shop.views.cart import CartDetails, CartItemDetail urlpatterns = patterns('', url(r'^delete/$', CartDetails.as_view(action='delete'), # DELETE name='cart_delete'), url('^item/$', CartDetails.as_view(action='post'), # POST name='cart_item_add'), url(r'^$', CartDetails.as_view(), name='cart'), # GET url(r'^update/$', CartDetails.as_view(action='put'), name='cart_update'), # CartItems url('^item/(?P<id>[0-9A-Za-z-_.//]+)$', CartItemDetail.as_view(), name='cart_item'), url('^item/(?P<id>[0-9A-Za-z-_.//]+)/delete$', CartItemDetail.as_view(action='delete'), name='cart_item_delete'), )
Migrate public test to phpunit 5
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Exporter\Test; use PHPUnit\Framework\TestCase; use Sonata\Exporter\Writer\TypedWriterInterface; /** * @author Grégoire Paris <postmaster@greg0ire.fr> */ abstract class AbstractTypedWriterTestCase extends TestCase { /** * @var WriterInterface */ private $writer; protected function setUp(): void { $this->writer = $this->getWriter(); } public function testFormatIsString(): void { $this->assertInternalType('string', $this->writer->getFormat()); } public function testDefaultMimeTypeIsString(): void { $this->assertInternalType('string', $this->writer->getDefaultMimeType()); } /** * Should return a very simple instance of the writer (no need for complex * configuration). * * @return WriterInterface */ abstract protected function getWriter(): TypedWriterInterface; }
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Exporter\Test; use Sonata\Exporter\Writer\TypedWriterInterface; /** * @author Grégoire Paris <postmaster@greg0ire.fr> */ abstract class AbstractTypedWriterTestCase extends \PHPUnit_Framework_TestCase { /** * @var WriterInterface */ private $writer; protected function setUp(): void { $this->writer = $this->getWriter(); } public function testFormatIsString(): void { $this->assertInternalType('string', $this->writer->getFormat()); } public function testDefaultMimeTypeIsString(): void { $this->assertInternalType('string', $this->writer->getDefaultMimeType()); } /** * Should return a very simple instance of the writer (no need for complex * configuration). * * @return WriterInterface */ abstract protected function getWriter(): TypedWriterInterface; }
Add prop type for Num.shorthand.
/** * Formatted number component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import { numFmt } from '../../util'; export default function Num( { value, shorthand, children, // eslint-disable-line no-unused-vars ...options } ) { if ( shorthand ) { return numFmt( value, shorthand ); } return numFmt( value, options ); } Num.propTypes = { value: PropTypes.oneOfType( [ PropTypes.number, PropTypes.string, ] ).isRequired, shorthand: PropTypes.string, };
/** * Formatted number component. * * Site Kit by Google, Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * External dependencies */ import PropTypes from 'prop-types'; /** * Internal dependencies */ import { numFmt } from '../../util'; export default function Num( { value, shorthand, children, // eslint-disable-line no-unused-vars ...options } ) { if ( shorthand ) { return numFmt( value, shorthand ); } return numFmt( value, options ); } Num.propTypes = { value: PropTypes.oneOfType( [ PropTypes.number, PropTypes.string, ] ).isRequired, };
Add better default for s3 region
import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from .base import * # noqa from .base import env SECRET_KEY = env("SECRET_KEY") # CELERY_BROKER_URL = env("CELERY_BROKER_URL") USE_SCHEDULER = False # if FRONTEND_URL == "http://testfrontend.it/": # raise ImproperlyConfigured("Please configure FRONTEND_URL for production") SENTRY_DSN = env("SENTRY_DSN", default="") if SENTRY_DSN: sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()]) SLACK_INCOMING_WEBHOOK_URL = env("SLACK_INCOMING_WEBHOOK_URL") DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None) AWS_S3_REGION_NAME = env("AWS_REGION_NAME", "eu-central-1") AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None) AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", None)
import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from .base import * # noqa from .base import env SECRET_KEY = env("SECRET_KEY") # CELERY_BROKER_URL = env("CELERY_BROKER_URL") USE_SCHEDULER = False # if FRONTEND_URL == "http://testfrontend.it/": # raise ImproperlyConfigured("Please configure FRONTEND_URL for production") SENTRY_DSN = env("SENTRY_DSN", default="") if SENTRY_DSN: sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()]) SLACK_INCOMING_WEBHOOK_URL = env("SLACK_INCOMING_WEBHOOK_URL") DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_STORAGE_BUCKET_NAME = env("AWS_MEDIA_BUCKET", None) AWS_S3_REGION_NAME = env("AWS_REGION_NAME", None) AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID", None) AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", None)
Use as_array() instead of _data in io.ascii compressed tests
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import numpy as np from ....tests.helper import pytest from .. import read ROOT = os.path.abspath(os.path.dirname(__file__)) @pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz', 't/short.rdb.gz']) def test_gzip(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.gz', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp.as_array() == t_uncomp.as_array()) @pytest.mark.parametrize('filename', ['t/short.rdb.bz2', 't/ipac.dat.bz2']) def test_bzip2(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.bz2', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp.as_array() == t_uncomp.as_array())
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os import numpy as np from ....tests.helper import pytest from .. import read ROOT = os.path.abspath(os.path.dirname(__file__)) @pytest.mark.parametrize('filename', ['t/daophot.dat.gz', 't/latex1.tex.gz', 't/short.rdb.gz']) def test_gzip(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.gz', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp._data == t_uncomp._data) @pytest.mark.parametrize('filename', ['t/short.rdb.bz2', 't/ipac.dat.bz2']) def test_bzip2(filename): t_comp = read(os.path.join(ROOT, filename)) t_uncomp = read(os.path.join(ROOT, filename.replace('.bz2', ''))) assert t_comp.dtype.names == t_uncomp.dtype.names assert np.all(t_comp._data == t_uncomp._data)
Add test route for heroku
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): return 'hello world' @app.route('/sparql') def do_sparql(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
from flask import Flask from SPARQLWrapper import SPARQLWrapper, JSON from flask import request, jsonify from flask.ext.cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def hello_world(): auth = request.authorization query = request.args.get('query') if not auth is None and not query is None: sparql = SPARQLWrapper('https://knowledgestore2.fbk.eu/nwr/dutchhouse/sparql') sparql.setQuery(query) sparql.setCredentials(auth.username, auth.password) sparql.setReturnFormat(JSON) results = sparql.query().convert() return jsonify(**results) else: msg = [] if auth is None: msg.append('authorization error') if query is None: msg.append('no query') response = jsonify({'status': 404, 'statusText': ' '.join(msg)}) response.status_code = 404 return response if __name__ == '__main__': app.run()
Rewrite getBestName to avoid jQuery
getBestName = function(result){ var bestName = ""; if(typeof result["scientificName"] !== "undefined"){ bestName = result["scientificName"]; } if(typeof result["vernacularNames"] !== "undefined" && result["vernacularNames"].length > 0){ var preferred = false; result["vernacularNames"].forEach(function(value){ if(value.language === "en"){ if(typeof value["eol_preferred"] !== "undefined" && value["eol_preferred"]){ preferred = true; bestName = value.vernacularName; } else if(!preferred){ bestName = value.vernacularName; } } }); } return bestName; }
getBestName = function(result){ var bestName = ""; if(typeof result["scientificName"] !== "undefined"){ bestName = result["scientificName"]; } if(typeof result["vernacularNames"] !== "undefined" && result["vernacularNames"].length > 0){ var preferred = false; $.each(result["vernacularNames"], function(key, value){ if(value.language === "en"){ if(typeof value["eol_preferred"] !== "undefined" && value["eol_preferred"]){ preferred = true; bestName = value.vernacularName; } else if(!preferred){ bestName = value.vernacularName; } } }); } return bestName; }
Fix unit test that fails on OS X.
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. // System import path from "path"; // Packages import given from "mocha-testdata"; import should from "should"; // Project import normalizePathSeparators from "../../src/util/normalizePathSeparators"; describe("util/normalizePathSeparators", function () { it("is a function", function () { return normalizePathSeparators .should.be.a.Function(); }); given( [ "", "" ], [ "abc", "abc" ], [ "abc/def", "abc/def" ], [ "abc/def/ghi", "abc/def/ghi" ], [ path.join("abc", "def"), "abc/def" ], [ path.join("abc", "def", "ghi"), "abc/def/ghi" ], [ path.join("abc/def", "ghi"), "abc/def/ghi" ] ). it("returns the expected normalized path", function (path, expectedResult) { normalizePathSeparators(path) .should.be.eql(expectedResult); }); });
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. // Packages import given from "mocha-testdata"; import should from "should"; // Project import normalizePathSeparators from "../../src/util/normalizePathSeparators"; describe("util/normalizePathSeparators", function () { it("is a function", function () { return normalizePathSeparators .should.be.a.Function(); }); given( [ "", "" ], [ "abc", "abc" ], [ "abc/def", "abc/def" ], [ "abc/def/ghi", "abc/def/ghi" ], [ "abc\\def", "abc/def" ], [ "abc\\def\\ghi", "abc/def/ghi" ], [ "abc/def\\ghi", "abc/def/ghi" ] ). it("returns the expected normalized path", function (path, expectedResult) { normalizePathSeparators(path) .should.be.eql(expectedResult); }); });
Make released version of tangled 0.1a5 the min
from setuptools import setup setup( name='tangled.contrib', version='0.1a3.dev0', description='Tangled namespace for contributed packages', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.contrib', 'tangled.contrib.scaffolds', 'tangled.contrib.tests', ], include_package_data=True, install_requires=[ 'tangled>=0.1a5', ], extras_require={ 'dev': [ 'tangled[dev]>=0.1a5', ], }, entry_points=""" [tangled.scaffolds] contrib = tangled.contrib.scaffolds:default contrib-core = tangled.contrib.scaffolds:core """, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], )
from setuptools import setup setup( name='tangled.contrib', version='0.1a3.dev0', description='Tangled namespace for contributed packages', long_description=open('README.rst').read(), url='http://tangledframework.org/', author='Wyatt Baldwin', author_email='self@wyattbaldwin.com', packages=[ 'tangled', 'tangled.contrib', 'tangled.contrib.scaffolds', 'tangled.contrib.tests', ], include_package_data=True, install_requires=[ 'tangled>=0.1.dev0', ], extras_require={ 'dev': [ 'tangled[dev]', ], }, entry_points=""" [tangled.scaffolds] contrib = tangled.contrib.scaffolds:default contrib-core = tangled.contrib.scaffolds:core """, classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], )
Fix CORS behavior to not freeze
// Importing Node modules and initializing Express const express = require('express'), app = express(), bodyParser = require('body-parser'), logger = require('morgan'), mongoose = require('mongoose'), router = require('./router'); config = require('./config/main'); // Database connection mongoose.connect(config.database); // Start the server const server = app.listen(config.port); console.log('Battlerite Base server is running on port ' + config.port + '.'); // Setting up basic middleware for all Express requests app.use(logger('dev')); // Log requests to API using morgan app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Enable CORS from client-side app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials"); res.header("Access-Control-Allow-Credentials", "true"); next(); }); router(app);
// Importing Node modules and initializing Express const express = require('express'), app = express(), bodyParser = require('body-parser'), logger = require('morgan'), mongoose = require('mongoose'), router = require('./router'); config = require('./config/main'); // Database connection mongoose.connect(config.database); // Start the server const server = app.listen(config.port); console.log('Battlerite Base server is running on port ' + config.port + '.'); // Setting up basic middleware for all Express requests app.use(logger('dev')); // Log requests to API using morgan app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Enable CORS from client-side app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", 'PUT, GET, POST, DELETE, OPTIONS'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Allow-Credentials"); res.header("Access-Control-Allow-Credentials", "true"); }); router(app);
Move runService function to WebService. Add comments. Get possibility set port via process.argv.
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var webServiceInit = new WebService(new CurrentUser()); var runService = webServiceInit.runWrapper(); // Database adapters. var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { // Add things to dependencies in everything service. webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); next(); }); app.use(function (req, res, next) { webServiceInit.runRef = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' })); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(process.argv[2]); console.log('Server listening on port ' + process.argv[2] + '.');
var express = require('express'); var app = express(); var CurrentUser = require('../Architecture/CurrentUser').CurrentUser; var WebService = require('../Architecture/WebService').WebService; var MongoAdapter = require('../Adapters/Mongo').MongoAdapter; var RedisAdapter = require('../Adapters/Redis').RedisAdapter; var mongodb = new MongoAdapter(); var redis = new RedisAdapter(); var webServiceRun; var runService = function (name, allowedTypeAccount, params) { return function (req, res) { params.req = req; params.res = res; webServiceRun(name, allowedTypeAccount, params); }; }; app.use(mongodb.connect()); app.use(redis.connect()); app.use(function (req, res, next) { var webServiceInit = new WebService(new CurrentUser()); webServiceInit.addDependency('mongo', mongodb); webServiceInit.addDependency('redis', redis); webServiceRun = webServiceInit.run.bind(webServiceInit); next(); }); app.use(express.static('Resources')); // ### Routing ### app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' })); app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' })); app.listen(4444); console.log('Server listening on port 4444.');
Fix warning from go lint
package server import ( "fmt" "github.com/Frostman/aptomi/pkg/slinga" "net/http" ) func endpointsHandler(w http.ResponseWriter, r *http.Request) { // Load the previous usage state state := slinga.LoadServiceUsageState() endpoints := state.Endpoints() writeJSON(w, endpoints) } // Serve starts http server on specified address that serves Aptomi API and WebUI func Serve(host string, port int) { // redirect from "/" to "/ui/" http.Handle("/", http.RedirectHandler("/ui/", http.StatusPermanentRedirect)) // serve all files from "webui" folder and require auth for everything except login.html http.Handle("/ui/", staticFilesHandler("/ui/", http.Dir("./webui/"))) // serve all API endpoints at /api/ path and require auth http.Handle("/api/endpoints", requireAuth(endpointsHandler)) // serve login/logout api without auth http.HandleFunc("/api/login", loginHandler) http.HandleFunc("/api/logout", logoutHandler) listenAddr := fmt.Sprintf("%s:%d", host, port) fmt.Println("Serving at", listenAddr) // todo better handle error returned from ListenAndServe (path to Fatal??) panic(http.ListenAndServe(listenAddr, nil)) }
package server import ( "fmt" "github.com/Frostman/aptomi/pkg/slinga" "net/http" ) func endpointsHandler(w http.ResponseWriter, r *http.Request) { // Load the previous usage state state := slinga.LoadServiceUsageState() endpoints := state.Endpoints() writeJSON(w, endpoints) } func Serve(host string, port int) { // redirect from "/" to "/ui/" http.Handle("/", http.RedirectHandler("/ui/", http.StatusPermanentRedirect)) // serve all files from "webui" folder and require auth for everything except login.html http.Handle("/ui/", staticFilesHandler("/ui/", http.Dir("./webui/"))) // serve all API endpoints at /api/ path and require auth http.Handle("/api/endpoints", requireAuth(endpointsHandler)) // serve login/logout api without auth http.HandleFunc("/api/login", loginHandler) http.HandleFunc("/api/logout", logoutHandler) listenAddr := fmt.Sprintf("%s:%d", host, port) fmt.Println("Serving at", listenAddr) // todo better handle error returned from ListenAndServe (path to Fatal??) panic(http.ListenAndServe(listenAddr, nil)) }
Handle null credentials object in the comparison.
package com.topsy.jmxproxy.jmx; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class ConnectionCredentials { @NotEmpty @JsonProperty private final String username; @NotEmpty @JsonProperty private final String password; public ConnectionCredentials(@JsonProperty("username") String username, @JsonProperty("password") String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } @Override public boolean equals(Object peer) { ConnectionCredentials auth = (ConnectionCredentials) peer; return auth != null && username == auth.getUsername() && password == auth.getPassword(); } }
package com.topsy.jmxproxy.jmx; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class ConnectionCredentials { @NotEmpty @JsonProperty private final String username; @NotEmpty @JsonProperty private final String password; public ConnectionCredentials(@JsonProperty("username") String username, @JsonProperty("password") String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public String getPassword() { return password; } @Override public boolean equals(Object peer) { ConnectionCredentials auth = (ConnectionCredentials) peer; return username == auth.getUsername() && password == auth.getPassword(); } }
Switch notebook list to PouchDB
var PouchDB = require('pouchdb'); // TODO: move this to a config lib var db_name = location.pathname.split('/')[1]; var db_url = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '') + '/' + db_name + '/'; var db = new PouchDB(db_url); module.exports = { replace: true, template: require('./template.html'), data: function() { return { items: [] }; }, methods: { isActive: function(id) { if (Object.keys(this.$root.current).length > 0) { return this.$root.current.notebook._id === id; } else { return false; } }, fetchData: function () { var self = this; db.query('sprung/notebooks', {reduce: false, include_docs: true}) .then(function(resp) { self.items = resp.rows; }); }, setCurrent: function(notebook) { this.$root.current.notebook = notebook; }, unsetCurrent: function() { this.$root.current.notebook = {}; } }, created: function() { this.fetchData(); } }
module.exports = { replace: true, template: require('./template.html'), data: function() { return { apiUrl: '_view/notebooks?reduce=false&include_docs=true', items: [] }; }, methods: { isActive: function(id) { if (Object.keys(this.$root.current).length > 0) { return this.$root.current.notebook._id === id; } else { return false; } }, fetchData: function () { if (!this.apiUrl) return false; var xhr = new XMLHttpRequest(), self = this; xhr.open('GET', self.apiUrl); xhr.onload = function () { // TODO: be less rash... self.items = JSON.parse(xhr.responseText).rows; }; xhr.send(); }, setCurrent: function(notebook) { this.$root.current.notebook = notebook; }, unsetCurrent: function() { this.$root.current.notebook = {}; } }, created: function() { this.fetchData(); } }
Enable map controls, switch to terrain view
(function () { function initialize_map() { var map_element = document.getElementById("map-drilldown-canvas"); if (!map_element) return false; // start with the default bounds for kenya var map_bounds = { north: 5, east: 44, south: -5, west: 33.5 }; var map_has_been_located = false; var myOptions = { mapTypeId: google.maps.MapTypeId.TERRAIN, maxZoom: 10 }; var map = new google.maps.Map(map_element, myOptions); map.fitBounds( make_bounds( map_bounds ) ); } function make_bounds ( bounds ) { var sw = new google.maps.LatLng( bounds.south, bounds.west ); var ne = new google.maps.LatLng( bounds.north, bounds.east ); return new google.maps.LatLngBounds( sw, ne ); } mzalendo_run_when_document_ready( function () { google.load( 'maps', '3', { callback: initialize_map, other_params:'sensor=false' } ); } ); })();
(function () { function initialize_map() { var map_element = document.getElementById("map-drilldown-canvas"); if (!map_element) return false; // start with the default bounds for kenya var map_bounds = { north: 5, east: 44, south: -5, west: 33.5 }; var map_has_been_located = false; var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, maxZoom: 10 }; var map = new google.maps.Map(map_element, myOptions); map.fitBounds( make_bounds( map_bounds ) ); } function make_bounds ( bounds ) { var sw = new google.maps.LatLng( bounds.south, bounds.west ); var ne = new google.maps.LatLng( bounds.north, bounds.east ); return new google.maps.LatLngBounds( sw, ne ); } mzalendo_run_when_document_ready( function () { google.load( 'maps', '3', { callback: initialize_map, other_params:'sensor=false' } ); } ); })();
Update template path to reflect multiple format support in the default SimpleChannelFrontend templates.
<?php require_once 'config.inc.php'; $options = $_GET; if (isset($_SERVER['REDIRECT_URL'])) { $options['view'] = 'package'; preg_match('/\/(?<package>[0-9a-z_]+)(-(?<version>[0-9ab.]+))?$/i', $_SERVER['REDIRECT_URL'], $matches); $options['package'] = $matches['package']; if (isset($matches['version'])) { $options['packageVersion'] = $matches['version']; $options['view'] = 'release'; } } $channel = new \pear2\Pyrus\ChannelFile(__DIR__ . '/channel.xml'); $frontend = new pear2\SimpleChannelFrontend\Main($channel, $options); $savant = new pear2\Templates\Savant\Main(); $savant->setClassToTemplateMapper(new pear2\SimpleChannelFrontend\TemplateMapper); $savant->setTemplatePath(array(__DIR__ . '/templates/default/html', __DIR__ . '/templates/pear2')); switch($frontend->options['format']) { case 'rss': $savant->addTemplatePath(__DIR__.'/templates/default/'.$frontend->options['format']); break; } $savant->setEscape('htmlspecialchars'); $savant->addFilters(array($frontend, 'postRender')); echo $savant->render($frontend); ?>
<?php require_once 'config.inc.php'; $options = $_GET; if (isset($_SERVER['REDIRECT_URL'])) { $options['view'] = 'package'; preg_match('/\/(?<package>[0-9a-z_]+)(-(?<version>[0-9ab.]+))?$/i', $_SERVER['REDIRECT_URL'], $matches); $options['package'] = $matches['package']; if (isset($matches['version'])) { $options['packageVersion'] = $matches['version']; $options['view'] = 'release'; } } $channel = new \pear2\Pyrus\ChannelFile(__DIR__ . '/channel.xml'); $frontend = new pear2\SimpleChannelFrontend\Main($channel, $options); $savant = new pear2\Templates\Savant\Main(); $savant->setClassToTemplateMapper(new pear2\SimpleChannelFrontend\TemplateMapper); $savant->setTemplatePath(array(__DIR__ . '/templates/default', __DIR__ . '/templates/pear2')); $savant->setEscape('htmlspecialchars'); $savant->addFilters(array($frontend, 'postRender')); echo $savant->render($frontend); ?>
Remove static file serve url
from project.settings_common import * DEBUG = True TEMPLATE_DEBUG = DEBUG # CACHE from memcacheify import memcacheify CACHES = memcacheify() MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/') STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATIC_URL = 'https://s3.amazonaws.com/lobbyingph/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_ACCESS_KEY_ID = os.environ['AWS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET'] AWS_STORAGE_BUCKET_NAME = 'lobbyingph' #import dj_database_url #DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
from project.settings_common import * DEBUG = False TEMPLATE_DEBUG = DEBUG # CACHE from memcacheify import memcacheify CACHES = memcacheify() MIDDLEWARE_CLASSES += ( 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static/') STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATIC_URL = 'https://s3.amazonaws.com/lobbyingph/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_ACCESS_KEY_ID = os.environ['AWS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET'] AWS_STORAGE_BUCKET_NAME = 'lobbyingph' import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}
Update 2019 day 5, second part for new intcode computer
package main import ( "fmt" "strings" "github.com/bewuethr/advent-of-code/go/convert" "github.com/bewuethr/advent-of-code/go/intcode" "github.com/bewuethr/advent-of-code/go/ioutil" "github.com/bewuethr/advent-of-code/go/log" ) func main() { scanner, err := ioutil.GetInputScanner() if err != nil { log.Die("getting scanner", err) } scanner.Scan() opCodesStr := strings.Split(scanner.Text(), ",") if err := scanner.Err(); err != nil { log.Die("reading input", err) } opCodes, err := convert.StrSliceToInt(opCodesStr) if err != nil { log.Die("converting string slice to int", err) } comp := intcode.NewComputer(opCodes) comp.RunProgram() comp.Input <- 5 Loop: for { select { case err := <-comp.Err: log.Die("running op codes", err) case <-comp.Done: break Loop case output := <-comp.Output: fmt.Println(output) } } }
package main import ( "strings" "github.com/bewuethr/advent-of-code/go/convert" "github.com/bewuethr/advent-of-code/go/intcode" "github.com/bewuethr/advent-of-code/go/ioutil" "github.com/bewuethr/advent-of-code/go/log" ) func main() { scanner, err := ioutil.GetInputScanner() if err != nil { log.Die("getting scanner", err) } scanner.Scan() opCodesStr := strings.Split(scanner.Text(), ",") if err := scanner.Err(); err != nil { log.Die("reading input", err) } opCodes, err := convert.StrSliceToInt(opCodesStr) if err != nil { log.Die("converting string slice to int", err) } comp := intcode.NewComputer(opCodes) if err := comp.RunProgram(5); err != nil { log.Die("running op codes", err) } }
Use namespaced PHPUnit test case Polyfilled by yoast package now
<?php use PHPUnit\Framework\TestCase; use WP_CLI_Login\WP_CLI_Login_Server; class WP_CLI_Login_ServerTest extends TestCase { /** @test */ function parses_endpoint_and_key_from_uri() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } /** @test */ function parses_endpoint_and_key_from_uri_for_subdirectory_site() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } }
<?php use WP_CLI_Login\WP_CLI_Login_Server; if (! class_exists('PHPUnit_Framework_TestCase')) { class_alias('PHPUnit\Framework\TestCase', 'PHPUnit_Framework_TestCase'); } class WP_CLI_Login_ServerTest extends PHPUnit_Framework_TestCase { /** @test */ function parses_endpoint_and_key_from_uri() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } /** @test */ function parses_endpoint_and_key_from_uri_for_subdirectory_site() { list($endpoint, $public) = WP_CLI_Login_Server::parseUri('/abc/end/key'); $this->assertSame('end', $endpoint); $this->assertSame('key', $public); } }
Fix passing onClearNotices to Notices in LogInBox
import React from 'react'; import Notices from 'components/notices'; const LogInBox = ( props ) => { return ( <div className="log-in-box"> <Notices errors={ props.errors } onClearNotices={ props.onClearNotices } /> <div className="log-in-box__content"> <img className="log-in-box__logo" alt="Voyageur logo" src="/assets/logo-medium-smooth.png" /> <h1 className="log-in-box__title">Voyageur</h1> <p className="log-in-box__subtitle">How far do you go?</p> <a onClick={ props.showAuth } className="log-in-box__button btn btn-primary btn-lg">Let's find out!</a> </div> </div> ); }; LogInBox.propTypes = { showAuth: React.PropTypes.func.isRequired, onClearNotices: React.PropTypes.func.isRequired, errors: React.PropTypes.array, }; export default LogInBox;
import React from 'react'; import Notices from 'components/notices'; const LogInBox = ( props ) => { return ( <div className="log-in-box"> <Notices errors={ props.errors } onClearNotices={ props.clearNotices } /> <div className="log-in-box__content"> <img className="log-in-box__logo" alt="Voyageur logo" src="/assets/logo-medium-smooth.png" /> <h1 className="log-in-box__title">Voyageur</h1> <p className="log-in-box__subtitle">How far do you go?</p> <a onClick={ props.showAuth } className="log-in-box__button btn btn-primary btn-lg">Let's find out!</a> </div> </div> ); }; LogInBox.propTypes = { showAuth: React.PropTypes.func.isRequired, onClearNotices: React.PropTypes.func.isRequired, errors: React.PropTypes.array, }; export default LogInBox;
Bump to next development cycle
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md')) as f: jgo_long_description = f.read() setup( name='jgo', version='0.2.1.dev0', author='Philipp Hanslovsky, Curtis Rueden', author_email='hanslovskyp@janelia.hhmi.org', description='Launch Java code from Python and the CLI, installation-free.', long_description=jgo_long_description, long_description_content_type='text/markdown', license='Public domain', url='https://github.com/scijava/jgo', packages=['jgo'], entry_points={ 'console_scripts': [ 'jgo=jgo.jgo:jgo_main' ] }, python_requires='>=3', )
from setuptools import setup from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.md')) as f: jgo_long_description = f.read() setup( name='jgo', version='0.2.0', author='Philipp Hanslovsky, Curtis Rueden', author_email='hanslovskyp@janelia.hhmi.org', description='Launch Java code from Python and the CLI, installation-free.', long_description=jgo_long_description, long_description_content_type='text/markdown', license='Public domain', url='https://github.com/scijava/jgo', packages=['jgo'], entry_points={ 'console_scripts': [ 'jgo=jgo.jgo:jgo_main' ] }, python_requires='>=3', )
Disable new test from r1779 for the android generator. BUG=gyp:379 TBR=torne@chromium.org Review URL: https://codereview.chromium.org/68333002
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() # Doesn't pass with the android generator, see gyp bug 379. test = TestGyp.TestGyp(formats=['!android']) test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
#!/usr/bin/env python # Copyright (c) 2013 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that copying files preserves file attributes. """ import TestGyp import os import stat import sys def check_attribs(path, expected_exec_bit): out_path = test.built_file_path(path, chdir='src') in_stat = os.stat(os.path.join('src', path)) out_stat = os.stat(out_path) if out_stat.st_mode & stat.S_IXUSR != expected_exec_bit: test.fail_test() test = TestGyp.TestGyp() test.run_gyp('copies-attribs.gyp', chdir='src') test.build('copies-attribs.gyp', chdir='src') if sys.platform != 'win32': out_path = test.built_file_path('executable-file.sh', chdir='src') test.must_contain(out_path, '#!/bin/bash\n' '\n' 'echo echo echo echo cho ho o o\n') check_attribs('executable-file.sh', expected_exec_bit=stat.S_IXUSR) test.pass_test()
Fix error message for empty field in FAQ ACP form
/* * Copyright (C) 2017 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.frontend.web.faq.logic; import java.util.Set; import javax.validation.ConstraintViolation; import org.springframework.stereotype.Component; import org.springframework.validation.BindingResult; @Component public class FaqErrorsBindingMapper { public void map(Set<ConstraintViolation<?>> constraintViolations, BindingResult bindingResult) { for (ConstraintViolation violation : constraintViolations) { String propertyPath = violation.getPropertyPath().toString(); propertyPath = propertyPath.replace("questions", "entries"); bindingResult.rejectValue(propertyPath, "x", violation.getMessage()); } } }
/* * Copyright (C) 2017 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.frontend.web.faq.logic; import java.util.Set; import javax.validation.ConstraintViolation; import org.springframework.stereotype.Component; import org.springframework.validation.BindingResult; @Component public class FaqErrorsBindingMapper { public void map(Set<ConstraintViolation<?>> constraintViolations, BindingResult bindingResult) { for (ConstraintViolation violation : constraintViolations) { String propertyPath = violation.getPropertyPath().toString(); propertyPath = propertyPath.replace("questions", "entries"); bindingResult.rejectValue(propertyPath, violation.getMessage()); } } }
[1.8] Remove tracing helper it's already in StackFrame.getStackDump http://code.google.com/p/fbug/source/detail?r=10854
/* See license.txt for terms of usage */ define([ "firebug/lib/trace" ], function(FBTrace) { // ********************************************************************************************* // // Debug APIs const Cc = Components.classes; const Ci = Components.interfaces; var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]); var Debug = {}; //************************************************************************************************ // Debug Logging Debug.ERROR = function(exc) { if (typeof(FBTrace) !== undefined) { if (exc.stack) exc.stack = exc.stack.split('\n'); FBTrace.sysout("Debug.ERROR: " + exc, exc); } if (consoleService) consoleService.logStringMessage("FIREBUG ERROR: " + exc); } // ********************************************************************************************* // return Debug; // ********************************************************************************************* // });
/* See license.txt for terms of usage */ define([ "firebug/lib/trace" ], function(FBTrace) { // ********************************************************************************************* // // Debug APIs const Cc = Components.classes; const Ci = Components.interfaces; var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci["nsIConsoleService"]); var Debug = {}; //************************************************************************************************ // Debug Logging Debug.ERROR = function(exc) { if (typeof(FBTrace) !== undefined) { if (exc.stack) exc.stack = exc.stack.split('\n'); FBTrace.sysout("Debug.ERROR: " + exc, exc); } if (consoleService) consoleService.logStringMessage("FIREBUG ERROR: " + exc); } // ********************************************************************************************* // /** * Dump the current stack trace. * @param {Object} message displayed for the log. */ Debug.STACK_TRACE = function(message) { var result = []; for (var frame = Components.stack, i = 0; frame; frame = frame.caller, i++) { if (i < 1) continue; var fileName = unescape(frame.filename ? frame.filename : ""); var lineNumber = frame.lineNumber ? frame.lineNumber : ""; result.push(fileName + ":" + lineNumber); } FBTrace.sysout(message, result); } return Debug; // ********************************************************************************************* // });