text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Make exception task filename to be empty string by default
<?php declare(strict_types=1); /* (c) Anton Medvedev <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Deployer\Exception; use Throwable; class Exception extends \Exception { private static $taskSourceLocation = ''; private $taskFilename = ''; private $taskLineNumber = ''; public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { if (function_exists('debug_backtrace')) { $trace = debug_backtrace(); foreach ($trace as $t) { if (!empty($t['file']) && $t['file'] === self::$taskSourceLocation) { $this->taskFilename = basename($t['file']); $this->taskLineNumber = $t['line']; break; } } } parent::__construct($message, $code, $previous); } public static function setTaskSourceLocation(string $filepath): void { self::$taskSourceLocation = $filepath; } public function getTaskFilename(): string { return $this->taskFilename; } public function getTaskLineNumber(): int { return $this->taskLineNumber; } public function setTaskFilename(string $taskFilename): void { $this->taskFilename = $taskFilename; } public function setTaskLineNumber(int $taskLineNumber): void { $this->taskLineNumber = $taskLineNumber; } }
<?php declare(strict_types=1); /* (c) Anton Medvedev <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Deployer\Exception; use Throwable; class Exception extends \Exception { private static $taskSourceLocation; private $taskFilename; private $taskLineNumber; public function __construct(string $message = "", int $code = 0, Throwable $previous = null) { if (function_exists('debug_backtrace')) { $trace = debug_backtrace(); foreach ($trace as $t) { if (!empty($t['file']) && $t['file'] === self::$taskSourceLocation) { $this->taskFilename = basename($t['file']); $this->taskLineNumber = $t['line']; break; } } } parent::__construct($message, $code, $previous); } public static function setTaskSourceLocation(string $filepath): void { self::$taskSourceLocation = $filepath; } public function getTaskFilename(): string { return $this->taskFilename; } public function getTaskLineNumber(): int { return $this->taskLineNumber; } public function setTaskFilename(string $taskFilename): void { $this->taskFilename = $taskFilename; } public function setTaskLineNumber(int $taskLineNumber): void { $this->taskLineNumber = $taskLineNumber; } }
Test of optimized output functions runs automatically.
""" Unit tests for Topographica $Id$ """ __version__='$Revision$' ### JABALERT! ### ### Should change this to be like topo/patterns/__init__.py, i.e. ### to automatically discover the test files. That way new tests ### can be just dropped in. import unittest, os import testboundingregion import testdummy import testbitmap import testsheet import testsheetview import testplot import testplotgroup import testplotfilesaver import testsimulator import testpalette import testcfsom import testpatterngenerator import testmatplotlib import testpatternpresent import testdistribution import testfeaturemap import testoutputfnsbasic import testoutputfnsoptimized # CEBHACKALERT: no test for patterns/image.py # tkgui import calls tkgui/__init__.py, which should contain other test # imports for that directory. import tkgui suite = unittest.TestSuite() display_loc = os.getenv('DISPLAY') for key,val in locals().items(): if type(val) == type(unittest) and not val in (unittest, os): try: print 'Checking module %s for test suite...' % key, new_test = getattr(val,'suite') if hasattr(new_test,'requires_display') and not display_loc: print 'skipped: No $DISPLAY.' else: print 'found.' suite.addTest(new_test) except AttributeError,err: print err def run(verbosity=1): unittest.TextTestRunner(verbosity=verbosity).run(suite)
""" Unit tests for Topographica $Id$ """ __version__='$Revision$' ### JABALERT! ### ### Should change this to be like topo/patterns/__init__.py, i.e. ### to automatically discover the test files. That way new tests ### can be just dropped in. import unittest, os import testboundingregion import testdummy import testbitmap import testsheet import testsheetview import testplot import testplotgroup import testplotfilesaver import testsimulator import testpalette import testcfsom import testpatterngenerator import testmatplotlib import testpatternpresent import testdistribution import testfeaturemap import testoutputfnsbasic # CEBHACKALERT: no test for patterns/image.py # tkgui import calls tkgui/__init__.py, which should contain other test # imports for that directory. import tkgui suite = unittest.TestSuite() display_loc = os.getenv('DISPLAY') for key,val in locals().items(): if type(val) == type(unittest) and not val in (unittest, os): try: print 'Checking module %s for test suite...' % key, new_test = getattr(val,'suite') if hasattr(new_test,'requires_display') and not display_loc: print 'skipped: No $DISPLAY.' else: print 'found.' suite.addTest(new_test) except AttributeError,err: print err def run(verbosity=1): unittest.TextTestRunner(verbosity=verbosity).run(suite)
Put statuses back to correct, adjust unsupported status
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { // Check for the various File API support. if (window.File && window.FileReader && window.FileList && window.Blob) { return {status: 2, msg: 'Ready'}; } else { return {status: 0, msg: 'The File APIs are not fully supported by your browser.'}; } }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ['r', '%m.k', 'k', 'heady'] ], menus: { k: ['headx', 'heady'] } }; ext.my_first_block = function() { console.log("hello, world."); }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; ext.k = function(m) { switch(m){ case 'headx': return 1; case 'heady': return 2; } }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
(function(ext) { // Cleanup function when the extension is unloaded ext._shutdown = function() {}; // Status reporting code // Use this to report missing hardware, plugin or unsupported browser ext._getStatus = function() { // Check for the various File API support. if (window.File && window.FileReader && window.FileList && window.Blob) { return {status: 1, msg: 'The File APIs are not fully supported by your browser.'}; //return {status: 2, msg: 'Ready'}; } else { return {status: 1, msg: 'The File APIs are not fully supported by your browser.'}; } }; // Block and block menu descriptions var descriptor = { blocks: [ ['', 'My First Block', 'my_first_block'], ['r', '%n ^ %n', 'power', 2, 3], ['r', '%m.k', 'k', 'heady'] ], menus: { k: ['headx', 'heady'] } }; ext.my_first_block = function() { console.log("hello, world."); }; ext.power = function(base, exponent) { return Math.pow(base, exponent); }; ext.k = function(m) { switch(m){ case 'headx': return 1; case 'heady': return 2; } }; // Register the extension ScratchExtensions.register('Kinect2Scratch', descriptor, ext); })({});
Fix sounds being uploaded to the wrong path
'use strict'; var fs = require('fs'); var express = require('express'); var app = express(); var multer = require('multer'); var path = require('path'); var upload = multer({ dest: 'sounds/', storage: multer.diskStorage({ destination: path.join(__dirname, '../sounds'), filename: function (req, file, cb) { cb(null, file.originalname); } }) }); module.exports = function(nodecg) { // When a POST is made to /lfg-sounds/upload... app.put('/lfg-sounds/upload', // Check if the user is authorized nodecg.util.authCheck, // Then receive the files they are sending, up to a max of 16 upload.array('file', 16), // Then send a response. function (req, res) { if (req.files) { res.status(200).send('Success'); } else { res.status(400).send('Bad Request'); } } ); app.get('/lfg-sounds/:filename', nodecg.util.authCheck, function (req, res, next) { var resName = req.params.filename; var fileLocation = path.join(__dirname, '../sounds/', resName); // Check if the file exists if (!fs.existsSync(fileLocation)) { next(); return; } res.sendFile(fileLocation); }); nodecg.mount(app); };
'use strict'; var fs = require('fs'); var express = require('express'); var app = express(); var multer = require('multer'); var path = require('path'); var upload = multer({ dest: 'sounds/', storage: multer.diskStorage({ destination: path.join(__dirname, './sounds'), filename: function (req, file, cb) { cb(null, file.originalname); } }) }); module.exports = function(nodecg) { // When a POST is made to /lfg-sounds/upload... app.put('/lfg-sounds/upload', // Check if the user is authorized nodecg.util.authCheck, // Then receive the files they are sending, up to a max of 16 upload.array('file', 16), // Then send a response. function (req, res) { if (req.files) { res.status(200).send('Success'); } else { res.status(400).send('Bad Request'); } } ); app.get('/lfg-sounds/:filename', nodecg.util.authCheck, function (req, res, next) { var resName = req.params.filename; var fileLocation = path.join(__dirname, '../sounds/', resName); // Check if the file exists if (!fs.existsSync(fileLocation)) { next(); return; } res.sendFile(fileLocation); }); nodecg.mount(app); };
Add new Modal storybook doc
import React from 'react'; import Modal, { PureModal } from '@ichef/gypcrete/src/Modal'; import ContainsColumnView from '../SplitView/ContainsColumnView'; import ClosableModalExample, { MulitpleClosableModalExample } from './ClosableModalExample'; export default { title: '@ichef/gypcrete|Modal', component: PureModal, subcomponents: { 'renderToLayer()': Modal }, } export function BasicModal() { return ( <Modal header="Basic modal"> Hello World! </Modal> ); } export function ClosableModal() { return <ClosableModalExample />; } export function SplitViewModal() { return ( <Modal header="With <SplitView>" flexBody bodyPadding={{ bottom: 0 }}> <ContainsColumnView /> </Modal> ); } SplitViewModal.story = { name: 'With <SplitView>', }; export function CenteredModal() { return ( <Modal header="Vertically-centered modal" centered> Hello World! </Modal> ); } export function MultilpleLayerModal() { return <MulitpleClosableModalExample depth={10} />; } MultilpleLayerModal.story = { parameters: { docs: { storyDescription: 'Indented with 32px from each side for each layer. When number of layer > 7 we won\'t indent it', }, }, };
import React from 'react'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import Modal, { PureModal } from '@ichef/gypcrete/src/Modal'; import { getAddonOptions } from 'utils/getPropTables'; import ContainsColumnView from '../SplitView/ContainsColumnView'; import ClosableModalExample, { MulitpleClosableModalExample } from './ClosableModalExample'; storiesOf('@ichef/gypcrete|Modal', module) .addDecorator(withInfo) .add( 'basic modal', () => ( <Modal header="Basic modal"> Hello World! </Modal> ) ) .add( 'closable modal', () => <ClosableModalExample /> ) .add( 'with <SplitView>', () => ( <Modal header="With <SplitView>" flexBody bodyPadding={{ bottom: 0 }}> <ContainsColumnView /> </Modal> ) ) .add( 'centered modal', () => ( <Modal header="Vertically-centered modal"> Hello World! </Modal> ) ) .add( 'multiple layer modals', () => <MulitpleClosableModalExample depth={10} />, { info: 'Indented with 32px from each side for each layer. When number of layer > 7 we won\'t indent it', } ) // Props table .add( 'props', () => <div />, { info: getAddonOptions([PureModal, Modal]) } );
Fix welcoming new members using outdated functions
'use strict'; const DiscordHook = require('../../../../bot/modules/DiscordHook'); const ModuleGuildWars2 = require('../../guildwars2'); class HookWelcomeNewMember extends DiscordHook { constructor(bot) { super(bot, 'welcome-new-member'); this._hooks = { guildMemberAdd: this.onNewMember.bind(this), }; } async onNewMember(member) { if (!member || !member.guild) { return; } const bot = this.getBot(); const l = bot.getLocalizer(); const channelId = this.getConfig().get('channel-id'); let channel; try { if (channelId && (channel = member.guild.channels.get(channelId)) && channel.type === 'text') { const moduleGw2 = bot.getModule(ModuleGuildWars2); const commandEu = moduleGw2.getActivity('region-eu').getCommandRoute().getInvocation(); const commandNa = moduleGw2.getActivity('region-na').getCommandRoute().getInvocation(); return await channel.send(l.t('module.utilities:welcome-new-member.welcome', { member: member.toString(), region_na_command: commandNa, region_eu_command: commandEu })); } } catch (err) { this.log(`Error while welcoming new member ${member.tag}:\n${err}`, 'warn'); } } } module.exports = HookWelcomeNewMember;
'use strict'; const DiscordHook = require('../../../../bot/modules/DiscordHook'); class HookWelcomeNewMember extends DiscordHook { constructor(bot) { super(bot, 'welcome-new-member'); this._hooks = { guildMemberAdd: this.onNewMember.bind(this), }; } async onNewMember(member) { if (!member || !member.guild) { return; } const bot = this.getBot(); const l = bot.getLocalizer(); const channelId = this.getConfig().get('channel-id'); let channel; if (channelId && (channel = member.guild.channels.get(channelId)) && channel.type === 'text') { const commandPrefix = bot.getConfig().get('discord.commands.prefix'); const moduleGw2 = bot.getModule('guildwars2'); const commandEu = `${commandPrefix}${moduleGw2.getActivity('region-eu').getTriggers()[0]}`; const commandNa = `${commandPrefix}${moduleGw2.getActivity('region-na').getTriggers()[0]}`; return await channel.send(l.t('module.utilities:welcome-new-member.welcome', { member: member.toString(), region_na_command: commandNa, region_eu_command: commandEu })); } } } module.exports = HookWelcomeNewMember;
Test the puzzle before solving Norvig's code makes this easier than I thought!
import os import pickle as pck import numpy as np from pprint import pprint import sys from scripts.sudokuExtractor import Extractor from scripts.train import NeuralNetwork from scripts.sudoku_str import SudokuStr class Sudoku(object): def __init__(self, name): image_path = self.getImagePath(name) cells = Extractor(image_path).cells neuralnetpath = os.getcwd() + '/networks/net' sizes, biases, wts = pck.load(open(neuralnetpath, 'r')) net = NeuralNetwork(customValues=(sizes, biases, wts)) self.res = [[None for _ in range(9)] for _ in range(9)] for i, row in enumerate(cells): for j, cell in enumerate(row): vector = np.reshape(cell, (784, 1)) x = net.feedforward(vector) x[0] = 0 s = sum(x) if list(x[np.argmax(x)])[0] / s > 0.8: self.res[i][j] = str(np.argmax(x)) else: self.res[i][j] = ' ' s = SudokuStr(self.res) print(s) print('') if sudopy.parse_grid(str(s)): print(s.solve()) else: print('No solution found. Please rescan the puzzle.') def getImagePath(self, name): return os.path.abspath(name) Sudoku(sys.argv[1])
import os import pickle as pck import numpy as np from pprint import pprint import sys from scripts.sudokuExtractor import Extractor from scripts.train import NeuralNetwork from scripts.sudoku_str import SudokuStr class Sudoku(object): def __init__(self, name): image_path = self.getImagePath(name) cells = Extractor(image_path).cells neuralnetpath = os.getcwd() + '/networks/net' sizes, biases, wts = pck.load(open(neuralnetpath, 'r')) net = NeuralNetwork(customValues=(sizes, biases, wts)) self.res = [[None for _ in range(9)] for _ in range(9)] for i, row in enumerate(cells): for j, cell in enumerate(row): vector = np.reshape(cell, (784, 1)) x = net.feedforward(vector) x[0] = 0 s = sum(x) if list(x[np.argmax(x)])[0] / s > 0.8: self.res[i][j] = str(np.argmax(x)) else: self.res[i][j] = ' ' s = SudokuStr(self.res) print(s) print('') print(s.solve()) def getImagePath(self, name): return os.path.abspath(name) Sudoku(sys.argv[1])
Correct code to remove JSHint error "Did you mean to return a conditional instead of an assignment?"
(function () { 'use strict'; angular .module('app.core') .run(function($rootScope, $state) { return $rootScope.$on('$stateChangeStart', function() { $rootScope.$state = $state; }); }) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', controller: 'Home', controllerAs: 'home', templateUrl: 'app/home/home.html', data: { title: 'Home' } }) .state('color', { url: '/color', controller: 'Color', controllerAs: 'color', templateUrl: 'app/color/color.html', data: { title: 'Color' } }) .state('404', { url: '/404', templateUrl: 'app/core/404.html', data: { title: '404' } }); }); }());
(function () { 'use strict'; angular .module('app.core') .run(function($rootScope, $state) { return $rootScope.$on('$stateChangeStart', function() { return $rootScope.$state = $state; }); }) .config(function ($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('home', { url: '/home', controller: 'Home', controllerAs: 'home', templateUrl: 'app/home/home.html', data: { title: 'Home' } }) .state('color', { url: '/color', controller: 'Color', controllerAs: 'color', templateUrl: 'app/color/color.html', data: { title: 'Color' } }) .state('404', { url: '/404', templateUrl: 'app/core/404.html', data: { title: '404' } }); }); }());
Check type of options more carefully
module.exports = ({types: t}) => { return { pre(file) { const opts = this.opts; if ( !( opts && typeof opts === 'object' && Object.keys(opts).every(key => ( opts[key] && ( typeof opts[key] === 'string' || ( typeof opts[key] === 'object' && typeof opts[key].moduleName === 'string' && typeof opts[key].exportName === 'string' ) ) )) ) ) { throw new Error( 'Invalid config options for babel-plugin-import-globals, espected a mapping from global variable name ' + 'to either a module name (with a default export) or an object of the type {moduleName: string, ' + 'exportName: string}.' ); } }, visitor: { ReferencedIdentifier(path, state) { const {node, scope} = path; if (scope.getBindingIdentifier(node.name)) return; const opts = this.opts; const name = node.name; if (!(name in opts) || (typeof opts[name] !== 'string' && typeof opts[name] !== 'object')) { return; } const source = ( typeof opts[name] === 'string' ? {moduleName: opts[name], exportName: 'default'} : opts[name] ); const newIdentifier = state.addImport( source.moduleName, source.exportName, name ); path.replaceWith( node.type === 'JSXIdentifier' ? t.jSXIdentifier(newIdentifier.name) : newIdentifier ); }, }, }; };
module.exports = ({types: t}) => { return { pre(file) { const opts = this.opts; if ( !( opts && typeof opts === 'object' && Object.keys(opts).every(key => ( opts[key] && ( typeof opts[key] === 'string' || ( typeof opts[key] === 'object' && typeof opts[key].moduleName === 'string' && typeof opts[key].exportName === 'string' ) ) )) ) ) { throw new Error( 'Invalid config options for babel-plugin-import-globals, espected a mapping from global variable name ' + 'to either a module name (with a default export) or an object of the type {moduleName: string, ' + 'exportName: string}.' ); } }, visitor: { ReferencedIdentifier(path, state) { const {node, scope} = path; if (scope.getBindingIdentifier(node.name)) return; const opts = this.opts; const name = node.name; if (!(name in opts)) { return; } const source = ( typeof opts[name] === 'string' ? {moduleName: opts[name], exportName: 'default'} : opts[name] ); const newIdentifier = state.addImport( source.moduleName, source.exportName, name ); path.replaceWith( node.type === 'JSXIdentifier' ? t.jSXIdentifier(newIdentifier.name) : newIdentifier ); }, }, }; };
BUGFIX: Remove pre-PHP7 code and avoid __toString deprecation warning
<?php namespace Neos\Flow\Reflection; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * Extended version of the ReflectionParameter * * @Flow\Proxy(false) */ class ParameterReflection extends \ReflectionParameter { /** * @var string */ protected $parameterClassName; /** * Returns the declaring class * * @return ClassReflection The declaring class */ public function getDeclaringClass() { return new ClassReflection(parent::getDeclaringClass()->getName()); } /** * Returns the parameter class * * @return ClassReflection The parameter class */ public function getClass() { try { $class = parent::getClass(); } catch (\Exception $exception) { return null; } return is_object($class) ? new ClassReflection($class->getName()) : null; } /** * @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise */ public function getBuiltinType() { $type = $this->getType(); if ($type === null || !$type->isBuiltin()) { return null; } return $type instanceof \ReflectionNamedType ? $type->getName() : (string)$type; } }
<?php namespace Neos\Flow\Reflection; /* * This file is part of the Neos.Flow package. * * (c) Contributors of the Neos Project - www.neos.io * * This package is Open Source Software. For the full copyright and license * information, please view the LICENSE file which was distributed with this * source code. */ use Neos\Flow\Annotations as Flow; /** * Extended version of the ReflectionParameter * * @Flow\Proxy(false) */ class ParameterReflection extends \ReflectionParameter { /** * @var string */ protected $parameterClassName; /** * Returns the declaring class * * @return ClassReflection The declaring class */ public function getDeclaringClass() { return new ClassReflection(parent::getDeclaringClass()->getName()); } /** * Returns the parameter class * * @return ClassReflection The parameter class */ public function getClass() { try { $class = parent::getClass(); } catch (\Exception $exception) { return null; } return is_object($class) ? new ClassReflection($class->getName()) : null; } /** * @return string The name of a builtin type (e.g. string, int) if it was declared for the parameter (scalar type declaration), null otherwise */ public function getBuiltinType() { if (!is_callable([$this, 'getType'])) { return null; } $type = $this->getType(); if ($type === null || !$type->isBuiltin()) { return null; } return (string)$type; } }
Add comment about blocking work to be done
package fault.java.singlewriter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; /** * Created by timbrooks on 11/16/14. */ public class ResilientPromise<T> { public T result; public Throwable error; private Status status = Status.PENDING; // TODO The CountDownLatch on POSIX is leading to very high await latency. Should look at blocking in FutureTask // TODO which does not have the same issue. There is probably some spin and park strategy work in that case. private CountDownLatch latch = new CountDownLatch(1); public void deliverResult(T result) { this.result = result; status = Status.SUCCESS; latch.countDown(); } public void deliverError(Throwable error) { this.error = error; status = Status.ERROR; latch.countDown(); } public void await() throws InterruptedException { latch.await(); } public T getResult() { return result; } public void setTimedOut() { status = Status.TIMED_OUT; latch.countDown(); } public boolean isSuccessful() { return status == Status.SUCCESS; } public boolean isDone() { return status != Status.PENDING; } public boolean isError() { return status == Status.ERROR; } public boolean isTimedOut() { return status == Status.TIMED_OUT; } public enum Status {SUCCESS, ERROR, PENDING, TIMED_OUT} }
package fault.java.singlewriter; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReference; /** * Created by timbrooks on 11/16/14. */ public class ResilientPromise<T> { public T result; public Throwable error; private Status status = Status.PENDING; private CountDownLatch latch = new CountDownLatch(1); public void deliverResult(T result) { this.result = result; status = Status.SUCCESS; latch.countDown(); } public void deliverError(Throwable error) { this.error = error; status = Status.ERROR; latch.countDown(); } public void await() throws InterruptedException { latch.await(); } public T getResult() { return result; } public void setTimedOut() { status = Status.TIMED_OUT; latch.countDown(); } public boolean isSuccessful() { return status == Status.SUCCESS; } public boolean isDone() { return status != Status.PENDING; } public boolean isError() { return status == Status.ERROR; } public boolean isTimedOut() { return status == Status.TIMED_OUT; } public enum Status {SUCCESS, ERROR, PENDING, TIMED_OUT} }
Use `find_packages()` like all the cool kids do.
from setuptools import setup from setuptools import setup, find_packages exec (open('plotly/version.py').read()) def readme(): with open('README.rst') as f: return f.read() setup(name='plotly', version=__version__, use_2to3=False, author='Chris P', author_email='[email protected]', maintainer='Chris P', maintainer_email='[email protected]', url='https://plot.ly/api/python', description="Python plotting library for collaborative, " "interactive, publication-quality graphs.", long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Visualization', ], license='MIT', packages=find_packages(), package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']}, install_requires=['requests', 'six', 'pytz'], extras_require={"PY2.6": ['simplejson', 'ordereddict', 'requests[security]']}, zip_safe=False)
from setuptools import setup exec (open('plotly/version.py').read()) def readme(): with open('README.rst') as f: return f.read() setup(name='plotly', version=__version__, use_2to3=False, author='Chris P', author_email='[email protected]', maintainer='Chris P', maintainer_email='[email protected]', url='https://plot.ly/api/python', description="Python plotting library for collaborative, " "interactive, publication-quality graphs.", long_description=readme(), classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering :: Visualization', ], license='MIT', packages=['plotly', 'plotly/plotly', 'plotly/plotly/chunked_requests', 'plotly/graph_objs', 'plotly/grid_objs', 'plotly/widgets', 'plotly/matplotlylib', 'plotly/matplotlylib/mplexporter', 'plotly/matplotlylib/mplexporter/renderers'], package_data={'plotly': ['graph_reference/*.json', 'widgets/*.js']}, install_requires=['requests', 'six', 'pytz'], extras_require={"PY2.6": ['simplejson', 'ordereddict', 'requests[security]']}, zip_safe=False)
Return HTTP 502 and error message if upstream server error.
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); try { ctx.body = await request(url, options); } catch (error) { ctx.status = 502; ctx.body = {error: error.message}; } }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
const util = require('util'); const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor(verbose) { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; if (verbose) { if (options) { console.log(url, util.inspect(options, {depth: null, breakLength: Infinity})); } else { console.log(url); } } options = Object.assing({forever: true, gzip: true}, options); ctx.body = await request(url, options); }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
Include colons in URL matching
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) response = requests.get(url) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url
from plugins.categories import ISilentCommand try: import requests_pyopenssl from requests.packages.urllib3 import connectionpool connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket except ImportError: pass import requests from bs4 import BeautifulSoup class URLGrabber (ISilentCommand): triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-]+).*': "url"} def trigger_url(self, context, user, channel, match): if user == 'JustCommit': return try: url = match.group(1) response = requests.get(url) except (requests.exceptions.ConnectionError) as e: print "Failed to load URL: %s" % url print "Message: %s" % e else: soup = BeautifulSoup(response.text) if soup.title and soup.title.text: title = soup.title.string title = title.replace('\n', '') # remove newlines title = title.replace('\x01', '') # remove dangerous control character \001 title = ' '.join(title.split()) # normalise all other whitespace # Truncate length if len(title) > 120: title = title[:117] + "..." return title else: print "URL has no title: %s" % url
Remove unnecessary access modifiers from nested private class
package com.ibm.mil.smartringer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; public class IncomingCallReceiver extends BroadcastReceiver { private static final String TAG = IncomingCallReceiver.class.getName(); private static PhoneStateListener phoneStateListener; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Received system event for change in phone state"); // register phone state listener only once if (phoneStateListener == null) { phoneStateListener = new IncomingCallPhoneStateListener(context); TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } } private static class IncomingCallPhoneStateListener extends PhoneStateListener { Context mContext; boolean isInitialRing = true; IncomingCallPhoneStateListener(Context context) { mContext = context; } @Override public void onCallStateChanged(int state, String incomingNumber) { if (state == TelephonyManager.CALL_STATE_RINGING && isInitialRing) { mContext.startService(new Intent(mContext, RingerAdjusterService.class)); // prevents CALL_STATE_RINGING from being triggered multiple times isInitialRing = false; } } } }
package com.ibm.mil.smartringer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; public class IncomingCallReceiver extends BroadcastReceiver { private static final String TAG = IncomingCallReceiver.class.getName(); private static PhoneStateListener phoneStateListener; @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "Received system event for change in phone state"); // register phone state listener only once if (phoneStateListener == null) { Log.i(TAG, "Phone state listener is being initialized"); phoneStateListener = new IncomingCallPhoneStateListener(context); TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } } private static class IncomingCallPhoneStateListener extends PhoneStateListener { private Context mContext; private boolean isInitialRing = true; public IncomingCallPhoneStateListener(Context context) { mContext = context; } @Override public void onCallStateChanged(int state, String incomingNumber) { if (state == TelephonyManager.CALL_STATE_RINGING && isInitialRing) { mContext.startService(new Intent(mContext, RingerAdjusterService.class)); // prevents CALL_STATE_RINGING from being triggered multiple times isInitialRing = false; } } } }
Set Hystrix group key to command class name
package name.webdizz.fault.tolerance.inventory.client.command; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> { private final InventoryRequester inventoryRequester; private final Store store; private final Product product; public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName())) .andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName())) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withCircuitBreakerForceClosed(true) .withExecutionTimeoutInMilliseconds(timeoutInMillis)) ); this.inventoryRequester = inventoryRequester; this.store = store; this.product = product; } @Override protected Inventory run() throws Exception { return inventoryRequester.requestInventoryFor(store, product); } }
package name.webdizz.fault.tolerance.inventory.client.command; import name.webdizz.fault.tolerance.inventory.client.InventoryRequester; import name.webdizz.fault.tolerance.inventory.domain.Inventory; import name.webdizz.fault.tolerance.inventory.domain.Product; import name.webdizz.fault.tolerance.inventory.domain.Store; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandKey; import com.netflix.hystrix.HystrixCommandProperties; public class TimeOutInventoryRequestCommand extends HystrixCommand<Inventory> { private final InventoryRequester inventoryRequester; private final Store store; private final Product product; public TimeOutInventoryRequestCommand(final int timeoutInMillis, final InventoryRequester inventoryRequester, final Store store, final Product product) { super(Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("InventoryRequest")) .andCommandKey(HystrixCommandKey.Factory.asKey(TimeOutInventoryRequestCommand.class.getSimpleName())) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withCircuitBreakerForceClosed(true) .withExecutionTimeoutInMilliseconds(timeoutInMillis)) ); this.inventoryRequester = inventoryRequester; this.store = store; this.product = product; } @Override protected Inventory run() throws Exception { return inventoryRequester.requestInventoryFor(store, product); } }
Change event tracking to reflect latest button text.
/** * Meetings and Conferences */ var m = require('mithril'); var $osf = require('js/osfHelpers'); // CSS require('css/meetings-and-conferences.css'); var MeetingsAndConferences = { view: function(ctrl) { return m('.p-v-sm', m('.row', [ m('.col-md-8', [ m('div.conference-centering', m('h3', 'Hosting a conference or meeting?')), m('div.conference-centering.m-t-lg', m('p.text-bigger', 'Use the OSF for Meetings service to provide a central location for conference submissions.') ) ] ), m('.col-md-4.text-center', m('div', m('a.btn.btn-info.btn-lg.m-v-xl', { style : 'box-shadow: 0 0 9px -4px #000;', type:'button', href:'/meetings/', onclick: function() { $osf.trackClick('meetingsAndConferences', 'navigate', 'navigate-to-view-meetings'); }}, 'View meetings')) ) ] ) ); } }; module.exports = MeetingsAndConferences;
/** * Meetings and Conferences */ var m = require('mithril'); var $osf = require('js/osfHelpers'); // CSS require('css/meetings-and-conferences.css'); var MeetingsAndConferences = { view: function(ctrl) { return m('.p-v-sm', m('.row', [ m('.col-md-8', [ m('div.conference-centering', m('h3', 'Hosting a conference or meeting?')), m('div.conference-centering.m-t-lg', m('p.text-bigger', 'Use the OSF for Meetings service to provide a central location for conference submissions.') ) ] ), m('.col-md-4.text-center', m('div', m('a.btn.btn-info.btn-lg.m-v-xl', { style : 'box-shadow: 0 0 9px -4px #000;', type:'button', href:'/meetings/', onclick: function() { $osf.trackClick('meetingsAndConferences', 'navigate', 'navigate-to-create-a-meeting'); }}, 'Create a Meeting')) ) ] ) ); } }; module.exports = MeetingsAndConferences;
Fix chart no data display
var merge = require('merge'); var temperature = require('../model/temperature.js'); var humidity = require('../model/humidity.js'); var gas = require('../model/gas.js'); var co = require('../model/co.js'); var timestamp = require('../timestamp.js'); exports.index = function index(callback) { // FIXME: callback hell temperature.get5MinData(function (result) { var data = {data_temperature: handleResult('temperature', result)}; humidity.get5MinData(function (result) { data = merge(data, {data_humidity: handleResult('humidity', result)}); gas.get5MinData(function (result) { data = merge(data, {data_gas: handleResult('gas', result)}); co.get5MinData(function (result) { callback(merge(data, {data_co: handleResult('co', result)})); }); }); }); }); }; function handleResult(title, result) { var data = [ [{label: 'Times', type: 'date'}, title] ]; if (result.length == 0) { data.push([timestamp.toChartDateString(new Date()), 0]); } for (var i in result) { data.push([ timestamp.toChartDateString(result[i].saved), result[i].value ]); } return data; }
var merge = require('merge'); var temperature = require('../model/temperature.js'); var humidity = require('../model/humidity.js'); var gas = require('../model/gas.js'); var co = require('../model/co.js'); var timestamp = require('../timestamp.js'); exports.index = function index(callback) { // FIXME: callback hell temperature.get5MinData(function (result) { var data = {data_temperature: handleResult('temperature', result)}; humidity.get5MinData(function (result) { data = merge(data, {data_humidity: handleResult('humidity', result)}); gas.get5MinData(function (result) { data = merge(data, {data_gas: handleResult('gas', result)}); co.get5MinData(function (result) { callback(merge(data, {data_co: handleResult('co', result)})); }); }); }); }); }; function handleResult(title, result) { var data = [ [{label: 'Times', type: 'date'}, title] ]; if (result.length == 0) { data.push(['', 0]); } for (var i in result) { data.push([ timestamp.toChartDateString(result[i].saved), result[i].value ]); } return data; }
Handle situation where dav does not send length
from __future__ import unicode_literals import requests from django.core.files import File from django.core.files.storage import Storage from davstorage.utils import trim_trailing_slash class DavStorage(Storage): def __init__(self, internal_url, external_url): self._internal_url = trim_trailing_slash(internal_url) self._external_url = trim_trailing_slash(external_url) def exists(self, name): url = self.internal_url(name) response = requests.head(url) return response.status_code == 200 def delete(self, name): url = self.internal_url(name) requests.delete(url) def size(self, name): url = self.internal_url(name) response = requests.head(url, headers={'accept-encoding': None}) content_length = response.headers.get('content-length') try: return int(content_length) except (TypeError, ValueError): return None def url(self, name): return '%s/%s' % (self._external_url, name) def internal_url(self, name): return '%s/%s' % (self._internal_url, name) def _open(self, name, mode='rb'): url = self.internal_url(name) response = requests.get(url, stream=True) response.raw.decode_content = True return File(response.raw, name) def _save(self, name, content): url = self.internal_url(name) requests.put(url, data=content) return name
from __future__ import unicode_literals import requests from django.core.files import File from django.core.files.storage import Storage from davstorage.utils import trim_trailing_slash class DavStorage(Storage): def __init__(self, internal_url, external_url): self._internal_url = trim_trailing_slash(internal_url) self._external_url = trim_trailing_slash(external_url) def exists(self, name): url = self.internal_url(name) response = requests.head(url) return response.status_code == 200 def delete(self, name): url = self.internal_url(name) requests.delete(url) def size(self, name): url = self.internal_url(name) response = requests.head(url, headers={'accept-encoding': None}) return int(response.headers['content-length']) def url(self, name): return '%s/%s' % (self._external_url, name) def internal_url(self, name): return '%s/%s' % (self._internal_url, name) def _open(self, name, mode='rb'): url = self.internal_url(name) response = requests.get(url, stream=True) response.raw.decode_content = True return File(response.raw, name) def _save(self, name, content): url = self.internal_url(name) requests.put(url, data=content) return name
Add source maps in dev
const path = require("path"); const webpack = require("webpack"); module.exports = { devtool: "source-map", resolve: { extensions: [".js"] }, module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"] }, { test: /\.js$/, exclude: /(node_modules)/, use: { loader: "babel-loader" } }, { test: /\.(wsz|mp3)$/, use: [ { loader: "file-loader", options: { emitFile: true, name: "[path][name]-[hash].[ext]" } } ] } ], noParse: [/jszip\.js$/] }, plugins: [ new webpack.DefinePlugin({ SENTRY_DSN: JSON.stringify( "https://[email protected]/146022" ) }) ], entry: { winamp: ["./js/index.js"], skinExplorer: "./js/skinExplorer.js" }, output: { filename: "[name].js", publicPath: "/built/", path: path.resolve(__dirname, "built") } };
const path = require("path"); const webpack = require("webpack"); module.exports = { resolve: { extensions: [".js"] }, module: { rules: [ { test: /\.css$/, use: ["style-loader", "css-loader"] }, { test: /\.js$/, exclude: /(node_modules)/, use: { loader: "babel-loader" } }, { test: /\.(wsz|mp3)$/, use: [ { loader: "file-loader", options: { emitFile: true, name: "[path][name]-[hash].[ext]" } } ] } ], noParse: [/jszip\.js$/] }, plugins: [ new webpack.DefinePlugin({ SENTRY_DSN: JSON.stringify( "https://[email protected]/146022" ) }) ], entry: { winamp: ["./js/index.js"], skinExplorer: "./js/skinExplorer.js" }, output: { filename: "[name].js", publicPath: "/built/", path: path.resolve(__dirname, "built") } };
Update redux to version 2.0
import React from 'react'; import { createStore, combineReducers, compose } from 'redux'; import { Provider } from 'react-redux'; import * as reducers from './_reducers'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import { Router } from 'react-router'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import routes from './routes'; import LiveData from './_data/LiveData'; const finalCreateStore = compose( devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); function openDevTools() { const win = window.open(null, 'redux-devtools', 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no'); win.location.reload(); setTimeout(() => { React.render( <DebugPanel top right bottom left > <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> , win.document.body); }, 10); } export default class Root extends React.Component { render() { const history = new BrowserHistory(); const liveData = new LiveData(store); openDevTools(); liveData.init(); return ( <Provider store={store}> {() => <Router history={history} children={routes}/>} </Provider> ); } }
import React from 'react'; import { createStore, combineReducers, compose } from 'redux'; import { provide } from 'react-redux'; import * as reducers from './_reducers'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import { Router } from 'react-router'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import routes from './routes'; import LiveData from './_data/LiveData'; const finalCreateStore = compose( devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)), createStore ); const reducer = combineReducers(reducers); const store = finalCreateStore(reducer); function openDevTools() { const win = window.open(null, 'redux-devtools', 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no'); win.location.reload(); setTimeout(() => { React.render( <DebugPanel top right bottom left > <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> , win.document.body); }, 10); } @provide(store) export default class Root extends React.Component { render() { const history = new BrowserHistory(); const liveData = new LiveData(store); openDevTools(); liveData.init(); return ( <div> <Router history={history} children={routes}/> </div> ); } }
Allow modals to close themselves For example on accept.
import React from 'react'; import Top from 'app/containers/top' import Login from 'app/containers/login.js' import Console from 'app/containers/console.js' import FlashMessageList from 'app/containers/flashmessages.js' import Router from 'app/router' import get_modal from './modalfactory' import Piwik from 'app/containers/piwik.js' function Main(props){ //console.log("Main component props %o", props.location) let modal = [] if (props.location.state && props.location.state.modal){ const mod = props.location.state const Modal = get_modal(mod.modal) if (Modal){ console.log("Render Modal %o -> %o", mod.modal, Modal) const dispatch = require('app/utils/store').default.dispatch const goBack = require('react-router-redux').goBack modal=( <Modal {...mod.data} onClose={ () => dispatch( goBack() ) }/> ) } else{ console.error("Error rendering modal: %o. Not found.", mod.modal) } } var contents=[] if (props.logged_in) contents=( <div> <Top onLogout={props.onLogout}/> <div className="ui main area"> <Router/> {modal} </div> </div> ) else contents=( <Login onLogin={props.onLogin}/> ) return ( <div> <Piwik/> <FlashMessageList/> <Console/> {contents} </div> ) } export default Main
import React from 'react'; import Top from 'app/containers/top' import Login from 'app/containers/login.js' import Console from 'app/containers/console.js' import FlashMessageList from 'app/containers/flashmessages.js' import Router from 'app/router' import get_modal from './modalfactory' import Piwik from 'app/containers/piwik.js' function Main(props){ //console.log("Main component props %o", props.location) let modal = [] if (props.location.state && props.location.state.modal){ const mod = props.location.state const Modal = get_modal(mod.modal) if (Modal){ console.log("Render Modal %o -> %o", mod.modal, Modal) modal=( <Modal {...mod.data}/> ) } else{ console.error("Error rendering modal: %o. Not found.", mod.modal) } } var contents=[] if (props.logged_in) contents=( <div> <Top onLogout={props.onLogout}/> <div className="ui main area"> <Router/> {modal} </div> </div> ) else contents=( <Login onLogin={props.onLogin}/> ) return ( <div> <Piwik/> <FlashMessageList/> <Console/> {contents} </div> ) } export default Main
Replace anonymous type with lambda
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features; import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView; import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @author Jan Molak */ public class HasHeadline implements Feature<Headline> { private final HeadlineConfig config; private JobView job; public HasHeadline(HeadlineConfig config) { this.config = config; } @Override public HasHeadline of(JobView jobView) { this.job = jobView; return this; } @Override public Headline asJson() { return headlineOf(job).asJson(); } private CandidateHeadline headlineOf(final JobView job) { List<CandidateHeadline> availableHeadlines = new ArrayList<>(); Collections.addAll(availableHeadlines, new HeadlineOfExecuting(job, config), new HeadlineOfAborted(job, config), new HeadlineOfFixed(job, config), new HeadlineOfFailing(job, config) ); return availableHeadlines.stream() .filter(candidateHeadline -> candidateHeadline.isApplicableTo(job)) .findFirst() .orElse(new NoHeadline()); } }
package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features; import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView; import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; /** * @author Jan Molak */ public class HasHeadline implements Feature<Headline> { private final HeadlineConfig config; private JobView job; public HasHeadline(HeadlineConfig config) { this.config = config; } @Override public HasHeadline of(JobView jobView) { this.job = jobView; return this; } @Override public Headline asJson() { return headlineOf(job).asJson(); } private CandidateHeadline headlineOf(final JobView job) { List<CandidateHeadline> availableHeadlines = new ArrayList<>(); Collections.addAll(availableHeadlines, new HeadlineOfExecuting(job, config), new HeadlineOfAborted(job, config), new HeadlineOfFixed(job, config), new HeadlineOfFailing(job, config) ); return availableHeadlines.stream().filter(new Predicate<CandidateHeadline>() { @Override public boolean test(CandidateHeadline candidateHeadline) { return candidateHeadline.isApplicableTo(job); } }).findFirst().orElse(new NoHeadline()); } }
Add brackets around rule ID in parseable format. This formatter was supposed to model after the PEP8 format, but was incorrect. The actualy format is: "<filename>:<linenumber>: [<rule.id>] <message>"
class Formatter: def format(self, match): formatstr = "[{0}] {1}\n{2}:{3}\n{4}\n" return formatstr.format(match.rule.id, match.message, match.filename, match.linenumber, match.line) class QuietFormatter: def format(self, match): formatstr = "[{0}] {1}:{2}" return formatstr.format(match.rule.id, match.filename, match.linenumber) class ParseableFormatter: def format(self, match): formatstr = "{0}:{1}: [{2}] {3}" return formatstr.format(match.filename, match.linenumber, match.rule.id, match.message, )
class Formatter: def format(self, match): formatstr = "[{0}] {1}\n{2}:{3}\n{4}\n" return formatstr.format(match.rule.id, match.message, match.filename, match.linenumber, match.line) class QuietFormatter: def format(self, match): formatstr = "[{0}] {1}:{2}" return formatstr.format(match.rule.id, match.filename, match.linenumber) class ParseableFormatter: def format(self, match): formatstr = "{0}:{1}: {2} {3}" return formatstr.format(match.filename, match.linenumber, match.rule.id, match.message, )
BAP-16688: Replace form aliases by FQCN in entity configs
<?php namespace Oro\Bundle\CalendarBundle\Migrations\Schema\v1_14; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\EntityBundle\EntityConfig\DatagridScope; use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope; use Oro\Bundle\FormBundle\Form\Type\OroResizeableRichTextType; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class AddExtendDescription implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { $table = $schema->getTable('oro_system_calendar'); if (!$table->hasColumn('extend_description')) { $table->addColumn( 'extend_description', 'text', [ 'oro_options' => [ 'extend' => ['is_extend' => true, 'owner' => ExtendScope::OWNER_CUSTOM], 'datagrid' => ['is_visible' => DatagridScope::IS_VISIBLE_FALSE], 'merge' => ['display' => true], 'dataaudit' => ['auditable' => true], 'form' => ['type' => OroResizeableRichTextType::class], 'view' => ['type' => 'html'], ] ] ); } } }
<?php namespace Oro\Bundle\CalendarBundle\Migrations\Schema\v1_14; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\EntityBundle\EntityConfig\DatagridScope; use Oro\Bundle\EntityExtendBundle\EntityConfig\ExtendScope; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class AddExtendDescription implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { $table = $schema->getTable('oro_system_calendar'); if (!$table->hasColumn('extend_description')) { $table->addColumn( 'extend_description', 'text', [ 'oro_options' => [ 'extend' => ['is_extend' => true, 'owner' => ExtendScope::OWNER_CUSTOM], 'datagrid' => ['is_visible' => DatagridScope::IS_VISIBLE_FALSE], 'merge' => ['display' => true], 'dataaudit' => ['auditable' => true], 'form' => ['type' => 'oro_resizeable_rich_text'], 'view' => ['type' => 'html'], ] ] ); } } }
Fix whitespace issue with Admin Panel ModelAdmin columns
@if (method_exists($modelAdmin, 'tableTbodyRow')) {{ $modelAdmin->tableTbodyRow($modelItem) }} @else <tr> @foreach ($modelAdmin->getColumns() as $key => $field) <td>{!! $modelAdmin->getAttribute($key, $modelItem) !!}</td> @endforeach <td style="width: 1%; white-space:nowrap"> @include('flare::admin.modeladmin.includes.table.actions.before') @if ($modelAdmin->hasViewing()) @include('flare::admin.modeladmin.includes.table.actions.view') @endif @if ($modelAdmin->hasEditting()) @include('flare::admin.modeladmin.includes.table.actions.edit') @endif @if ($modelAdmin->hasDeleting() && ($modelAdmin->hasSoftDeleting() && $modelItem->trashed())) @include('flare::admin.modeladmin.includes.table.actions.restore') @elseif ($modelAdmin->hasCloning()) @include('flare::admin.modeladmin.includes.table.actions.clone') @endif @if ($modelAdmin->hasDeleting()) @include('flare::admin.modeladmin.includes.table.actions.delete') @endif @include('flare::admin.modeladmin.includes.table.actions.after') </td> </tr> @endif
@if (method_exists($modelAdmin, 'tableTbodyRow')) {{ $modelAdmin->tableTbodyRow($modelItem) }} @else <tr> @foreach ($modelAdmin->getColumns() as $key => $field) <td> {!! $modelAdmin->getAttribute($key, $modelItem) !!} </td> @endforeach <td style="width: 1%; white-space:nowrap"> @include('flare::admin.modeladmin.includes.table.actions.before') @if ($modelAdmin->hasViewing()) @include('flare::admin.modeladmin.includes.table.actions.view') @endif @if ($modelAdmin->hasEditting()) @include('flare::admin.modeladmin.includes.table.actions.edit') @endif @if ($modelAdmin->hasDeleting() && ($modelAdmin->hasSoftDeleting() && $modelItem->trashed())) @include('flare::admin.modeladmin.includes.table.actions.restore') @elseif ($modelAdmin->hasCloning()) @include('flare::admin.modeladmin.includes.table.actions.clone') @endif @if ($modelAdmin->hasDeleting()) @include('flare::admin.modeladmin.includes.table.actions.delete') @endif @include('flare::admin.modeladmin.includes.table.actions.after') </td> </tr> @endif
Rename f to func in one last place (ActionQueue)
import logging import queue import threading log = logging.getLogger(__name__) class Action: func = None args = [] kwargs = {} def __init__(self, func=None, args=[], kwargs={}): self.func = func self.args = args self.kwargs = kwargs def run(self): self.func(*self.args, **self.kwargs) class ActionQueue: ID = 0 def __init__(self): self.queue = queue.Queue() self.id = ActionQueue.ID ActionQueue.ID += 1 # Starts a thread which will continuously check the queue for actions. def start(self): t = threading.Thread(target=self._action_parser, name="ActionQueueThread_{}".format(self.id)) t.daemon = True t.start() # Start a loop which waits and things to be added into the queue. # Note: This is a blocking method, and should be run in a separate thread # This method is started automatically if ActionQueue is declared threaded. def _action_parser(self): while True: action = self.queue.get() action.run() # Run a single action in the queue if the queue is not empty. def parse_action(self): if not self.queue.empty(): action = self.queue.get() action.run() def add(self, func, args=[], kwargs={}): action = Action(func, args, kwargs) self._add(action) def _add(self, action): self.queue.put(action)
import logging import queue import threading log = logging.getLogger(__name__) class Action: func = None args = [] kwargs = {} def __init__(self, func=None, args=[], kwargs={}): self.func = func self.args = args self.kwargs = kwargs def run(self): self.func(*self.args, **self.kwargs) class ActionQueue: ID = 0 def __init__(self): self.queue = queue.Queue() self.id = ActionQueue.ID ActionQueue.ID += 1 # Starts a thread which will continuously check the queue for actions. def start(self): t = threading.Thread(target=self._action_parser, name="ActionQueueThread_{}".format(self.id)) t.daemon = True t.start() # Start a loop which waits and things to be added into the queue. # Note: This is a blocking method, and should be run in a separate thread # This method is started automatically if ActionQueue is declared threaded. def _action_parser(self): while True: action = self.queue.get() action.run() # Run a single action in the queue if the queue is not empty. def parse_action(self): if not self.queue.empty(): action = self.queue.get() action.run() def add(self, f, args=[], kwargs={}): action = Action(f, args, kwargs) self._add(action) def _add(self, action): self.queue.put(action)
Use exchange instead of topic from joram
package no.ntnu.okse.protocol.amqp091; import no.ntnu.okse.core.messaging.Message; import no.ntnu.okse.core.messaging.MessageService; import no.ntnu.okse.core.subscription.Publisher; import org.ow2.joram.mom.amqp.AMQPMessageListener; import org.ow2.joram.mom.amqp.messages.*; public class AMQP091MessageListener implements AMQPMessageListener { private final AMQP091ProtocolServer amqpProtocolServer; public AMQP091MessageListener(AMQP091ProtocolServer amqp091ProtocolServer) { this.amqpProtocolServer = amqp091ProtocolServer; } @Override public void onConnect(ConnectMessage connectMessage) { } @Override public void onDisconnect(DisconnectMessage disConnectMessage) { } @Override public void onMessageReceived(MessageReceived messageReceived) { String message = new String(messageReceived.getBody()); String topic = messageReceived.getExchange(); String host = messageReceived.getHost(); int port = messageReceived.getPort(); String protocolServerType = amqpProtocolServer.getProtocolServerType(); Publisher pub = new Publisher(topic, host, port, protocolServerType); MessageService.getInstance().distributeMessage(new Message(message, topic, pub, protocolServerType)); } @Override public void onSubscribe(SubscribeMessage subscribeMessage) { } @Override public void onUnsubscribe(UnsubscribeMessage unsubscribeMessage) { } }
package no.ntnu.okse.protocol.amqp091; import no.ntnu.okse.core.messaging.Message; import no.ntnu.okse.core.messaging.MessageService; import no.ntnu.okse.core.subscription.Publisher; import org.ow2.joram.mom.amqp.AMQPMessageListener; import org.ow2.joram.mom.amqp.messages.*; public class AMQP091MessageListener implements AMQPMessageListener { private final AMQP091ProtocolServer amqpProtocolServer; public AMQP091MessageListener(AMQP091ProtocolServer amqp091ProtocolServer) { this.amqpProtocolServer = amqp091ProtocolServer; } @Override public void onConnect(ConnectMessage connectMessage) { } @Override public void onDisconnect(DisconnectMessage disConnectMessage) { } @Override public void onMessageReceived(MessageReceived messageReceived) { String message = new String(messageReceived.getBody()); String topic = messageReceived.getTopic(); String host = messageReceived.getHost(); int port = messageReceived.getPort(); String protocolServerType = amqpProtocolServer.getProtocolServerType(); Publisher pub = new Publisher(topic, host, port, protocolServerType); MessageService.getInstance().distributeMessage(new Message(message, topic, pub, protocolServerType)); } @Override public void onSubscribe(SubscribeMessage subscribeMessage) { } @Override public void onUnsubscribe(UnsubscribeMessage unsubscribeMessage) { } }
Add handler for when setTab is given a non-exsitant tab id
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange"; if (!this.querySelector("[id='"+tabid+"'][role='tab']")) { console.error("Cannot set to unknown tabid"); return false; } //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return true; } } }); })();
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; this.setTab(el.id, true); } }, accessors: { role: { attribute: {} } }, methods: { setTab: function (tabid, fireEvent) { var eventName = "tabChange", result = true; //Checks if person is trying to set to currently active tab if (this.activeTabId === tabid) { eventName = "activeTabPress" result = false; } else { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; } if (fireEvent) xtag.fireEvent(this, eventName, {detail: this.activeTabId}); return result; } } }); })();
Remove unneeded momentjs inclusion in blueprint
/* globals module */ module.exports = { afterInstall: function() { var self = this; return this.addBowerPackageToProject( 'bootstrap-datepicker' ) .then( function() { return self.addBowerPackageToProject( 'fontawesome' ); }) .then( function() { return self.addBowerPackageToProject( 'highcharts' ); }) .then( function() { return self.addBowerPackageToProject( 'moment' ); }) .then( function() { return self.addBowerPackageToProject( 'moment-timezone' ); }) .then( function() { return self.addBowerPackageToProject( 'select2' ); }) .then( function() { return self.addBowerPackageToProject( 'typeahead.js' ); }) .then( function() { return self.addBowerPackageToProject( '[email protected]:interface/sl-bootstrap#0.6.1' ); }); }, normalizeEntityName: function() {} };
/* globals module */ module.exports = { afterInstall: function() { var self = this; return this.addBowerPackageToProject( 'bootstrap-datepicker' ) .then( function() { return self.addBowerPackageToProject( 'momentjs' ); }) .then( function() { return self.addBowerPackageToProject( 'fontawesome' ); }) .then( function() { return self.addBowerPackageToProject( 'highcharts' ); }) .then( function() { return self.addBowerPackageToProject( 'moment' ); }) .then( function() { return self.addBowerPackageToProject( 'moment-timezone' ); }) .then( function() { return self.addBowerPackageToProject( 'select2' ); }) .then( function() { return self.addBowerPackageToProject( 'typeahead.js' ); }) .then( function() { return self.addBowerPackageToProject( '[email protected]:interface/sl-bootstrap#0.6.1' ); }); }, normalizeEntityName: function() {} };
Fix exception handling in management command. Clean up.
"""Creates an admin user if there aren't any existing superusers.""" from optparse import make_option from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Creates/Updates an Admin user' def add_arguments(self, parser): parser.add_argument('--username', action='store', dest='username', default=None, help='Admin username') parser.add_argument('--password', action='store', dest='password', default=None, help='Admin password') def handle(self, *args, **options): username = options.get('username') password = options.get('password') if not username or not password: raise CommandError('You must specify a username and password') # Get the current superusers su_count = User.objects.filter(is_superuser=True).count() if su_count == 0: # there aren't any superusers, create one user, created = User.objects.get_or_create(username=username) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() print(f'{username} updated') else: print(f'There are already {su_count} superusers')
''' Creates an admin user if there aren't any existing superusers ''' from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from optparse import make_option class Command(BaseCommand): help = 'Creates/Updates an Admin user' def add_arguments(self, parser): parser.add_argument('--username', action='store', dest='username', default=None, help='Admin username') parser.add_argument('--password', action='store', dest='password', default=None, help='Admin password') def handle(self, *args, **options): username = options.get('username') password = options.get('password') if not username or not password: raise StandardError('You must specify a username and password') # Get the current superusers su_count = User.objects.filter(is_superuser=True).count() if su_count == 0: # there aren't any superusers, create one user, created = User.objects.get_or_create(username=username) user.set_password(password) user.is_staff = True user.is_superuser = True user.save() print('{0} updated'.format(username)) else: print('There are already {0} superusers'.format(su_count))
Add method to reset SQL schema and to empty the container
<?php namespace PhpAbac; use PhpAbac\Manager\AttributeManager; use PhpAbac\Manager\PolicyRuleManager; class Abac { /** @var array **/ private static $container; /** * @param \PDO $connection */ public function __construct(\PDO $connection) { // Set the main managers self::set('pdo-connection', $connection); self::set('policy-rule-manager', new PolicyRuleManager()); self::set('attribute-manager', new AttributeManager()); } public static function resetSchema() { self::get('pdo-connection')->exec( file_get_contents(dirname(dirname(__DIR__)) . '/sql/schema.sql') ); } public static function clearContainer() { self::$container = null; } /** * @param string $serviceName * @param mixed $service * @param boolean $force * @throws \InvalidArgumentException */ public static function set($serviceName, $service, $force = false) { if(self::has($serviceName) && $force === false) { throw new \InvalidArgumentException( "The service $serviceName is already set in PhpAbac container. ". 'Please set $force parameter to true if you want to replace the set service' ); } self::$container[$serviceName] = $service; } /** * @param string $serviceName * @return boolean */ public static function has($serviceName) { return isset(self::$container[$serviceName]); } /** * @throws \InvalidArgumentException * @return mixed */ public static function get($serviceName) { if(!self::has($serviceName)) { throw new \InvalidArgumentException("The PhpAbac container has no service named $serviceName"); } return self::$container[$serviceName]; } }
<?php namespace PhpAbac; class Abac { /** @var array **/ private static $container; /** * @param \PDO $connection */ public function __construct($connection) { self::set('policy-rule-manager', new PolicyRuleManager()); self::set('attribute-manager', new AttributeManager()); self::set('pdo-connection', $connection); } /** * @param string $serviceName * @param mixed $service * @param boolean $force * @throws \InvalidArgumentException */ public static function set($serviceName, $service, $force = false) { if(self::has($serviceName) && $force === false) { throw new \InvalidArgumentException( "The service $serviceName is already set in PhpAbac container. ". 'Please set $force parameter to true if you want to replace the set service' ); } self::$container[$serviceName] = $service; } /** * @param string $serviceName * @return boolean */ public static function has($serviceName) { return isset(self::$container[$serviceName]); } /** * @throws \InvalidArgumentException * @return mixed */ public static function get($serviceName) { if(!self::has($serviceName)) { throw new \InvalidArgumentException("The PhpAbac container has no service named $serviceName"); } return self::$container[$serviceName]; } }
Exclude tests from set of installed packages
from ez_setup import use_setuptools # https://pypi.python.org/pypi/setuptools use_setuptools() from setuptools import setup, find_packages from packager import __version__ # Get the long description from the README file. def get_long_description(): from codecs import open from os import path here = path.abspath(path.dirname(__file__)) try: with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() except: return [] else: return long_description setup( name='packagebuilder', version=__version__, description='Tools for building rpm and deb packages for CSDMS software', long_description=get_long_description(), url='https://github.com/csdms/packagebuilder', author='Mark Piper', author_email='[email protected]', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='CSDMS, earth system modeling, packaging, Linux, rpm, deb', packages=find_packages(exclude=['*test']), install_requires=['nose'], package_data={ 'packager': ['repositories.txt'], }, entry_points={ 'console_scripts': [ 'build_rpm=packager.rpm.build:main', ], }, )
from ez_setup import use_setuptools # https://pypi.python.org/pypi/setuptools use_setuptools() from setuptools import setup, find_packages from packager import __version__ # Get the long description from the README file. def get_long_description(): from codecs import open from os import path here = path.abspath(path.dirname(__file__)) try: with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() except: return [] else: return long_description setup( name='packagebuilder', version=__version__, description='Tools for building rpm and deb packages for CSDMS software', long_description=get_long_description(), url='https://github.com/csdms/packagebuilder', author='Mark Piper', author_email='[email protected]', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='CSDMS, earth system modeling, packaging, Linux, rpm, deb', packages=find_packages(), install_requires=['nose'], package_data={ 'packager': ['repositories.txt'], }, entry_points={ 'console_scripts': [ 'build_rpm=packager.rpm.build:main', ], }, )
Use safe_load_all to detect errors in multi-document files
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Pyyaml plugin class.""" from SublimeLinter.lint import PythonLinter, persist class Pyyaml(PythonLinter): """Provides an interface to pyyaml.""" syntax = 'yaml' cmd = None regex = r'^:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)' line_col_base = (0, 0) # the lines and columns are 0-based module = 'yaml' def check(self, code, filename): """ Call directly the yaml module, and handles the exception. Return str. Very similar to the SublimeLinter-json linter, except yaml is not in the python core library. """ yaml = self.module try: for x in yaml.safe_load_all(code): # exhausting generator so all documents are checked pass except yaml.error.YAMLError as exc: if persist.settings.get('debug'): persist.printf('{} - {} : {}'.format(self.name, type(exc), exc)) message = '{} : {} {}'.format(type(exc).__name__, exc.problem, exc.context) return ':{}:{}: {}\n'.format(exc.problem_mark.line, exc.problem_mark.column, message) except Exception as exc: persist.printf('{} - uncaught exception - {} : {}'.format(self.name, type(exc), exc)) return ''
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Pyyaml plugin class.""" from SublimeLinter.lint import PythonLinter, persist class Pyyaml(PythonLinter): """Provides an interface to pyyaml.""" syntax = 'yaml' cmd = None regex = r'^:(?P<line>\d+):(?P<col>\d+): (?P<message>.+)' line_col_base = (0, 0) # the lines and columns are 0-based module = 'yaml' def check(self, code, filename): """ Call directly the yaml module, and handles the exception. Return str. Very similar to the SublimeLinter-json linter, except yaml is not in the python core library. """ yaml = self.module try: yaml.safe_load(code) except yaml.error.YAMLError as exc: if persist.settings.get('debug'): persist.printf('{} - {} : {}'.format(self.name, type(exc), exc)) message = '{} : {} {}'.format(type(exc).__name__, exc.problem, exc.context) return ':{}:{}: {}\n'.format(exc.problem_mark.line, exc.problem_mark.column, message) except Exception as exc: persist.printf('{} - uncaught exception - {} : {}'.format(self.name, type(exc), exc)) return ''
Fix evaluating complex spell properties on load
package com.elmakers.mine.bukkit.magic; import java.util.HashSet; import java.util.Set; import javax.annotation.Nullable; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class MageParameters extends ParameterizedConfiguration { private static Set<String> attributes; private final @Nullable Mage mage; public MageParameters(Mage mage, String context) { super(context); this.mage = mage; } public MageParameters(MageParameters copy) { super(copy); this.mage = copy.mage; } @Nullable protected MageController getController() { return mage == null ? null : mage.getController(); } @Nullable protected Mage getMage() { return mage; } public static void initializeAttributes(Set<String> attrs) { attributes = new HashSet<>(attrs); } @Override @Nullable protected Double evaluate(String expression) { if (mage != null && mage.isPlayer()) { expression = mage.getController().setPlaceholders(mage.getPlayer(), expression); } return super.evaluate(expression); } @Override protected double getParameter(String parameter) { Double value = mage == null ? null : mage.getAttribute(parameter); return value == null || Double.isNaN(value) || Double.isInfinite(value) ? 0 : value; } @Override protected Set<String> getParameters() { return attributes; } }
package com.elmakers.mine.bukkit.magic; import java.util.HashSet; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; public class MageParameters extends ParameterizedConfiguration { private static Set<String> attributes; private final @Nonnull Mage mage; public MageParameters(Mage mage, String context) { super(context); this.mage = mage; } public MageParameters(MageParameters copy) { super(copy); this.mage = copy.mage; } protected MageController getController() { return mage.getController(); } protected Mage getMage() { return mage; } public static void initializeAttributes(Set<String> attrs) { attributes = new HashSet<>(attrs); } @Override @Nullable protected Double evaluate(String expression) { if (mage.isPlayer()) { expression = getController().setPlaceholders(mage.getPlayer(), expression); } return super.evaluate(expression); } @Override protected double getParameter(String parameter) { Double value = mage.getAttribute(parameter); return value == null || Double.isNaN(value) || Double.isInfinite(value) ? 0 : value; } @Override protected Set<String> getParameters() { return attributes; } }
Write ID to DB test
<!DOCTYPE html> <html> <head><title>Response</title></head> <body> <h1>Response</h1> <?php require("secretSettings.php"); $raw = file_get_contents('php://input'); echo "Raw: " . $raw; $contents = split(":", $raw); $id = trim(str_replace("}", "", $contents[1])); echo " ID: " . $id; $file = fopen("logs/scannedID.txt","a+") or die("cant open/create file"); fwrite($file,$id."\n"); fclose($file); $time = date('Y-m-d h:i:s'); echo $time; try { $conn = new PDO("mysql:host=$SERVERNAME;dbname=$DBNAME", $USERNAME, $PASSWORD); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "\nConnected successfully\n"; $sql = "INSERT INTO attendance (badgeID,time) VALUES ($id,$time)"; $conn->exec($sql); echo "New record created successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> <h3>Cron job test</h3> </body> </html>
<!DOCTYPE html> <html> <head><title>Response</title></head> <body> <h1>Response</h1> <?php require("secretSettings.php"); $raw = file_get_contents('php://input'); echo "Raw: " . $raw; $contents = split(":", $raw); $id = trim(str_replace("}", "", $contents[1])); echo " ID: " . $id; $file = fopen("logs/scannedID.txt","a+") or die("cant open/create file"); fwrite($file,$id."\n"); fclose($file); try { $conn = new PDO("mysql:host=$SERVERNAME;dbname=$DBNAME", $USERNAME, $PASSWORD); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> <h3>Cron job test</h3> </body> </html>
Fix invalid reference to fileNameFromKey
var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0 var dont = 0; function check (key) { chrome.storage.sync.get(key, function (resp) { console.log('comparing to cloud', key, resp); if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key] && confirm('Overwrite "' + utils.fileNameFromKey(key) + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.')) { console.log('Overwriting', key); localStorage.setItem(key, resp[key]); updateFiles(); } else { console.log('add to obj', obj, key); obj[key] = localStorage[key]; } done++; if (done >= count) { chrome.storage.sync.set(obj, function () { console.log('updated cloud files with: ', obj, this, arguments); }) } }) } for (var y in window.localStorage) { console.log('checking', y); obj[y] = window.localStorage.getItem(y); if (y.indexOf(utils.getCacheFilePrefix()) !== 0) { continue; } count++; check(y); } }; } module.exports = StorageHandler;
var utils = require('./utils'); function StorageHandler (updateFiles) { this.sync = function () { if (typeof chrome === 'undefined' || !chrome || !chrome.storage || !chrome.storage.sync) { return; } var obj = {}; var done = false; var count = 0 var dont = 0; function check (key) { chrome.storage.sync.get(key, function (resp) { console.log('comparing to cloud', key, resp); if (typeof resp[key] !== 'undefined' && obj[key] !== resp[key] && confirm('Overwrite "' + fileNameFromKey(key) + '"? Click Ok to overwrite local file with file from cloud. Cancel will push your local file to the cloud.')) { console.log('Overwriting', key); localStorage.setItem(key, resp[key]); updateFiles(); } else { console.log('add to obj', obj, key); obj[key] = localStorage[key]; } done++; if (done >= count) { chrome.storage.sync.set(obj, function () { console.log('updated cloud files with: ', obj, this, arguments); }) } }) } for (var y in window.localStorage) { console.log('checking', y); obj[y] = window.localStorage.getItem(y); if (y.indexOf(utils.getCacheFilePrefix()) !== 0) { continue; } count++; check(y); } }; } module.exports = StorageHandler;
:wrench: Use cssnext instead of custom packages
const path = require('path') const webpack = require('webpack') module.exports = { module: { rules: [{ test: /\.less$/, use: [ 'style-loader', 'css-loader?importLoaders=1&sourceMap=true&modules=true', 'less-loader', ], }, { test: /\.(eot|woff|woff2|ttf)$/, use: { loader: 'file-loader', query: { name: 'static/media/[name].[ext]', }, }, }, { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&modules=true', { loader: require.resolve('postcss-loader'), options: { plugins: () => ([ require('postcss-import'), require('postcss-cssnext'), ]) } }, ] }], }, plugins: [ // Ignore locales for momentJS // see http://stackoverflow.com/questions/25384360 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ] }
const path = require('path') const webpack = require('webpack') module.exports = { module: { rules: [{ test: /\.less$/, use: [ 'style-loader', 'css-loader?importLoaders=1&sourceMap=true&modules=true', 'less-loader', ], }, { test: /\.(eot|woff|woff2|ttf)$/, use: { loader: 'file-loader', query: { name: 'static/media/[name].[ext]', }, }, }, { test: /\.css$/, use: [ 'style-loader', 'css-loader?importLoaders=1&sourceMap=true&modules=true', { loader: 'postcss-loader', options: { plugins: () => ([ require('postcss-import'), require('postcss-custom-properties'), require('postcss-color-function'), require('autoprefixer'), ]) } }, ] }], }, plugins: [ // Ignore locales for momentJS // see http://stackoverflow.com/questions/25384360 new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ] }
Make muting rerender properly when getting updates. If you have two browsers open for the same account, muting in one browser will now be reflected in the other browser. This got regressed when changing the approach from collapsing to hiding. The new code should be less brittle, as we encapsulate re-rendering in muting.rerender(). (imported from commit 4e65e265b64513d38f518770453b7436cb92b4ca)
var muting_ui = (function () { var exports = {}; function timestamp_ms() { return (new Date()).getTime(); } var last_topic_update = 0; exports.rerender = function () { current_msg_list.rerender_after_muting_changes(); if (current_msg_list !== home_msg_list) { home_msg_list.rerender_after_muting_changes(); } }; exports.persist_and_rerender = function () { // Optimistically rerender our new muting preferences. The back // end should eventually save it, and if it doesn't, it's a recoverable // error--the user can just mute the topic again, and the topic might // die down before the next reload anyway, making the muting moot. exports.rerender(); var data = { muted_topics: JSON.stringify(muting.get_muted_topics()) }; last_topic_update = timestamp_ms(); $.ajax({ type: 'POST', url: '/json/set_muted_topics', data: data, dataType: 'json' }); }; exports.handle_updates = function (muted_topics) { if (timestamp_ms() < last_topic_update + 1000) { // This topic update is either the one that we just rendered, or, // much less likely, it's coming from another device and would probably // be overwriting this device's preferences with stale data. return; } muting.set_muted_topics(muted_topics); exports.rerender(); }; return exports; }());
var muting_ui = (function () { var exports = {}; function timestamp_ms() { return (new Date()).getTime(); } var last_topic_update = 0; exports.persist_and_rerender = function () { // Optimistically rerender our new muting preferences. The back // end should eventually save it, and if it doesn't, it's a recoverable // error--the user can just mute the topic again, and the topic might // die down before the next reload anyway, making the muting moot. current_msg_list.rerender_after_muting_changes(); if (current_msg_list !== home_msg_list) { home_msg_list.rerender_after_muting_changes(); } var data = { muted_topics: JSON.stringify(muting.get_muted_topics()) }; last_topic_update = timestamp_ms(); $.ajax({ type: 'POST', url: '/json/set_muted_topics', data: data, dataType: 'json' }); }; exports.handle_updates = function (muted_topics) { if (timestamp_ms() < last_topic_update + 1000) { // This topic update is either the one that we just rendered, or, // much less likely, it's coming from another device and would probably // be overwriting this device's preferences with stale data. return; } muting.set_muted_topics(muted_topics); current_msg_list.rerender(); }; return exports; }());
Remove m2m fields from ctnr edit form
from django import forms from cyder.base.constants import LEVELS from cyder.base.mixins import UsabilityFormMixin from cyder.core.ctnr.models import Ctnr class CtnrForm(forms.ModelForm, UsabilityFormMixin): class Meta: model = Ctnr exclude = ('users', 'domains', 'ranges', 'workgroups') def filter_by_ctnr_all(self, ctnr): pass class CtnrUserForm(forms.Form): level = forms.ChoiceField(widget=forms.RadioSelect, label="Level*", choices=[item for item in LEVELS.items()]) class CtnrObjectForm(forms.Form): obj_type = forms.ChoiceField( widget=forms.RadioSelect, label='Type*', choices=( ('user', 'User'), ('domain', 'Domain'), ('range', 'Range'), ('workgroup', 'Workgroup'))) def __init__(self, *args, **kwargs): obj_perm = kwargs.pop('obj_perm', False) super(CtnrObjectForm, self).__init__(*args, **kwargs) if not obj_perm: self.fields['obj_type'].choices = (('user', 'User'),) obj = forms.CharField( widget=forms.TextInput(attrs={'id': 'object-searchbox'}), label='Search*')
from django import forms from cyder.base.constants import LEVELS from cyder.base.mixins import UsabilityFormMixin from cyder.core.ctnr.models import Ctnr class CtnrForm(forms.ModelForm, UsabilityFormMixin): class Meta: model = Ctnr exclude = ('users',) def filter_by_ctnr_all(self, ctnr): pass class CtnrUserForm(forms.Form): level = forms.ChoiceField(widget=forms.RadioSelect, label="Level*", choices=[item for item in LEVELS.items()]) class CtnrObjectForm(forms.Form): obj_type = forms.ChoiceField( widget=forms.RadioSelect, label='Type*', choices=( ('user', 'User'), ('domain', 'Domain'), ('range', 'Range'), ('workgroup', 'Workgroup'))) def __init__(self, *args, **kwargs): obj_perm = kwargs.pop('obj_perm', False) super(CtnrObjectForm, self).__init__(*args, **kwargs) if not obj_perm: self.fields['obj_type'].choices = (('user', 'User'),) obj = forms.CharField( widget=forms.TextInput(attrs={'id': 'object-searchbox'}), label='Search*')
Upgrade six 1.10 to 1.11
import sys from setuptools import setup, find_packages with open('VERSION') as version_fp: VERSION = version_fp.read().strip() if sys.version_info[:2] < (3, 4): django_version = '1.8' else: django_version = '1.9' setup( name='django-perms', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-perms', author='Matt Johnson', author_email='[email protected]', maintainer='Wyatt Baldwin', maintainer_email='[email protected]', description='Syntactic sugar for handling permission functions in views, templates, and code', packages=find_packages(), zip_safe=False, install_requires=[ 'six>=1.11.0', ], extras_require={ 'dev': [ 'coverage', 'django>={version},<{version}.999'.format(version=django_version), 'flake8', 'tox', ], }, classifiers=[ 'Framework :: Django', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
import sys from setuptools import setup, find_packages with open('VERSION') as version_fp: VERSION = version_fp.read().strip() if sys.version_info[:2] < (3, 4): django_version = '1.8' else: django_version = '1.9' setup( name='django-perms', version=VERSION, url='https://github.com/PSU-OIT-ARC/django-perms', author='Matt Johnson', author_email='[email protected]', maintainer='Wyatt Baldwin', maintainer_email='[email protected]', description='Syntactic sugar for handling permission functions in views, templates, and code', packages=find_packages(), zip_safe=False, install_requires=[ 'six>=1.10.0', ], extras_require={ 'dev': [ 'coverage', 'django>={version},<{version}.999'.format(version=django_version), 'flake8', 'tox', ], }, classifiers=[ 'Framework :: Django', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], )
Fix remove message object from greeting
import json from http_client import HttpClient from models.message import ReceivedMessage class Bot(): """ @brief Facebook messenger bot """ def __init__(self, token): self.api_token = token self.client = HttpClient(token) def send_message(self, message): response, error = self.client.submit_request( '/me/messages', 'POST', message.to_json()) if error is not None: print 'Error Encountered! Could not send message\n' print 'Message: %s' % error return response, error def set_welcome(self, message): greeting = { 'setting_type': 'greeting', 'greeting': { 'text': message } } data = json.dumps(greeting) response, error = self.client.submit_request( '/me/thread_settings', 'POST', data) return response, error def messages_for_request(self, request): """ Handle incoming requests from the webhook """ entries = request.json['entry'] messages = [] for entry in entries: message = {} for msg in entry['messaging']: if msg.get('message') and msg['message'].get('text'): messages.append(ReceivedMessage(msg)) return messages def message_from_reciept(receipt): """ Handle receipts """ raise NotImplementedError
from http_client import HttpClient from models.message import ReceivedMessage class Bot(): """ @brief Facebook messenger bot """ def __init__(self, token): self.api_token = token self.client = HttpClient(token) def send_message(self, message): response, error = self.client.submit_request( '/me/messages', 'POST', message.to_json()) if error is not None: print 'Error Encountered! Could not send message\n' print 'Message: %s' % error return response, error def set_welcome(self, message, completion): self.client.submit_request( '/me/thread_settings', 'POST', message.to_json()) def messages_for_request(self, request): """ Handle incoming requests from the webhook """ entries = request.json['entry'] messages = [] for entry in entries: message = {} for msg in entry['messaging']: if msg.get('message') and msg['message'].get('text'): messages.append(ReceivedMessage(msg)) return messages def message_from_reciept(receipt): """ Handle receipts """ raise NotImplementedError
Add a quick and dirty mute list.
package com.demigodsrpg.chitchat.command; import com.demigodsrpg.chitchat.Chitchat; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CCMuteCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player && sender.hasPermission("chitchat.mute")) { if (args.length > 0) { if (command.getName().equals("ccmute")) { if ("list".equalsIgnoreCase(args[0])) { sender.sendMessage(ChatColor.YELLOW + "// -- Currently Muted Players -- //"); for (String mutedName : Chitchat.getMuteSet()) { sender.sendMessage(ChatColor.YELLOW + " - " + mutedName); } return true; } Chitchat.getMuteSet().add(args[0]); sender.sendMessage(ChatColor.YELLOW + "Muted " + args[0]); } else { Chitchat.getMuteSet().remove(args[0]); sender.sendMessage(ChatColor.YELLOW + "Unmuted " + args[0]); } } else { return false; } } else { sender.sendMessage(ChatColor.RED + "You don't have permission to use that command."); } return true; } }
package com.demigodsrpg.chitchat.command; import com.demigodsrpg.chitchat.Chitchat; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class CCMuteCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player && sender.hasPermission("chitchat.mute")) { if (args.length > 0) { if (command.getName().equals("ccmute")) { Chitchat.getMuteSet().add(args[0]); sender.sendMessage(ChatColor.YELLOW + "Muted " + args[0]); } else { Chitchat.getMuteSet().remove(args[0]); sender.sendMessage(ChatColor.YELLOW + "Unmuted " + args[0]); } } else { return false; } } else { sender.sendMessage(ChatColor.RED + "You don't have permission to use that command."); } return true; } }
Fix wrong boolean binding in fx-root example
package de.saxsys.jfx.mvvmfx.fx_root_example; import de.saxsys.jfx.mvvm.api.ViewModel; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import java.util.concurrent.Callable; public class LabeledTextFieldViewModel implements ViewModel { private StringProperty labelText = new SimpleStringProperty("default"); private BooleanProperty buttonDisabled = new SimpleBooleanProperty(); private StringProperty inputText = new SimpleStringProperty(""); public LabeledTextFieldViewModel(){ buttonDisabled.bind(Bindings.createBooleanBinding(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final String text = inputText.get(); return text == null || text.isEmpty(); } }, inputText)); } public void changeLabel(){ labelText.set(inputText.get()); inputText.set(""); } public ReadOnlyStringProperty labelTextProperty(){ return labelText; } public ReadOnlyBooleanProperty buttonDisabledProperty(){ return buttonDisabled; } public StringProperty inputTextProperty(){ return inputText; } }
package de.saxsys.jfx.mvvmfx.fx_root_example; import de.saxsys.jfx.mvvm.api.ViewModel; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import java.util.concurrent.Callable; public class LabeledTextFieldViewModel implements ViewModel { private StringProperty labelText = new SimpleStringProperty("default"); private BooleanProperty buttonDisabled = new SimpleBooleanProperty(); private StringProperty inputText = new SimpleStringProperty(""); public LabeledTextFieldViewModel(){ buttonDisabled.bind(Bindings.createBooleanBinding(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final String text = inputText.get(); return text != null && text.isEmpty(); } }, inputText)); } public void changeLabel(){ labelText.set(inputText.get()); inputText.set(""); } public ReadOnlyStringProperty labelTextProperty(){ return labelText; } public ReadOnlyBooleanProperty buttonDisabledProperty(){ return buttonDisabled; } public StringProperty inputTextProperty(){ return inputText; } }
Use appropriate key if isMultiple is true
<?php namespace Nails\GeoCode\Settings; use Nails\GeoCode\Service\Driver; use Nails\Common\Helper\Form; use Nails\Common\Interfaces; use Nails\Common\Service\FormValidation; use Nails\Components\Setting; use Nails\GeoCode\Constants; use Nails\Factory; /** * Class General * * @package Nails\GeoCode\Settings */ class General implements Interfaces\Component\Settings { /** * @inheritDoc */ public function getLabel(): string { return 'Geo-IP'; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function getPermissions(): array { return []; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function get(): array { /** @var Driver $oDriverService */ $oDriverService = Factory::service('Driver', Constants::MODULE_SLUG); /** @var Setting $oDriver */ $oDriver = Factory::factory('ComponentSetting'); $oDriver ->setKey($oDriverService->isMultiple() ? $oDriverService->getSettingKey() . '[]' : $oDriverService->getSettingKey() ) ->setType($oDriverService->isMultiple() ? Form::FIELD_DROPDOWN_MULTIPLE : Form::FIELD_DROPDOWN ) ->setLabel('Driver') ->setFieldset('Driver') ->setClass('select2') ->setOptions(['' => 'No Driver Selected'] + $oDriverService->getAllFlat()) ->setValidation([ FormValidation::RULE_REQUIRED, ]); return [ $oDriver, ]; } }
<?php namespace Nails\GeoCode\Settings; use Nails\GeoCode\Service\Driver; use Nails\Common\Helper\Form; use Nails\Common\Interfaces; use Nails\Common\Service\FormValidation; use Nails\Components\Setting; use Nails\GeoCode\Constants; use Nails\Factory; /** * Class General * * @package Nails\GeoCode\Settings */ class General implements Interfaces\Component\Settings { /** * @inheritDoc */ public function getLabel(): string { return 'Geo-IP'; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function getPermissions(): array { return []; } // -------------------------------------------------------------------------- /** * @inheritDoc */ public function get(): array { /** @var Driver $oDriverService */ $oDriverService = Factory::service('Driver', Constants::MODULE_SLUG); /** @var Setting $oDriver */ $oDriver = Factory::factory('ComponentSetting'); $oDriver ->setKey($oDriverService->getSettingKey()) ->setType($oDriverService->isMultiple() ? Form::FIELD_DROPDOWN_MULTIPLE : Form::FIELD_DROPDOWN ) ->setLabel('Driver') ->setFieldset('Driver') ->setClass('select2') ->setOptions(['' => 'No Driver Selected'] + $oDriverService->getAllFlat()) ->setValidation([ FormValidation::RULE_REQUIRED, ]); return [ $oDriver, ]; } }
Remove no longer needed local variable.
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] return os.path.join(path, locale, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
import json import os from django.conf import settings from django.utils.translation import get_language from django.utils.translation import to_locale _JSON_MESSAGES_FILE_CACHE = {} def locale_data_file(locale): path = getattr(settings, 'LOCALE_PATHS')[0] locale_path = os.path.join(path, locale) return os.path.join(locale_path, "LC_FRONTEND_MESSAGES", "contentcuration-messages.json") def get_messages(): global _JSON_MESSAGES_FILE_CACHE locale = to_locale(get_language()) if locale not in _JSON_MESSAGES_FILE_CACHE: try: with open(locale_data_file(locale), 'rb') as data: message_json = json.load(data) translation_dict = {} for key, value in message_json.items(): namespace, key = key.split(".") translation_dict[namespace] = translation_dict.get(namespace) or {} translation_dict[namespace][key] = value _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps(translation_dict) except IOError: _JSON_MESSAGES_FILE_CACHE[locale] = json.dumps({}) return _JSON_MESSAGES_FILE_CACHE[locale]
Rewrite using WNafUtil.generateNaf instead of the inline Naf generation
package org.bouncycastle.math.ec; import java.math.BigInteger; /** * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm. */ public class FpNafMultiplier implements ECMultiplier { /** * D.3.2 pg 101 * @see org.bouncycastle.math.ec.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger) */ public ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) { if (k.signum() < 0) { throw new IllegalArgumentException("'k' cannot be negative"); } if (k.signum() == 0) { return p.getCurve().getInfinity(); } byte[] wnaf = WNafUtil.generateNaf(k); p = p.normalize(); ECPoint negP = p.negate(); ECPoint R = p.getCurve().getInfinity(); int i = wnaf.length; while (--i >= 0) { int wi = wnaf[i]; if (wi == 0) { R = R.twice(); } else { ECPoint r = wi > 0 ? p : negP; R = R.twicePlus(r); } } return R; } }
package org.bouncycastle.math.ec; import java.math.BigInteger; /** * Class implementing the NAF (Non-Adjacent Form) multiplication algorithm. */ public class FpNafMultiplier implements ECMultiplier { /** * D.3.2 pg 101 * @see org.bouncycastle.math.ec.ECMultiplier#multiply(org.bouncycastle.math.ec.ECPoint, java.math.BigInteger) */ public ECPoint multiply(ECPoint p, BigInteger k, PreCompInfo preCompInfo) { // TODO Probably should try to add this // BigInteger e = k.mod(n); // n == order of p BigInteger e = k; BigInteger h = e.shiftLeft(1).add(e); p = p.normalize(); ECPoint neg = p.negate(); ECPoint R = p; for (int i = h.bitLength() - 2; i > 0; --i) { boolean hBit = h.testBit(i); boolean eBit = e.testBit(i); if (hBit != eBit) { R = R.twicePlus(hBit ? p : neg); } else { R = R.twice(); } } return R; } }
Make short desc less fudful
#!/usr/bin/env python """ # sentry-restricted-github A limited alternavite to sentry-github which doesn't require write access to repos. It allows creating tickets but doesn't link them to the sentry error group. """ from setuptools import setup, find_packages # tests_require = [ # 'nose', # ] install_requires = [ 'sentry>=6.0.0', ] setup( name='sentry-restricted-github', version='0.1', author='Daniel Benamy', author_email='[email protected]', url='https://github.com/stripe/sentry-restricted-github', description='Create github tickets from sentry errors without giving sentry write access to the repo.', long_description=__doc__, license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), zip_safe=False, install_requires=install_requires, # tests_require=tests_require, # extras_require={'test': tests_require}, test_suite='runtests.runtests', include_package_data=True, entry_points={ 'sentry.apps': [ 'safe_github = sentry_safe_github', ], 'sentry.plugins': [ 'safe_github = sentry_safe_github.plugin:SafeGithubPlugin', ], }, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
#!/usr/bin/env python """ # sentry-restricted-github A limited alternavite to sentry-github which doesn't require write access to repos. It allows creating tickets but doesn't link them to the sentry error group. """ from setuptools import setup, find_packages # tests_require = [ # 'nose', # ] install_requires = [ 'sentry>=6.0.0', ] setup( name='sentry-restricted-github', version='0.1', author='Daniel Benamy', author_email='[email protected]', url='https://github.com/stripe/sentry-restricted-github', description='Create github tickets from sentry errors. More secure but less featureful than sentry-github.', long_description=__doc__, license='MIT', package_dir={'': 'src'}, packages=find_packages('src'), zip_safe=False, install_requires=install_requires, # tests_require=tests_require, # extras_require={'test': tests_require}, test_suite='runtests.runtests', include_package_data=True, entry_points={ 'sentry.apps': [ 'safe_github = sentry_safe_github', ], 'sentry.plugins': [ 'safe_github = sentry_safe_github.plugin:SafeGithubPlugin', ], }, classifiers=[ 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
Change default channel to test_bed
import httplib import urllib import json class Slack: def __init__(self, webhook_path, url='hooks.slack.com', channel='#test_bed', username="sb-bot", icon=":satellite:"): self.web_hook_url = url self.webhook_path = webhook_path self.channel = channel self.username = username self.icon = icon def send(self, message): if message: conn = httplib.HTTPSConnection(self.web_hook_url) payload = { "channel": self.channel, "username": self.username, "icon_emoji": self.icon, "text": message } conn.request( "POST", self.webhook_path, urllib.urlencode({ 'payload': json.dumps(payload) }), {"Content-type": "application/x-www-form-urlencoded"} ) return conn.getresponse() if __name__ == '__main__': slack = Slack("/services/T2GLAPJHM/B4H2LRVS9/7fSoJ9VIrY5v5E0TQvML5kgC") slack.send("Hi there, I'm a robot added by Jay!! Reporting from SigBridge.")
import httplib import urllib import json class Slack: def __init__(self, webhook_path, url='hooks.slack.com', channel='#sigbridge', username="sb-bot", icon=":satellite:"): self.web_hook_url = url self.webhook_path = webhook_path self.channel = channel self.username = username self.icon = icon def send(self, message): if message: conn = httplib.HTTPSConnection(self.web_hook_url) payload = { "channel": self.channel, "username": self.username, "icon_emoji": self.icon, "text": message } conn.request( "POST", self.webhook_path, urllib.urlencode({ 'payload': json.dumps(payload) }), {"Content-type": "application/x-www-form-urlencoded"} ) return conn.getresponse() if __name__ == '__main__': slack = Slack("/services/T2GLAPJHM/B4H2LRVS9/7fSoJ9VIrY5v5E0TQvML5kgC") slack.send("Hi there, I'm a robot added by Jay!! Reporting from SigBridge.")
Use `contenthash` instead of `hash` for webpack output.filename To suppress "DeprecationWarning: [hash] is now [fullhash] (also consider using [chunkhash] or [contenthash], see documentation for details)"
const glob = require('glob'); const path = require('path'); const webpack = require('webpack'); const WebpackAssetsManifest = require('webpack-assets-manifest'); const { NODE_ENV } = process.env; const isProd = NODE_ENV === 'production'; const entry = {}; for (const p of glob.sync(path.resolve(__dirname, 'app/javascript/packs/*.{js,ts}'))) { entry[path.basename(p, path.extname(p))] = p; } module.exports = { entry: entry, mode: isProd ? 'production' : 'development', output: { path: path.resolve(__dirname, 'public/packs'), publicPath: '/packs/', filename: isProd ? '[name]-[contenthash].js' : '[name].js', }, module: { rules: [ { test: /\.(js|ts)x?$/, loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, resolve: { extensions: ['.js', '.ts'], }, optimization: { splitChunks: { chunks: 'initial', name: 'vendor', }, }, plugins: [ new WebpackAssetsManifest({ publicPath: true, output: 'manifest.json', }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), ], devtool: 'source-map', };
const glob = require('glob'); const path = require('path'); const webpack = require('webpack'); const WebpackAssetsManifest = require('webpack-assets-manifest'); const { NODE_ENV } = process.env; const isProd = NODE_ENV === 'production'; const entry = {}; for (const p of glob.sync(path.resolve(__dirname, 'app/javascript/packs/*.{js,ts}'))) { entry[path.basename(p, path.extname(p))] = p; } module.exports = { entry: entry, mode: isProd ? 'production' : 'development', output: { path: path.resolve(__dirname, 'public/packs'), publicPath: '/packs/', filename: isProd ? '[name]-[hash].js' : '[name].js', }, module: { rules: [ { test: /\.(js|ts)x?$/, loader: 'ts-loader', options: { transpileOnly: true, }, }, ], }, resolve: { extensions: ['.js', '.ts'], }, optimization: { splitChunks: { chunks: 'initial', name: 'vendor', }, }, plugins: [ new WebpackAssetsManifest({ publicPath: true, output: 'manifest.json', }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', }), ], devtool: 'source-map', };
Add choices_map and units_map global variables
"""Routines used by WMT hooks for TopoFlow components.""" choices_map = { 'Yes': 1, 'No': 0 } units_map = { 'meters': 'm^2', 'kilometers': 'km^2' } def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
def get_dtype(parameter_value): """Get the TopoFlow data type of a parameter. Parameters ---------- parameter_value : object An object, a scalar. """ try: float(parameter_value) except ValueError: return 'string' else: return 'float' def assign_parameters(env, file_list): """Assign values for input parameters in a TopoFlow component. A subset of TopoFlow input parameters can take a scalar value, or, through an uploaded file, a time series, a grid, or a grid sequence. This function assigns such parameters a scalar value, or the name of a file, based on the user's selection in WMT. Parameters ---------- env : dict A dict of component parameter values from WMT. file_list : list A list of file names used by the component. """ terminator = '_ptype' for key in env.copy().iterkeys(): if key.endswith(terminator): key_root, sep, end = key.partition(terminator) if env[key] == 'Scalar': env[key_root] = env[key_root + '_scalar'] else: env[key_root] = env[key_root + '_file'] file_list.append(key_root) env[key_root + '_dtype'] = get_dtype(env[key_root])
Remove default anchor behavior for smooth scrolling.
// // suuoh.com // Melvin Chien 2013 // $(document).ready(function() { $("a[href^='#']").click(function(e){ e.preventDefault(); var id = $(this).attr("href"); var posTop = $(id).position().top; if ($(".hidden-phone").is(":visible")) posTop -= 50; $("html, body").animate({ scrollTop: posTop }, 1000); }); $("a[href^='http']").attr("target", "_blank"); $("a[class='tooltip-hover']").tooltip(); $("img.lazy").show().lazyload({ effect: "fadeIn" }); $("a[href$='.gif'],a[href$='.jpg'],a[href$='.png']").fancybox({ padding: 10, margin: 50, loop: false, helpers: { title: { type: "over" }, overlay: { showEarly: false, css: { "background" : "rgba(25, 25, 25, 0.80)" } } } }); $(".fancybox-media").fancybox({ padding: 10, margin: 50, loop: false, helpers: { media: {}, title: { type: "float" }, overlay: { showEarly: false, css: { "background" : "rgba(25, 25, 25, 0.80)" } } } }); });
// // suuoh.com // Melvin Chien 2013 // $(document).ready(function() { $("a[href^='#']").click(function(){ var id = $(this).attr("href"); var posTop = $(id).position().top; if ($(".hidden-phone").is(":visible")) posTop -= 50; $("html, body").animate({ scrollTop: posTop }, 1000); }); $("a[href^='http']").attr("target", "_blank"); $("a[class='tooltip-hover']").tooltip(); $("img.lazy").show().lazyload({ effect: "fadeIn" }); $("a[href$='.gif'],a[href$='.jpg'],a[href$='.png']").fancybox({ padding: 10, margin: 50, loop: false, helpers: { title: { type: "over" }, overlay: { showEarly: false, css: { "background" : "rgba(25, 25, 25, 0.80)" } } } }); $(".fancybox-media").fancybox({ padding: 10, margin: 50, loop: false, helpers: { media: {}, title: { type: "float" }, overlay: { showEarly: false, css: { "background" : "rgba(25, 25, 25, 0.80)" } } } }); });
Fix syntax error, unexpected 'insteadof'.
<?php namespace Per3evere\Preq; use Illuminate\Foundation\Application as LaravelApplication; use Laravel\Lumen\Application as LumenApplication; use Illuminate\Support\ServiceProvider; /** * Class PreqServiceProvider * */ class PreqServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the configuration * * @return void */ public function boot() { $source = realpath(__DIR__ . '/../config/preq.php'); if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('preq.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('preq'); } $this->mergeConfigFrom($source, 'preq'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('preq', function ($app) { $config = $app->make('config')->get('preq'); return new CommandFactory($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['preq']; } }
<?php namespace Per3evere\Preq; use Illuminate\Foundation\Application as LaravelApplication; use Laravel\Lumen\Application as LumenApplication; use Illuminate\Support\ServiceProvider; /** * Class PreqServiceProvider * */ class PreqServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the configuration * * @return void */ public function boot() { $source = realpath(__DIR__ . '/../config/preq.php'); if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('preq.php')]); } elseif ($this->app insteadof LumenApplication) { $this->app->configure('preq'); } $this->mergeConfigFrom($source, 'preq'); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('preq', function ($app) { $config = $app->make('config')->get('preq'); return new CommandFactory($config); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['preq']; } }
Update bundle configuration for Symfony 4.2 change
<?php namespace LongRunning\Bundle\LongRunningBundle\DependencyInjection; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class Configuration implements ConfigurationInterface { public function __construct($alias) { $this->alias = $alias; } public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder($this->alias); if (method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->getRootNode(); } else { // BC layer for symfony/config 4.1 and older $rootNode = $treeBuilder->root($this->alias); } $rootNode ->children() ->arrayNode('bernard') ->canBeEnabled() ->end() ->arrayNode('doctrine_orm') ->canBeEnabled() ->end() ->arrayNode('doctrine_dbal') ->canBeEnabled() ->end() ->arrayNode('monolog') ->canBeEnabled() ->end() ->arrayNode('swift_mailer') ->canBeEnabled() ->end() ->arrayNode('sentry') ->canBeEnabled() ->end() ->arrayNode('simple_bus_rabbit_mq') ->canBeEnabled() ->end() ->end(); return $treeBuilder; } }
<?php namespace LongRunning\Bundle\LongRunningBundle\DependencyInjection; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\Builder\TreeBuilder; class Configuration implements ConfigurationInterface { public function __construct($alias) { $this->alias = $alias; } public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root($this->alias); $rootNode ->children() ->arrayNode('bernard') ->canBeEnabled() ->end() ->arrayNode('doctrine_orm') ->canBeEnabled() ->end() ->arrayNode('doctrine_dbal') ->canBeEnabled() ->end() ->arrayNode('monolog') ->canBeEnabled() ->end() ->arrayNode('swift_mailer') ->canBeEnabled() ->end() ->arrayNode('sentry') ->canBeEnabled() ->end() ->arrayNode('simple_bus_rabbit_mq') ->canBeEnabled() ->end() ->end(); return $treeBuilder; } }
Fix TF using all the GPU memory
from ..kernel import Kernel from scannerpy import DeviceType class TensorFlowKernel(Kernel): def __init__(self, config): import tensorflow as tf # If this is a CPU kernel, tell TF that it should not use # any GPUs for its graph operations cpu_only = True visible_device_list = [] tf_config = tf.ConfigProto() for handle in config.devices: if handle.type == DeviceType.GPU.value: visible_device_list.append(str(handle.id)) tf_config.gpu_options.allow_growth = True cpu_only = False if cpu_only: tf_config.device_count['GPU'] = 0 else: tf_config.gpu_options.visible_device_list = ','.join(visible_device_list) # TODO: wrap this in "with device" self.config = config self.tf_config = tf_config self.graph = self.build_graph() self.sess = tf.Session(config=self.tf_config, graph=self.graph) self.sess.as_default() self.protobufs = config.protobufs def close(self): self.sess.close() def build_graph(self): raise NotImplementedError def execute(self): raise NotImplementedError
from ..kernel import Kernel from scannerpy import DeviceType class TensorFlowKernel(Kernel): def __init__(self, config): import tensorflow as tf # If this is a CPU kernel, tell TF that it should not use # any GPUs for its graph operations cpu_only = True visible_device_list = [] tf_config = tf.ConfigProto() for handle in config.devices: if handle.type == DeviceType.GPU.value: visible_device_list.append(str(handle.id)) cpu_only = False if cpu_only: tf_config.device_count['GPU'] = 0 else: tf_config.gpu_options.visible_device_list = ','.join(visible_device_list) # TODO: wrap this in "with device" self.config = config self.tf_config = tf_config self.graph = self.build_graph() self.sess = tf.Session(config=self.tf_config, graph=self.graph) self.sess.as_default() self.protobufs = config.protobufs def close(self): self.sess.close() def build_graph(self): raise NotImplementedError def execute(self): raise NotImplementedError
Set status 500 on React rendered errors.
'use strict'; var React = require('react'); var doctype = '<!DOCTYPE html>\n'; var transformResponse = require('subprocess-middleware').transformResponse; var render = function (Component, body, res) { //var start = process.hrtime(); var context = JSON.parse(body); var props = { context: context, href: res.getHeader('X-href') || context['@id'] }; var component, markup; try { component = Component(props); markup = React.renderComponentToString(component); } catch (err) { props.context = { '@type': ['RenderingError', 'error'], status: 'error', code: 500, title: 'Server Rendering Error', description: 'The server erred while rendering the page.', detail: err.stack, log: console._stdout.toString(), warn: console._stderr.toString(), context: context }; // To debug in browser, pause on caught exceptions: // app.setProps({context: app.props.context.context}) res.statusCode = 500; component = Component(props); markup = React.renderComponentToString(component); } res.setHeader('Content-Type', 'text/html; charset=utf-8'); //var duration = process.hrtime(start); //res.setHeader('X-React-duration', duration[0] * 1e6 + (duration[1] / 1000 | 0)); return new Buffer(doctype + markup); }; module.exports.build = function (Component) { return transformResponse(render.bind(null, Component)); };
'use strict'; var React = require('react'); var doctype = '<!DOCTYPE html>\n'; var transformResponse = require('subprocess-middleware').transformResponse; var render = function (Component, body, res) { //var start = process.hrtime(); var context = JSON.parse(body); var props = { context: context, href: res.getHeader('X-href') || context['@id'] }; var component, markup; try { component = Component(props); markup = React.renderComponentToString(component); } catch (err) { props.context = { '@type': ['RenderingError', 'error'], status: 'error', code: 500, title: 'Server Rendering Error', description: 'The server erred while rendering the page.', detail: err.stack, log: console._stdout.toString(), warn: console._stderr.toString(), context: context }; // To debug in browser, pause on caught exceptions: // app.setProps({context: app.props.context.context}) component = Component(props); markup = React.renderComponentToString(component); } res.setHeader('Content-Type', 'text/html; charset=utf-8'); //var duration = process.hrtime(start); //res.setHeader('X-React-duration', duration[0] * 1e6 + (duration[1] / 1000 | 0)); return new Buffer(doctype + markup); }; module.exports.build = function (Component) { return transformResponse(render.bind(null, Component)); };
Fix the versioned Django, we're grabbing 1.4.1 off the requirements.txt
#!/usr/bin/env python from setuptools import setup, find_packages from billy import __version__ long_description = open('README.rst').read() setup(name='billy', version=__version__, packages=find_packages(), package_data={'billy': ['schemas/*.json', 'schemas/api/*.json', 'schemas/relax/api.rnc'], 'billy.web.admin': ['templates/billy/*.html'], }, author="James Turk", author_email="[email protected]", license="GPL v3", url="http://github.com/sunlightlabs/billy/", description='scraping, storing, and sharing legislative information', long_description=long_description, platforms=['any'], entry_points=""" [console_scripts] billy-scrape = billy.bin.update:scrape_compat_main billy-update = billy.bin.update:main billy-util = billy.bin.util:main """, install_requires=[ "Django>=1.4", "argparse==1.1", "boto", "django-piston", "icalendar", "lxml>=2.2", "name_tools>=0.1.2", "nose", "pymongo>=2.2", "scrapelib>=0.7.0", "unicodecsv", "validictory>=0.7.1", "pyes", ] )
#!/usr/bin/env python from setuptools import setup, find_packages from billy import __version__ long_description = open('README.rst').read() setup(name='billy', version=__version__, packages=find_packages(), package_data={'billy': ['schemas/*.json', 'schemas/api/*.json', 'schemas/relax/api.rnc'], 'billy.web.admin': ['templates/billy/*.html'], }, author="James Turk", author_email="[email protected]", license="GPL v3", url="http://github.com/sunlightlabs/billy/", description='scraping, storing, and sharing legislative information', long_description=long_description, platforms=['any'], entry_points=""" [console_scripts] billy-scrape = billy.bin.update:scrape_compat_main billy-update = billy.bin.update:main billy-util = billy.bin.util:main """, install_requires=[ "Django==1.4", "argparse==1.1", "boto", "django-piston", "icalendar", "lxml>=2.2", "name_tools>=0.1.2", "nose", "pymongo>=2.2", "scrapelib>=0.7.0", "unicodecsv", "validictory>=0.7.1", "pyes", ] )
Change default arg value for pynuxrc
#!/usr/bin/env python # -*- coding: utf8 -*- import sys import argparse from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo def main(argv=None): parser = argparse.ArgumentParser( description='Print count of objects for a given collection.') parser.add_argument('path', help="Nuxeo path to collection") parser.add_argument( '--pynuxrc', default='~/.pynuxrc', help="rcfile for use with pynux utils") parser.add_argument( '--components', action='store_true', help="show counts for object components") if argv is None: argv = parser.parse_args() dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc) print "about to fetch objects for path {}".format(dh.path) objects = dh.fetch_objects() object_count = len(objects) print "finished fetching objects. {} found".format(object_count) uid_set = set() for obj in objects: uid_set.add(obj['uid']) unique = len(uid_set) print "unique uid count: {}".format(unique) if not argv.components: return print "about to iterate through objects and get components" component_count = 0 for obj in objects: components = dh.fetch_components(obj) component_count = component_count + len(components) print "finished fetching components. {} found".format(component_count) print "Grand Total: {}".format(object_count + component_count) if __name__ == "__main__": sys.exit(main())
#!/usr/bin/env python # -*- coding: utf8 -*- import sys import argparse from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo def main(argv=None): parser = argparse.ArgumentParser( description='Print count of objects for a given collection.') parser.add_argument('path', help="Nuxeo path to collection") parser.add_argument( '--pynuxrc', default='~/.pynuxrc-prod', help="rcfile for use with pynux utils") parser.add_argument( '--components', action='store_true', help="show counts for object components") if argv is None: argv = parser.parse_args() dh = DeepHarvestNuxeo(argv.path, '', pynuxrc=argv.pynuxrc) print "about to fetch objects for path {}".format(dh.path) objects = dh.fetch_objects() object_count = len(objects) print "finished fetching objects. {} found".format(object_count) if not argv.components: return print "about to iterate through objects and get components" component_count = 0 for obj in objects: components = dh.fetch_components(obj) component_count = component_count + len(components) print "finished fetching components. {} found".format(component_count) print "Grand Total: {}".format(object_count + component_count) if __name__ == "__main__": sys.exit(main())
Move client and resource to __init__ * moved the calls to create the ec2 session resource session client to the init
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): ec2_resource = self.connection.resource("ec2") server = ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): ec2_client = self.connection.client("ec2") desc = ec2_client.describe_instances() return desc def delete_server(self, instance_id): ec2_resource = self.connection.resource("ec2") ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
Use StringUtils for the default string
package org.wikipedia.gallery; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.Collections; import java.util.List; @SuppressWarnings("unused") public class MediaListItem implements Serializable { @Nullable private String title; @SerializedName("section_id") private int sectionId; @Nullable private String type; @Nullable private TextInfo caption; private boolean showInGallery; @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets; public MediaListItem() { } public MediaListItem(@NonNull String title) { this.title = title; } @NonNull public String getType() { return StringUtils.defaultString(type); } @Nullable public TextInfo getCaption() { return caption; } public boolean showInGallery() { return showInGallery; } @NonNull public String getTitle() { return StringUtils.defaultString(title); } @NonNull public List<ImageSrcSet> getSrcSets() { return srcSets != null ? srcSets : Collections.emptyList(); } public class ImageSrcSet implements Serializable { @Nullable private String src; @Nullable private String scale; @NonNull public String getSrc() { return StringUtils.defaultString(src); } @NonNull public String getScale() { return StringUtils.defaultString(scale); } } }
package org.wikipedia.gallery; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.Collections; import java.util.List; @SuppressWarnings("unused") public class MediaListItem implements Serializable { @Nullable private String title; @SerializedName("section_id") private int sectionId; @Nullable private String type; @Nullable private TextInfo caption; private boolean showInGallery; @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets; public MediaListItem() { } public MediaListItem(@NonNull String title) { this.title = title; } @NonNull public String getType() { return StringUtils.defaultString(type); } @Nullable public TextInfo getCaption() { return caption; } public boolean showInGallery() { return showInGallery; } @NonNull public String getTitle() { return StringUtils.defaultString(title); } @NonNull public List<ImageSrcSet> getSrcSets() { return srcSets != null ? srcSets : Collections.emptyList(); } public class ImageSrcSet implements Serializable { @Nullable private String src; @Nullable private String scale; @Nullable public String getSrc() { return src; } @Nullable public String getScale() { return scale; } } }
Use single dist js file
const webpack = require('webpack'), HtmlWebpackPlugin = require('html-webpack-plugin'), path = require('path'), babelCfg = require("./babel.config"), paths = { root: path.join(__dirname, '../'), app: path.join(__dirname, '../app/'), dist: path.join(__dirname, '../dist/') }; module.exports = { resolve: { alias: { cx: paths.root + 'node_modules/cx-core/src/', app: paths.app //uncomment the line below to alias cx-react to cx-preact or some other React replacement library //'cx-react': 'cx-preact', } }, module: { loaders: [{ test: /\.js$/, //add here any ES6 based library include: /(app|intl-io|cx-core|cx|redux|redux-thunk|lodash)/, loader: 'babel', query: babelCfg }] }, entry: { //vendor: ['cx-react'], app: paths.app + 'index.js' }, output: { path: paths.dist, filename: "[name].js" }, plugins: [ // new webpack.optimize.CommonsChunkPlugin({ // names: ["vendor"], // minChunks: Infinity // }), new HtmlWebpackPlugin({ template: paths.app + 'index.html', hash: true }) ] };
const webpack = require('webpack'), HtmlWebpackPlugin = require('html-webpack-plugin'), path = require('path'), babelCfg = require("./babel.config"), paths = { root: path.join(__dirname, '../'), app: path.join(__dirname, '../app/'), dist: path.join(__dirname, '../dist/') }; module.exports = { resolve: { alias: { cx: paths.root + 'node_modules/cx-core/src/', app: paths.app //uncomment the line below to alias cx-react to cx-preact or some other React replacement library //'cx-react': 'cx-preact', } }, module: { loaders: [{ test: /\.js$/, //add here any ES6 based library include: /(app|intl-io|cx-core|cx|redux|redux-thunk|lodash)/, loader: 'babel', query: babelCfg }] }, entry: { vendor: ['cx-react'], app: paths.app + 'index.js' }, output: { path: paths.dist, filename: "[name].js" }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: ["vendor"], minChunks: Infinity }), new HtmlWebpackPlugin({ template: paths.app + 'index.html', hash: true }) ] };
Add more info to test_ais docstring
""" Test dbm_metrics script """ from pylearn2.scripts.dbm import dbm_metrics from pylearn2.datasets.mnist import MNIST def test_ais(): """ Test ais computation by comparing the output of estimate_likelihood to Russ's code's output for the same parameters. """ w_list = [None] b_list = [] # Add parameters import trainset = MNIST(which_set='train') testset = MNIST(which_set='test') train_ll, test_ll, log_z = dbm_metrics.estimate_likelihood(w_list, b_list, trainset, testset, pos_mf_steps=5) # Add log_z, test_ll import russ_log_z = 100. russ_train_ll = -100. russ_test_ll = -100. assert log_z == russ_log_z assert train_ll == russ_train_ll assert test_ll == russ_test_ll
""" Test dbm_metrics script """ from pylearn2.scripts.dbm import dbm_metrics from pylearn2.datasets.mnist import MNIST def test_ais(): """ Test ais computation """ w_list = [None] b_list = [] # Add parameters import trainset = MNIST(which_set='train') testset = MNIST(which_set='test') train_ll, test_ll, log_z = dbm_metrics.estimate_likelihood(w_list, b_list, trainset, testset, pos_mf_steps=5) # Add log_z, test_ll import russ_log_z = 100. russ_train_ll = -100. russ_test_ll = -100. assert log_z == russ_log_z assert train_ll == russ_train_ll assert test_ll == russ_test_ll
Remove showshildren as field from CMS
<?php class GroupedProduct extends Product { /** * @config */ private static $description = "A product containing other products"; private static $has_many = array( "ChildProducts" => "Product" ); public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab( "Root.Children", $grid = GridField::create( "Products", null, $this->ChildProducts() ) ); $config = GridfieldConfig_RelationEditor::create(); $grid->setConfig($config); $config ->getComponentByType("GridFieldDataColumns") ->setDisplayFields(array( "CMSThumbnail" => "Thumbnail", "ClassName" => "Product", "Title" => "Title", "StockID" => "StockID", "Price" => "Price", "Disabled" => "Disabled" )); return $fields; } public function onBeforeWrite() { parent::onBeforeWrite(); // Loop through our children and save (incase we need to set prices) foreach($this->ChildProducts() as $product) { $write = false; if(!$product->BasePrice && $this->BasePrice) { $product->BasePrice = $this->BasePrice; $write = true; } if($this->isChanged("BasePrice")) { $product->BasePrice = $this->BasePrice; $write = true; } if($write) $product->write(); } } }
<?php class GroupedProduct extends Product { /** * @config */ private static $description = "A product containing other products"; private static $has_many = array( "ChildProducts" => "Product" ); public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab( "Root.Settings", $grid = DropdownField::create( "ShowChildrenAs", null, $this->dbobject("ShowChildrenAs")->enumValues() ) ); $fields->addFieldToTab( "Root.Children", $grid = GridField::create( "Products", null, $this->ChildProducts() ) ); $config = GridfieldConfig_RelationEditor::create(); $grid->setConfig($config); $config ->getComponentByType("GridFieldDataColumns") ->setDisplayFields(array( "CMSThumbnail" => "Thumbnail", "ClassName" => "Product", "Title" => "Title", "StockID" => "StockID", "Price" => "Price", "Disabled" => "Disabled" )); return $fields; } public function onBeforeWrite() { parent::onBeforeWrite(); // Loop through our children and save (incase we need to set prices) foreach($this->ChildProducts() as $product) { $write = false; if(!$product->BasePrice && $this->BasePrice) { $product->BasePrice = $this->BasePrice; $write = true; } if($this->isChanged("BasePrice")) { $product->BasePrice = $this->BasePrice; $write = true; } if($write) $product->write(); } } }
Fix keys implementation - Object.keys does not work on functions
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
if (typeof buster == "undefined") { var buster = {}; } buster.util = (function () { var toString = Object.prototype.toString; var div = typeof document != "undefined" && document.createElement("div"); return { isNode: function (obj) { if (!div) { return false; } try { div.appendChild(obj); div.removeChild(obj); } catch (e) { return false; } return true; }, isElement: function (obj) { return obj && this.isNode(obj) && obj.nodeType === 1; }, isArguments: function (obj) { if (typeof obj != "object" || typeof obj.length != "number" || toString.call(obj) == "[object Array]") { return false; } if (typeof obj.callee == "function") { return true; } try { obj[obj.length] = 6; delete obj[obj.length]; } catch (e) { return true; } return false; }, keys: Object.keys || function (object) { var keys = []; for (var prop in object) { if (Object.prototype.hasOwnProperty.call(object, prop)) { keys.push(prop); } } return keys; } }; }()); if (typeof module != "undefined") { module.exports = buster.util; }
Simplify creation of MetaData in SQLBackend Squash a few lines into one.
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels'): meta = MetaData(bind=create_engine(url)) self.table = Table(table_name, meta, Column('id', types.Integer, primary_key=True), Column('key', types.CHAR(32), nullable=False, unique=True), Column('data', types.LargeBinary, nullable=False)) self.table.create(checkfirst=True) def __setitem__(self, key, value): raw = self.serialize(value) # Check if this key exists with a SELECT FOR UPDATE, to protect # against a race with other concurrent writers of this key. r = self.table.select('1', for_update=True).\ where(self.table.c.key == key).execute().fetchone() if r: # If it exists, use an UPDATE. self.table.update().values(data=raw).\ where(self.table.c.key == key).execute() else: # Otherwise INSERT. self.table.insert().values(key=key, data=raw).execute() def __getitem__(self, key): r = select([self.table.c.data], self.table.c.key == key).\ execute().fetchone() if r: raw = r[0] return self.deserialize(raw) else: raise KeyError('key %r not found' % key)
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels'): engine = create_engine(url) meta = MetaData() meta.bind = engine self.table = Table(table_name, meta, Column('id', types.Integer, primary_key=True), Column('key', types.CHAR(32), nullable=False, unique=True), Column('data', types.LargeBinary, nullable=False)) self.table.create(checkfirst=True) def __setitem__(self, key, value): raw = self.serialize(value) # Check if this key exists with a SELECT FOR UPDATE, to protect # against a race with other concurrent writers of this key. r = self.table.select('1', for_update=True).\ where(self.table.c.key == key).execute().fetchone() if r: # If it exists, use an UPDATE. self.table.update().values(data=raw).\ where(self.table.c.key == key).execute() else: # Otherwise INSERT. self.table.insert().values(key=key, data=raw).execute() def __getitem__(self, key): r = select([self.table.c.data], self.table.c.key == key).\ execute().fetchone() if r: raw = r[0] return self.deserialize(raw) else: raise KeyError('key %r not found' % key)
Include data in an array in Promotion archive method
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\EntityRepository; /** * PromotionRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PromotionRepository extends EntityRepository { /** * Create a json of a promotion. * * @param int $promotion id of the promotion to convert to a json. * @return string JSON that contain the element of a promotion. */ public function toJson($promotion) { $jsonDate = array(); $qb = $this->createQueryBuilder('p'); $qb->where('p.id = :id') ->setParameter('id', $promotion) ->andWhere('p.archive IS NULL') ->setMaxResults(1); $promotion = $qb->getQuery() ->getSingleResult(); $jsonData[] = array( 'promotion' => $promotion->__toString(), 'formation' => $promotion->getFormation()->__toString(), 'start' => $promotion->getStartDate()->format('Y-m-d H:i:s'), 'end' => $promotion->getEndDate()->format('Y-m-d H:i:s') ); return json_encode($jsonData); } }
<?php namespace Project\AppBundle\Entity; use Doctrine\ORM\EntityRepository; /** * PromotionRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PromotionRepository extends EntityRepository { /** * Create a json of a promotion. * * @param int $promotion id of the promotion to convert to a json. * @return string JSON that contain the element of a promotion. */ public function toJson($promotion) { $qb = $this->createQueryBuilder('p'); $qb->where('p.id = :id') ->setParameter('id', $promotion) ->andWhere('p.archive IS NULL') ->setMaxResults(1); $promotion = $qb->getQuery() ->getSingleResult(); $jsonData = array( 'promotion' => $promotion->__toString(), 'formation' => $promotion->getFormation()->__toString(), 'start' => $promotion->getStartDate()->format('Y-m-d H:i:s'), 'end' => $promotion->getEndDate()->format('Y-m-d H:i:s') ); return json_encode($jsonData); } }
Change "Development Status" classifier to "5 - Production/Stable"
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='1.1', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(exclude=['tests']), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='1.1', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(exclude=['tests']), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
Add decorator for GDB connect test failing on FreeBSD llvm.org/pr18313 git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@197910 91177308-0d34-0410-b5e6-96231b3b80d8
""" Test lldb 'process connect' command. """ import os import unittest2 import lldb import pexpect from lldbtest import * class ConnectRemoteTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @expectedFailureFreeBSD('llvm.org/pr18313') def test_connect_remote(self): """Test "process connect connect:://localhost:12345".""" # First, we'll start a fake debugserver (a simple echo server). fakeserver = pexpect.spawn('./EchoServer.py') # Turn on logging for what the child sends back. if self.TraceOn(): fakeserver.logfile_read = sys.stdout # Schedule the fake debugserver to be shutting down during teardown. def shutdown_fakeserver(): fakeserver.close() self.addTearDownHook(shutdown_fakeserver) # Wait until we receive the server ready message before continuing. fakeserver.expect_exact('Listening on localhost:12345') # Connect to the fake server.... if sys.platform.startswith('freebsd') or sys.platform.startswith("linux"): self.runCmd("process connect -p gdb-remote connect://localhost:12345") else: self.runCmd("process connect connect://localhost:12345") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
""" Test lldb 'process connect' command. """ import os import unittest2 import lldb import pexpect from lldbtest import * class ConnectRemoteTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def test_connect_remote(self): """Test "process connect connect:://localhost:12345".""" # First, we'll start a fake debugserver (a simple echo server). fakeserver = pexpect.spawn('./EchoServer.py') # Turn on logging for what the child sends back. if self.TraceOn(): fakeserver.logfile_read = sys.stdout # Schedule the fake debugserver to be shutting down during teardown. def shutdown_fakeserver(): fakeserver.close() self.addTearDownHook(shutdown_fakeserver) # Wait until we receive the server ready message before continuing. fakeserver.expect_exact('Listening on localhost:12345') # Connect to the fake server.... if sys.platform.startswith('freebsd') or sys.platform.startswith("linux"): self.runCmd("process connect -p gdb-remote connect://localhost:12345") else: self.runCmd("process connect connect://localhost:12345") if __name__ == '__main__': import atexit lldb.SBDebugger.Initialize() atexit.register(lambda: lldb.SBDebugger.Terminate()) unittest2.main()
Update minimum babel version to >=2.3. Babel 1.0 is now 3 years obsolete. Numerous critical bug fixes are included in the 1.0 - 2.3 range.
""" Flask-Babel ----------- Adds i18n/l10n support to Flask applications with the help of the `Babel`_ library. Links ````` * `documentation <http://packages.python.org/Flask-Babel>`_ * `development version <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_ .. _Babel: http://babel.edgewall.org/ """ from setuptools import setup setup( name='Flask-Babel', version='0.9', url='http://github.com/mitsuhiko/flask-babel', license='BSD', author='Armin Ronacher', author_email='[email protected]', description='Adds i18n/l10n support to Flask applications', long_description=__doc__, packages=['flask_babel'], zip_safe=False, platforms='any', install_requires=[ 'Flask', 'Babel>=2.3', 'speaklater>=1.2', 'Jinja2>=2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-Babel ----------- Adds i18n/l10n support to Flask applications with the help of the `Babel`_ library. Links ````` * `documentation <http://packages.python.org/Flask-Babel>`_ * `development version <http://github.com/mitsuhiko/flask-babel/zipball/master#egg=Flask-Babel-dev>`_ .. _Babel: http://babel.edgewall.org/ """ from setuptools import setup setup( name='Flask-Babel', version='0.9', url='http://github.com/mitsuhiko/flask-babel', license='BSD', author='Armin Ronacher', author_email='[email protected]', description='Adds i18n/l10n support to Flask applications', long_description=__doc__, packages=['flask_babel'], zip_safe=False, platforms='any', install_requires=[ 'Flask', 'Babel>=1.0', 'speaklater>=1.2', 'Jinja2>=2.5' ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Include agents as a default test family
#!/usr/bin/python # -*- coding: utf-8 -*- # For better print formatting from __future__ import print_function # Imports import os ############################################ # CONSTANTS ############################################ DEFAULT_SKIP = True DEFAULT_NUM_RETRIES = 3 DEFAULT_FAIL_FAST = False DEFAULT_FAMILIES = [ "agents", "autoparallel", "c", "cloud", "java", "performance", "pscos", "python", "tools", "fault_tolerance"] DEFAULT_TESTS = [] DEFAULT_CFG_FILE = "NIO.cfg" DEFAULT_CFG_EXTENSION = ".cfg" DEFAULT_COMPSS_HOME = "/opt/COMPSs/" DEFAULT_COMM = "es.bsc.compss.nio.master.NIOAdaptor" DEFAULT_EXECUTION_ENVS = ["python2", "python3", "python2_mpi", "python3_mpi"] SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) TESTS_DIR = os.path.join(SCRIPT_DIR, "../sources") CONFIGURATIONS_DIR = os.path.join(SCRIPT_DIR, "../configurations") RUNCOMPSS_REL_PATH = "Runtime/scripts/user/runcompss" CLEAN_PROCS_REL_PATH = "Runtime/scripts/utils/compss_clean_procs"
#!/usr/bin/python # -*- coding: utf-8 -*- # For better print formatting from __future__ import print_function # Imports import os ############################################ # CONSTANTS ############################################ DEFAULT_SKIP = True DEFAULT_NUM_RETRIES = 3 DEFAULT_FAIL_FAST = False DEFAULT_FAMILIES = ["autoparallel", "c", "cloud", "java", "performance", "pscos", "python", "tools", "fault_tolerance"] DEFAULT_TESTS = [] DEFAULT_CFG_FILE = "NIO.cfg" DEFAULT_CFG_EXTENSION = ".cfg" DEFAULT_COMPSS_HOME = "/opt/COMPSs/" DEFAULT_COMM = "es.bsc.compss.nio.master.NIOAdaptor" DEFAULT_EXECUTION_ENVS = ["python2", "python3", "python2_mpi", "python3_mpi"] SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) TESTS_DIR = os.path.join(SCRIPT_DIR, "../sources") CONFIGURATIONS_DIR = os.path.join(SCRIPT_DIR, "../configurations") RUNCOMPSS_REL_PATH = "Runtime/scripts/user/runcompss" CLEAN_PROCS_REL_PATH = "Runtime/scripts/utils/compss_clean_procs"
Add introspection rule; prevent South weirdness
from django.db.models import CharField, NOT_PROVIDED from django.core.exceptions import ValidationError from south.modelsinspector import add_introspection_rules from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value add_introspection_rules([ ( [MacAddrField], # model [], # args {'dhcp_enabled': ('dhcp_enabled', {})}, # kwargs ) ], [r'^cyder\.core\.fields\.MacAddrField'])
from django.db.models import CharField from django.core.exceptions import ValidationError from cyder.cydhcp.validation import validate_mac class MacAddrField(CharField): """A general purpose MAC address field This field holds a MAC address. clean() removes colons and hyphens from the field value, raising an exception if the value is invalid or empty. Arguments: dhcp_enabled (string): The name of another attribute (possibly a field) in the model that holds a boolean specifying whether to validate this MacAddrField; if not specified, always validate. """ def __init__(self, *args, **kwargs): if 'dhcp_enabled' in kwargs: self.dhcp_enabled = kwargs.pop('dhcp_enabled') else: self.dhcp_enabled = None # always validate for option in ['max_length', 'blank']: if option in kwargs: raise Exception('You cannot specify the {0} option.' .format(option)) kwargs['max_length'] = 12 kwargs['blank'] = True super(MacAddrField, self).__init__(*args, **kwargs) def clean(self, value, model_instance): # [ always validate ] [ DHCP is enabled ] if not self.dhcp_enabled or getattr(model_instance, self.dhcp_enabled): if value == '': raise ValidationError( "This field is required when DHCP is enabled") value = value.lower().replace(':', '') validate_mac(value) value = super(CharField, self).clean(value, model_instance) return value
Add helper methods for creating args
package fi.helsinki.cs.tmc.cli.command; import static org.junit.Assert.assertTrue; import fi.helsinki.cs.tmc.cli.Application; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; public class LoginCommandTest { private static String serverAddress; private static String username; private static String password; private Application app; private OutputStream os; public LoginCommandTest() { } @BeforeClass public static void setUpClass() { LoginCommandTest.serverAddress = System.getenv("TMC_SERVER_ADDRESS"); LoginCommandTest.username = System.getenv("TMC_USERNAME"); LoginCommandTest.password = System.getenv("TMC_PASSWORD"); } @Before public void setUp() { this.app = new Application(); this.os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); System.setOut(ps); } @Test public void logsInWithCorrectServerUserAndPassword() { String[] args = createArgs( LoginCommandTest.serverAddress, LoginCommandTest.username, LoginCommandTest.password); app.run(args); String output = os.toString(); assertTrue(output.contains("Login successful!")); } private String[] createArgs(String server, String username, String pwd) { return new String[]{ "login", "-s", server, "-u", username, "-p", pwd}; } private String[] createArgs(String username, String pwd) { return new String[]{ "login", "-s", LoginCommandTest.serverAddress, "-u", username, "-p", pwd}; } }
package fi.helsinki.cs.tmc.cli.command; import static org.junit.Assert.assertTrue; import fi.helsinki.cs.tmc.cli.Application; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.PrintStream; public class LoginCommandTest { private static String serverAddress; private static String username; private static String password; private Application app; private OutputStream os; public LoginCommandTest() { } @BeforeClass public static void setUpClass() { LoginCommandTest.serverAddress = System.getenv("TMC_SERVER_ADDRESS"); LoginCommandTest.username = System.getenv("TMC_USERNAME"); LoginCommandTest.password = System.getenv("TMC_PASSWORD"); } @Before public void setUp() { this.app = new Application(); this.os = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(os); System.setOut(ps); } @Test public void logsInWithCorrectServerUserAndPassword() { String[] args = {"login", "-s", LoginCommandTest.serverAddress, "-u", LoginCommandTest.username, "-p", LoginCommandTest.password}; app.run(args); String output = os.toString(); assertTrue(output.contains("Login successful!")); } }
Return empty list instead of null in mock
package com.llnw.storage.client; import com.google.common.collect.Lists; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { public MockEndpointFactory() { super(null, null, null); } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return Lists.newArrayList(); } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
package com.llnw.storage.client; import com.llnw.storage.client.io.ActivityCallback; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.util.List; public class MockEndpointFactory extends EndpointFactory { public MockEndpointFactory() { super(null, null, null); } @Override public Endpoint create(boolean useFTP) { return new Endpoint() { @Override public void deleteDirectory(String path) throws IOException { } @Override public void deleteFile(String path) throws IOException { } @Override public void close() { } @Override public void makeDirectory(String path) throws IOException { } @Override public List<String> listFiles(String path) throws IOException { return null; } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { } @Override public void noop() throws IOException { } @Override public boolean exists(String path) throws IOException { return false; } }; } }
Check if `this.providerParams` is defined
// Load modules var Crypto = require('crypto'); // Declare internals var internals = {}; exports = module.exports = function (options) { return { protocol: 'oauth2', auth: 'https://www.linkedin.com/uas/oauth2/authorization', token: 'https://www.linkedin.com/uas/oauth2/accessToken', scope: ['r_fullprofile', 'r_emailaddress', 'r_contactinfo'], scopeSeparator: ',', profile: function (credentials, params, get, callback) { var query = { format: 'json', appsecret_proof: Crypto.createHmac('sha256', this.clientSecret).update(credentials.token).digest('hex') }; var fields = ''; if (this.providerParams && this.providerParams.fields) { fields = this.providerParams.fields; } get('https://api.linkedin.com/v1/people/~' + fields, query, function (profile) { credentials.profile = { id: profile.id, name: { first: profile.firstName, last: profile.lastName }, email: profile.email, headline: profile.headline, raw: profile }; return callback(); }); } }; };
// Load modules var Crypto = require('crypto'); // Declare internals var internals = {}; exports = module.exports = function (options) { return { protocol: 'oauth2', auth: 'https://www.linkedin.com/uas/oauth2/authorization', token: 'https://www.linkedin.com/uas/oauth2/accessToken', scope: ['r_fullprofile', 'r_emailaddress', 'r_contactinfo'], scopeSeparator: ',', profile: function (credentials, params, get, callback) { var query = { format: 'json', appsecret_proof: Crypto.createHmac('sha256', this.clientSecret).update(credentials.token).digest('hex') }; var fields = ''; if (this.providerParams.fields) { fields = this.providerParams.fields; } get('https://api.linkedin.com/v1/people/~' + fields, query, function (profile) { credentials.profile = { id: profile.id, name: { first: profile.firstName, last: profile.lastName }, email: profile.email, headline: profile.headline, raw: profile }; return callback(); }); } }; };
Fix build. Change CommandMetadata import.
package io.bootique.undertow.command; import com.google.inject.Inject; import com.google.inject.Provider; import io.bootique.cli.Cli; import io.bootique.command.CommandOutcome; import io.bootique.command.CommandWithMetadata; import io.bootique.meta.application.CommandMetadata; import io.bootique.undertow.UndertowServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command for running Undertow server. * * @since 0.1 */ public class ServerCommand extends CommandWithMetadata { private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class); private final Provider<UndertowServer> serverProvider; @Inject public ServerCommand(Provider<UndertowServer> serverProvider) { super(createMetadata()); this.serverProvider = serverProvider; } @Override public CommandOutcome run(Cli cli) { LOGGER.info("Will run Undertow Server..."); UndertowServer server = serverProvider.get(); try { server.start(); } catch (Exception e) { return CommandOutcome.failed(1, e); } try { Thread.currentThread().join(); } catch (InterruptedException ie) { try { server.stop(); } catch (Exception se) { return CommandOutcome.failed(1, se); } } return CommandOutcome.succeeded(); } private static CommandMetadata createMetadata() { return CommandMetadata .builder(ServerCommand.class) .description("Starts Undertow server.") .build(); } }
package io.bootique.undertow.command; import com.google.inject.Inject; import com.google.inject.Provider; import io.bootique.application.CommandMetadata; import io.bootique.cli.Cli; import io.bootique.command.CommandOutcome; import io.bootique.command.CommandWithMetadata; import io.bootique.undertow.UndertowServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command for running Undertow server. * * @since 0.1 */ public class ServerCommand extends CommandWithMetadata { private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class); private final Provider<UndertowServer> serverProvider; @Inject public ServerCommand(Provider<UndertowServer> serverProvider) { super(createMetadata()); this.serverProvider = serverProvider; } @Override public CommandOutcome run(Cli cli) { LOGGER.info("Will run Undertow Server..."); UndertowServer server = serverProvider.get(); try { server.start(); } catch (Exception e) { return CommandOutcome.failed(1, e); } try { Thread.currentThread().join(); } catch (InterruptedException ie) { try { server.stop(); } catch (Exception se) { return CommandOutcome.failed(1, se); } } return CommandOutcome.succeeded(); } private static CommandMetadata createMetadata() { return CommandMetadata .builder(ServerCommand.class) .description("Starts Undertow server.") .build(); } }
Use jar.lang.Array instead of native as returnvalue
JAR.register({ MID: 'jar.lang.Object.Object-info', deps: ['..', '.!reduce|derive', '..Array!reduce'] }, function(lang, Obj, Arr) { 'use strict'; var reduce = Obj.reduce; lang.extendNativeType('Object', { keys: function() { return reduce(this, pushKey, Arr()); }, pairs: function() { return reduce(this, pushKeyValue, Arr()); }, prop: function(key) { var propList = key.split('.'); return Arr.reduce(propList, extractProperty, this); }, size: function() { return reduce(this, countProperties, 0); }, values: function() { return reduce(this, pushValue, Arr()); } }); function extractProperty(obj, key) { return (obj && Obj.hasOwn(obj, key)) ? obj[key] : undefined; } function countProperties(size) { return ++size; } function pushKey(array, value, key) { array[array.length] = key; return array; } function pushValue(array, value) { array[array.length] = value; return array; } function pushKeyValue(array, value, key) { array[array.length] = Arr(key, value); return array; } return Obj.extract(Obj, ['keys', 'pairs', 'prop', 'size', 'values']); });
JAR.register({ MID: 'jar.lang.Object.Object-info', deps: ['..', '.!reduce|derive', '..Array!reduce'] }, function(lang, Obj, Arr) { 'use strict'; var reduce = Obj.reduce; lang.extendNativeType('Object', { keys: function() { return reduce(this, pushKey, []); }, pairs: function() { return reduce(this, pushKeyValue, []); }, prop: function(key) { var propList = key.split('.'); return Arr.reduce(propList, extractProperty, this); }, size: function() { return reduce(this, countProperties, 0); }, values: function() { return reduce(this, pushValue, []); } }); function extractProperty(obj, key) { return (obj && Obj.hasOwn(obj, key)) ? obj[key] : undefined; } function countProperties(size) { return ++size; } function pushKey(array, value, key) { array[array.length] = key; return array; } function pushValue(array, value) { array[array.length] = value; return array; } function pushKeyValue(array, value, key) { array[array.length] = [key, value]; return array; } return Obj.extract(Obj, ['keys', 'pairs', 'prop', 'size', 'values']); });
Reduce height of mana curve chart So that labels are visible
app.directive("manaCurveChart", function($timeout) { return { restrict: "E", template: "Mana curve<div></div>", scope: { curve: "=" }, link: function(scope, elem, attrs) { scope.$watch("curve", function(curve) { if (!curve) { return; } var data = new google.visualization.DataTable(); data.addColumn("string", "Converted Mana Cost"); data.addColumn("number", "Count"); for (var i = 0; i < curve.length; i++) { var item = curve[i]; data.addRow([item[0], item[1]]); } var options = { backgroundColor: "#eee", legend: { position: "none" }, fontSize: 12, fontName: "'Helvetica Neue', Helvetica, Arial, sans-serif;", chartArea: { width: "100%", height: "80%" }, titleTextStyle: { fontSize: 14, bold: false } }; $timeout(function() { var chart = new google.visualization.ColumnChart(elem.children("div")[0]); chart.draw(data, options); }, 1000); }); } } });
app.directive("manaCurveChart", function($timeout) { return { restrict: "E", template: "Mana curve<div></div>", scope: { curve: "=" }, link: function(scope, elem, attrs) { scope.$watch("curve", function(curve) { if (!curve) { return; } var data = new google.visualization.DataTable(); data.addColumn("string", "Converted Mana Cost"); data.addColumn("number", "Count"); for (var i = 0; i < curve.length; i++) { var item = curve[i]; data.addRow([item[0], item[1]]); } var options = { backgroundColor: "#eee", legend: { position: "none" }, fontSize: 12, fontName: "'Helvetica Neue', Helvetica, Arial, sans-serif;", chartArea: { width: "100%", height: "90%" }, titleTextStyle: { fontSize: 14, bold: false } }; $timeout(function() { var chart = new google.visualization.ColumnChart(elem.children("div")[0]); chart.draw(data, options); }, 1000); }); } } });
Correct data in payment request
import json import requests from .environment import Environment class SwishClient(object): def __init__(self, environment, payee_alias, cert): self.environment = Environment.parse_environment(environment) self.payee_alias = payee_alias self.cert = cert def post(self, endpoint, json): url = self.environment.base_url + endpoint return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert) def get(self, endpoint, id): print("Not implemented yet!") def payment_request(self, amount, currency, callback_url, payee_payment_reference='', message=''): data = { 'payeeAlias': self.payee_alias, 'amount': amount, 'currency': currency, 'callbackUrl': callback_url, 'payeePaymentReference': payee_payment_reference, 'message': message } r = self.post('paymentrequests', json.dumps(data)) return r def get_payment_request(payment_request_id): print("Not implemented yet!") def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''): data = { 'amount': amount, 'currency': currency, 'callback_url': callback_url } r = self.post('refunds', json.dumps(data)) return r def get_refund(refund_id): print("Not implemented yet!")
import json import requests from .environment import Environment class SwishClient(object): def __init__(self, environment, payee_alias, cert): self.environment = Environment.parse_environment(environment) self.payee_alias = payee_alias self.cert = cert def post(self, endpoint, json): url = self.environment.base_url + endpoint return requests.post(url=url, json=json, headers={'Content-Type': 'application/json'}, cert=self.cert) def get(self, endpoint, id): print("Not implemented yet!") def payment_request(self, amount, currency, callback_url, payment_reference='', message=''): data = { 'amount': amount, 'currency': currency, 'callback_url': callback_url, 'payment_reference': payment_reference, 'message': message } r = self.post('paymentrequests', json.dumps(data)) return r def get_payment_request(payment_request_id): print("Not implemented yet!") def refund(self, amount, currency, callback_url, original_payment_reference, payer_payment_reference=''): data = { 'amount': amount, 'currency': currency, 'callback_url': callback_url } r = self.post('refunds', json.dumps(data)) return r def get_refund(refund_id): print("Not implemented yet!")
Use class, module and async
import events from 'events' import util from 'util' import web3 from 'web3' class Contract extends events.EventEmitter { constructor(source) { super() this.source = source this.instance = null this.name = '' this.deploying = false } async compile () { return await web3.eth.compile.solidity(this.source) } async deploy (accountAddress) { var self = this var compiled = await self.compile() , contractName = Object.keys(compiled)[0] , Contract = web3.eth.contract(compiled[contractName].info.abiDefinition) Contract.new( 0, // (uint initialValue) { from: accountAddress, data: compiled[contractName].code, gas: 1000000 }, function (err, contract) { if (err) return done(err) if (!contract.address) { self.deploying = true self.emit('deploying', contract) } else { self.instance = contract self.deploying = false self.emit('deployed', self.instance) } }) } async init (contractAddress) { var compiled = await this.compile() , contractName = Object.keys(compiled)[0] , abiDefinition = compiled[contractName].info.abiDefinition this.instance = web3.eth.contract(abiDefinition).at(contractAddress) } } export default Contract
var events = require('events') var util = require('util') var web3 = require('web3') function Contract (source) { this.source = source this.instance = null this.name = '' this.deploying = false } util.inherits(Contract, events.EventEmitter) Contract.prototype.compile = async function () { try { return await web3.eth.compile.solidity(this.source) } catch (e) { console.log(e) } } Contract.prototype.deploy = function (accountAddress) { var self = this var compiled = self.compile() , contractName = Object.keys(compiled)[0] , Contract = web3.eth.contract(compiled[contractName].info.abiDefinition) Contract.new( 0, // (uint initialValue) { from: accountAddress, data: compiled[contractName].code, gas: 1000000 }, function (err, contract) { if (err) return done(err) if (!contract.address) { self.deploying = true self.emit('deploying', contract) } else { self.instance = contract self.deploying = false self.emit('deployed', self.instance) } }) } Contract.prototype.init = function (contractAddress) { var compiled = this.compile() , contractName = Object.keys(compiled)[0] , abiDefinition = compiled[contractName].info.abiDefinition this.instance = web3.eth.contract(abiDefinition).at(contractAddress) } module.exports = Contract
Switch to toJSON to pull data from models Allows for simpler customization of data.
/** * Page view constructor * Handles all jQuery Mobile setup for any sub-classed page. */ define([ "backbone" ], function(Backbone) { var PageView = Backbone.View.extend({ tagName: "div", isInDOM: false, _name: null, getName: function() { return this._name; }, postRender: function() { this.isInDOM = true; return this; }, render: function() { if (this.isInDOM) { console.warn(this.getName() + " already in DOM."); } else { if (this.model) { this.$el.html(this.template(this.model.toJSON())); } else { this.$el.html(this.template()); } // Set jQuery Mobile attributes here. this.$el.attr("data-role", "page"); // Append to body. $("body").append(this.$el); } return this; } }); return PageView; });
/** * Page view constructor * Handles all jQuery Mobile setup for any sub-classed page. */ define([ "backbone" ], function(Backbone) { var PageView = Backbone.View.extend({ tagName: "div", isInDOM: false, _name: null, getName: function() { return this._name; }, postRender: function() { this.isInDOM = true; return this; }, render: function() { if (this.isInDOM) { console.warn(this.getName() + " already in DOM."); } else { if (this.model) { this.$el.html(this.template(this.model.attributes)); } else { this.$el.html(this.template()); } // Set jQuery Mobile attributes here. this.$el.attr("data-role", "page"); // Append to body. $("body").append(this.$el); } return this; } }); return PageView; });
Add status to project form
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(commit=False) instance.user = self.user instance.flp = self.user instance.status = 'unrevised' instance.save(*args, **kwargs) self.save_m2m() return instance class Meta: model = Project fields = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners', 'status') class RestrictedProjectForm(forms.ModelForm): def save(self, *args, **kwargs): instance = super(RestrictedProjectForm, self).save(commit=False) return instance class Meta: model = Project exclude = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners', 'flp', 'created_at', 'user', ) fileds = ( 'status', 'attitude', )
from django import forms from .models import Project class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(ProjectForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = super(ProjectForm, self).save(commit=False) instance.user = self.user instance.flp = self.user instance.status = 'unrevised' instance.save(*args, **kwargs) self.save_m2m() return instance class Meta: model = Project fields = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners',) class RestrictedProjectForm(forms.ModelForm): def save(self, *args, **kwargs): instance = super(RestrictedProjectForm, self).save(commit=False) return instance class Meta: model = Project exclude = ( 'name', 'team', 'description', 'targets', 'tasks', 'target_group', 'schedule', 'resources', 'finance_description', 'partners', 'flp', 'created_at', 'user', ) fileds = ( 'status', 'attitude', )
Set some Regexp related global variables - $& - $~
<?php namespace Phuby { class Regexp extends Object { } } namespace Phuby\Regexp { class ClassMethods { static function initialized($self) { $self->alias_method('quote', 'escape'); $self->alias_method('valid?', 'valid_query'); } function escape($string, $delimiter = null) { return preg_quote($string, $delimiter); } function valid_query($regexp) { return @preg_match($regexp, '') !== false; } } class InstanceMethods { static function initialized($self) { $self->attr_reader('regexp'); } function initialize($regexp) { if (!$this->class->{'valid?'}($regexp)) $regexp = "/$regexp/"; $this->{'@regexp'} = $regexp; } function match($string) { $string = (string) $string; $this->{'$&'} = null; if (preg_match($this->regexp, $string, $matches)) { $match = Phuby('Phuby\MatchData')->new($this, $string, $matches); $this->{'$&'} = $string; $this->{'$~'} = $match; foreach ($matches as $index => $value) if ($index > 0) $this->{"$$index"} = $value; return $match; } } } }
<?php namespace Phuby { class Regexp extends Object { } } namespace Phuby\Regexp { class ClassMethods { static function initialized($self) { $self->alias_method('quote', 'escape'); $self->alias_method('valid?', 'valid_query'); } function escape($string, $delimiter = null) { return preg_quote($string, $delimiter); } function valid_query($regexp) { return @preg_match($regexp, '') !== false; } } class InstanceMethods { static function initialized($self) { $self->attr_reader('regexp'); } function initialize($regexp) { if (!$this->class->{'valid?'}($regexp)) $regexp = "/$regexp/"; $this->{'@regexp'} = $regexp; } function match($string) { $string = (string) $string; if (preg_match($this->regexp, $string, $matches)) return Phuby('Phuby\MatchData')->new($this, $string, $matches); } } }
Move the taxonomy table definition into a class
<?php namespace Bolt\Database\Table; /** * Table for taxonomy data. * * @author Gawain Lynch <[email protected]> */ class Taxonomy extends BaseTable { /** * {@inheritdoc} */ protected function addColumns() { // @codingStandardsIgnoreStart $this->table->addColumn('id', 'integer', ['autoincrement' => true]); $this->table->addColumn('content_id', 'integer', []); $this->table->addColumn('contenttype', 'string', ['length' => 32]); $this->table->addColumn('taxonomytype', 'string', ['length' => 32]); $this->table->addColumn('slug', 'string', ['length' => 64]); $this->table->addColumn('name', 'string', ['length' => 64, 'default' => '']); $this->table->addColumn('sortorder', 'integer', ['default' => 0]); // @codingStandardsIgnoreEnd } /** * {@inheritdoc} */ protected function addIndexes() { $this->table->addIndex(['content_id']); $this->table->addIndex(['contenttype']); $this->table->addIndex(['taxonomytype']); $this->table->addIndex(['sortorder']); } /** * {@inheritdoc} */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['id']); } }
<?php namespace Bolt\Database\Table; use Doctrine\DBAL\Schema\Schema; /** * Table for taxonomy data. * * @author Gawain Lynch <[email protected]> */ class Taxonomy extends BaseTable { /** * {@inheritdoc} */ protected function addColumns() { // @codingStandardsIgnoreStart $this->table->addColumn('id', 'integer', ['autoincrement' => true]); $this->table->addColumn('content_id', 'integer', []); $this->table->addColumn('contenttype', 'string', ['length' => 32]); $this->table->addColumn('taxonomytype', 'string', ['length' => 32]); $this->table->addColumn('slug', 'string', ['length' => 64]); $this->table->addColumn('name', 'string', ['length' => 64, 'default' => '']); $this->table->addColumn('sortorder', 'integer', ['default' => 0]); // @codingStandardsIgnoreEnd } /** * {@inheritdoc} */ protected function addIndexes() { $this->table->addIndex(['content_id']); $this->table->addIndex(['contenttype']); $this->table->addIndex(['taxonomytype']); $this->table->addIndex(['sortorder']); } /** * {@inheritdoc} */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['id']); } }
Add directConnect to true in protractor tests - it's to avoid the Error: Timed out waiting for the WebDriver server
var HtmlScreenshotReporter = require("protractor-jasmine2-screenshot-reporter"); var JasmineReporters = require('jasmine-reporters'); exports.config = { seleniumServerJar: '../../../node_modules/protractor/selenium/selenium-server-standalone-2.47.1.jar', chromeDriver: '../../../node_modules/protractor/selenium/chromedriver', allScriptsTimeout: 20000, specs: [ 'e2e/*.js' ], capabilities: { 'browserName': 'firefox', 'phantomjs.binary.path': require('phantomjs').path, 'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG'] }, directConnect: true, baseUrl: 'http://localhost:8080/', framework: 'jasmine2', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000 }, onPrepare: function() { browser.driver.manage().window().setSize(1280, 1024); jasmine.getEnv().addReporter(new JasmineReporters.JUnitXmlReporter({ savePath: '<% if (buildTool == 'maven') { %>target<% } else { %>build<% } %>/reports/e2e', consolidateAll: false })); jasmine.getEnv().addReporter(new HtmlScreenshotReporter({ dest: "<% if (buildTool == 'maven') { %>target<% } else { %>build<% } %>/reports/e2e/screenshots" })); } };
var HtmlScreenshotReporter = require("protractor-jasmine2-screenshot-reporter"); var JasmineReporters = require('jasmine-reporters'); exports.config = { seleniumServerJar: '../../../node_modules/protractor/selenium/selenium-server-standalone-2.47.1.jar', chromeDriver: '../../../node_modules/protractor/selenium/chromedriver', allScriptsTimeout: 20000, specs: [ 'e2e/*.js' ], capabilities: { 'browserName': 'firefox', 'phantomjs.binary.path': require('phantomjs').path, 'phantomjs.ghostdriver.cli.args': ['--loglevel=DEBUG'] }, baseUrl: 'http://localhost:8080/', framework: 'jasmine2', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000 }, onPrepare: function() { browser.driver.manage().window().setSize(1280, 1024); jasmine.getEnv().addReporter(new JasmineReporters.JUnitXmlReporter({ savePath: '<% if (buildTool == 'maven') { %>target<% } else { %>build<% } %>/reports/e2e', consolidateAll: false })); jasmine.getEnv().addReporter(new HtmlScreenshotReporter({ dest: "<% if (buildTool == 'maven') { %>target<% } else { %>build<% } %>/reports/e2e/screenshots" })); } };
Make forms & related stuff final again
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\UiBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Paweł Jędrzejewski <[email protected]> */ final class SecurityLoginType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('_username', TextType::class, [ 'label' => 'sylius.form.login.username', ]) ->add('_password', PasswordType::class, [ 'label' => 'sylius.form.login.password', ]) ->add('_remember_me', CheckboxType::class, [ 'label' => 'sylius.form.login.remember_me', 'required' => false, ]) ; } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'sylius_security_login'; } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\UiBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; /** * @author Paweł Jędrzejewski <[email protected]> */ class SecurityLoginType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('_username', TextType::class, [ 'label' => 'sylius.form.login.username', ]) ->add('_password', PasswordType::class, [ 'label' => 'sylius.form.login.password', ]) ->add('_remember_me', CheckboxType::class, [ 'label' => 'sylius.form.login.remember_me', 'required' => false, ]) ; } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'sylius_security_login'; } }
Add extra class for Artisan Adds the call() command. Fixes #42
<?php return array( /* |-------------------------------------------------------------------------- | Filename |-------------------------------------------------------------------------- | | The default path to the helper file | */ 'filename' => '_ide_helper.php', /* |-------------------------------------------------------------------------- | Helper files to include |-------------------------------------------------------------------------- | | Include helper files. By default not included, but can be toggled with the | -- helpers (-H) option. Extra helper files can be included. | */ 'include_helpers' => false, 'helper_files' => array( base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', ), /* |-------------------------------------------------------------------------- | Extra classes |-------------------------------------------------------------------------- | | These implementations are not really extended, but called with magic functions | */ 'extra' => array( 'Artisan' => array('Illuminate\Foundation\Artisan'), 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), 'Session' => array('Illuminate\Session\Store'), ), 'magic' => array( 'Log' => array( 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', 'warning' => 'Monolog\Logger::addWarning', 'error' => 'Monolog\Logger::addError', 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', ) ) );
<?php return array( /* |-------------------------------------------------------------------------- | Filename |-------------------------------------------------------------------------- | | The default path to the helper file | */ 'filename' => '_ide_helper.php', /* |-------------------------------------------------------------------------- | Helper files to include |-------------------------------------------------------------------------- | | Include helper files. By default not included, but can be toggled with the | -- helpers (-H) option. Extra helper files can be included. | */ 'include_helpers' => false, 'helper_files' => array( base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', ), /* |-------------------------------------------------------------------------- | Extra classes |-------------------------------------------------------------------------- | | These implementations are not really extended, but called with magic functions | */ 'extra' => array( 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), 'Session' => array('Illuminate\Session\Store'), ), 'magic' => array( 'Log' => array( 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', 'warning' => 'Monolog\Logger::addWarning', 'error' => 'Monolog\Logger::addError', 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', ) ) );
Use 'fields' instead of 'kwargs' to document intent.
# -*- coding: utf-8 -*- """ The Renderer class provides the infrastructure for generating template-based code. It's used by the .grammars module for parser generation. """ from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')}) override = self.render_fields(fields) if template is None: if override is not None: template = override else: template = self.template fields.update(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- """ The Renderer class provides the infrastructure for generating template-based code. It's used by the .grammars module for parser generation. """ from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **kwargs): fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')}) override = self.render_fields(fields) if template is None: if override is not None: template = override else: template = self.template fields.update(kwargs) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Fix demographics resolve form formatting.
from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset from . import models class DemographicsForm(ModelForm): class Meta: model = models.Demographics exclude = ['patient', 'creation_date'] def __init__(self, *args, **kwargs): super(DemographicsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Fieldset('Medical', 'has_insurance', 'ER_visit_last_year', 'last_date_physician_visit', 'chronic_condition'), Fieldset('Social', 'lives_alone', 'dependents', 'resource_access', 'transportation'), Fieldset('Employment', 'currently_employed', 'education_level', 'work_status', 'annual_income') ) self.helper.add_input(Submit('submit', 'Submit'))
from django.forms import ModelForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset from . import models class DemographicsForm(ModelForm): class Meta: model = models.Demographics exclude = ['patient', 'creation_date'] def __init__(self, *args, **kwargs): super(DemographicsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-8' self.helper.layout = Layout( Fieldset('Medical', 'has_insurance', 'ER_visit_last_year', 'last_date_physician_visit', 'chronic_condition'), Fieldset('Social', 'lives_alone', 'dependents', 'resource_access', 'transportation'), Fieldset('Employment', 'currently_employed', 'education_level', 'work_status', 'annual_income') ) self.helper.add_input(Submit('submit', 'Submit'))
Apply additional fix to add_user_foreign_key migration The hack in 583fb729b1e201c830579345dca5beca4b131006 modified 0010_add_user_foreign_key in such a way that it ended up *not* setting a database constraint when it should have. Enable the database-enforced constraint in the right place. Co-authored-by: Florian Haas <[email protected]>
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import migrations, models import django.db.models.deletion import logging logger = logging.getLogger(__name__) class Migration(migrations.Migration): def backfill_learner(apps, schema_editor): """ Use the 'student_id' to link stacks to the User model. """ Stack = apps.get_model("hastexo", "Stack") AnonymousUserId = apps.get_model("student", "AnonymousUserId") for stack in Stack.objects.all(): try: stack.learner = AnonymousUserId.objects.get( anonymous_user_id=stack.student_id).user stack.save(update_fields=['learner']) except ObjectDoesNotExist: logger.warning('Unable to link stack to user: ' f'{stack.name}') dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('hastexo', '0009_add_null_true_for_key_and_password'), ] operations = [ migrations.AddField( model_name='stack', name='learner', field=models.ForeignKey( db_constraint=False, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), migrations.RunPython(backfill_learner), migrations.AlterField( model_name='stack', name='learner', field=models.ForeignKey( db_constraint=True, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), ]
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.db import migrations, models import django.db.models.deletion import logging logger = logging.getLogger(__name__) class Migration(migrations.Migration): def backfill_learner(apps, schema_editor): """ Use the 'student_id' to link stacks to the User model. """ Stack = apps.get_model("hastexo", "Stack") AnonymousUserId = apps.get_model("student", "AnonymousUserId") for stack in Stack.objects.all(): try: stack.learner = AnonymousUserId.objects.get( anonymous_user_id=stack.student_id).user stack.save(update_fields=['learner']) except ObjectDoesNotExist: logger.warning('Unable to link stack to user: ' f'{stack.name}') dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('hastexo', '0009_add_null_true_for_key_and_password'), ] operations = [ migrations.AddField( model_name='stack', name='learner', field=models.ForeignKey( db_constraint=False, null=True, on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL), ), migrations.RunPython(backfill_learner), ]
Remove a now useless test
var merge = require('./merge'); var isPlainObject = require('./isPlainObject'); var hash = JSON.stringify; function applyTransforms(transforms, declarations, transformCache, result) { var property; for (property in declarations) { var value = declarations[property]; if (property in transforms) { var transform = transforms[property]; var isFunction = typeof transform === 'function'; var key = property + (isFunction ? ':' + hash(value) : ''); if (!(key in transformCache)) { transformCache[key] = merge( Object.create(null), isFunction ? transform(value) : transform ); applyTransforms(transforms, transformCache[key], transformCache, transformCache[key]); } merge(result, transformCache[key]); } else if (isPlainObject(value)) { if (!isPlainObject(result[property])) { result[property] = Object.create(null); } applyTransforms(transforms, value, transformCache, result[property]); } else { result[property] = value; } } return result; } module.exports = function (transforms, declarations, transformCache) { var result = Object.create(null); applyTransforms(transforms, declarations, transformCache, result); return result; };
var merge = require('./merge'); var isPlainObject = require('./isPlainObject'); var hash = JSON.stringify; function applyTransforms(transforms, declarations, transformCache, result) { var property; for (property in declarations) { var value = declarations[property]; if (property in transforms) { var transform = transforms[property]; var isFunction = typeof transform === 'function'; var key = property + (isFunction ? ':' + hash(value) : ''); if (!(key in transformCache)) { transformCache[key] = merge( Object.create(null), isFunction ? transform(value) : transform ); applyTransforms(transforms, transformCache[key], transformCache, transformCache[key]); } if (declarations !== transformCache[key]) { merge(result, transformCache[key]); } } else if (isPlainObject(value)) { if (!isPlainObject(result[property])) { result[property] = Object.create(null); } applyTransforms(transforms, value, transformCache, result[property]); } else { result[property] = value; } } return result; } module.exports = function (transforms, declarations, transformCache) { var result = Object.create(null); applyTransforms(transforms, declarations, transformCache, result); return result; };
Update the schema instead of ignoring when the schema for the table already exists
<?php namespace Common\Doctrine\Entity; use Doctrine\DBAL\Exception\TableExistsException; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\ORM\Tools\ToolsException; class CreateSchema { /** @var EntityManager */ private $entityManager; /** * @param EntityManager $entityManager */ public function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } /** * Adds a new doctrine entity in the database * * @param string $entityClass */ public function forEntityClass($entityClass) { $this->forEntityClasses([$entityClass]); } /** * Adds new doctrine entities in the database * * @param array $entityClasses * * @throws ToolsException */ public function forEntityClasses(array $entityClasses) { // create the database table for the given class using the doctrine SchemaTool $schemaTool = new SchemaTool($this->entityManager); try { $schemaTool->createSchema( array_map( [$this->entityManager, 'getClassMetadata'], $entityClasses ) ); } catch (TableExistsException $tableExists) { $schemaTool->updateSchema( array_map( [$this->entityManager, 'getClassMetadata'], $entityClasses ) ); } catch (ToolsException $toolsException) { if (!$toolsException->getPrevious() instanceof TableExistsException) { throw $toolsException; } $schemaTool->updateSchema( array_map( [$this->entityManager, 'getClassMetadata'], $entityClasses ) ); } } }
<?php namespace Common\Doctrine\Entity; use Doctrine\DBAL\Exception\TableExistsException; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; class CreateSchema { /** @var EntityManager */ private $entityManager; /** * @param EntityManager $entityManager */ public function __construct(EntityManager $entityManager) { $this->entityManager = $entityManager; } /** * Adds a new doctrine entity in the database * * @param string $entityClass */ public function forEntityClass($entityClass) { $this->forEntityClasses([$entityClass]); } /** * Adds new doctrine entities in the database * * @param array $entityClasses */ public function forEntityClasses(array $entityClasses) { // create the database table for the given class using the doctrine SchemaTool $schemaTool = new SchemaTool($this->entityManager); try { $schemaTool->createSchema( array_map( [$this->entityManager, 'getClassMetadata'], $entityClasses ) ); } catch (TableExistsException $tableExists) { // do nothing because it already exists in the database } } }
Fix placement of newly added list items Update how we work out where to add new items to lists to cope with the changed page layout
// ------------------------ // Launch a backbone powered entry box when someone clicks the new-person button // ------------------------ define( [ 'jquery', 'underscore', 'instance-admin/views/list-item-edit' ], function ( $, _, ListItemEditView ) { "use strict"; return function (args) { var collection = args.collection; var defaults = args.defaults || {}; return function(event) { event.preventDefault(); var $link = $(this); var $element = $link.hasClass('add') ? null : $link.closest('li'); if (!$element || !$element.length) { $element = $('<li/>'); $link.closest('ul').prepend($element); } var cid = $element.data('id'), object; // create contact. Might be existing one, or a new one. if (cid) { object = collection.get(cid); object.exists = true; } else { object = new collection.model(defaults, { collection: collection }); object.exists = false; $element.data('id', object.cid); } object.direct = args.direct; // create the view. Hook it up to the enclosing element. var view = new ListItemEditView({ template: _.template(args.template), model: object, el: $element }); view.render(); }; }; } );
// ------------------------ // Launch a backbone powered entry box when someone clicks the new-person button // ------------------------ define( [ 'jquery', 'underscore', 'instance-admin/views/list-item-edit' ], function ( $, _, ListItemEditView ) { "use strict"; return function (args) { var collection = args.collection; var defaults = args.defaults || {}; return function(event) { event.preventDefault(); var $link = $(this), $element = $link.closest('li'); if (!$element.length) { $element = $('<li/>'); $link.closest('section').find('ul').prepend($element); } var cid = $element.data('id'), object; // create contact. Might be existing one, or a new one. if (cid) { object = collection.get(cid); object.exists = true; } else { object = new collection.model(defaults, { collection: collection }); object.exists = false; $element.data('id', object.cid); } object.direct = args.direct; // create the view. Hook it up to the enclosing element. var view = new ListItemEditView({ template: _.template(args.template), model: object, el: $element }); view.render(); }; }; } );
Fix jslint warning in null checks
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function(global) { var wef = function() { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version: "0.0.1", init: function() { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp === null) { tmp = {}; } if (receiver === null) { return tmp; } for (var property in giver) { tmp[property] = giver[property]; } return tmp; } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (global.wef) { throw new Error("wef has already been defined"); } else { global.wef = wef(); } })(window);
/*! * Wef * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ /** * wef module */ (function(global) { var wef = function() { return new wef.prototype.init(); }; wef.prototype = { constructor:wef, version: "0.0.1", init: function() { return this; } }; wef.fn = wef.prototype; wef.prototype.init.prototype = wef.prototype; wef.fn.extend = function (receiver, giver) { var tmp = receiver; //both must be objects if (typeof receiver === "object" && typeof giver === "object") { if (tmp === null) { tmp = {}; } if (receiver === null) { return tmp; } for (var property in giver) { tmp[property] = giver[property]; } return tmp } wef.f.error("InvalidArgumentException: incorrect argument type"); return null; }; wef.fn.isFunction = function (obj) { return typeof obj == "function"; }; wef.fn.isString = function (obj) { return typeof obj == "string"; }; wef.fn.error = function (message) { throw new Error(message); }; //registering global variable if (global.wef) { throw new Error("wef has already been defined"); } else { global.wef = wef(); } })(window);
Add ld alias for the link subcommand.
""" Main entry point """ # from ppci.cli import main import sys import importlib valid_programs = [ "archive", "asm", "build", "c3c", "cc", "disasm", "hexdump", "hexutil", "java", "ld", "link", "llc", "mkuimage", "objcopy", "objdump", "ocaml", "opt", "pascal", "pedump", "pycompile", "readelf", "wabt", "wasm2wat", "wasmcompile", "wat2wasm", "yacc", ] aliases = { 'ld': 'link' } def main(): if len(sys.argv) < 2: print_help_message() else: subcommand = sys.argv[1] subcommand = aliases.get(subcommand, subcommand) cmd_args = sys.argv[2:] if subcommand in valid_programs: m = importlib.import_module("ppci.cli." + subcommand) func = getattr(m, "main", None) or getattr(m, subcommand) func(cmd_args) else: print_help_message() def print_help_message(): print("Welcome to PPCI command line!") print() print("Please use one of the subcommands below:") for cmd in valid_programs: print(" $ python -m ppci {} -h".format(cmd)) print() if __name__ == "__main__": main()
""" Main entry point """ # from ppci.cli import main import sys import importlib valid_programs = [ "archive", "asm", "build", "c3c", "cc", "disasm", "hexdump", "hexutil", "java", "link", "llc", "mkuimage", "objcopy", "objdump", "ocaml", "opt", "pascal", "pedump", "pycompile", "readelf", "wabt", "wasm2wat", "wasmcompile", "wat2wasm", "yacc", ] def main(): if len(sys.argv) < 2: print_help_message() else: subcommand = sys.argv[1] cmd_args = sys.argv[2:] if subcommand in valid_programs: m = importlib.import_module("ppci.cli." + subcommand) func = getattr(m, "main", None) or getattr(m, subcommand) func(cmd_args) else: print_help_message() def print_help_message(): print("Welcome to PPCI command line!") print() print("Please use one of the subcommands below:") for cmd in valid_programs: print(" $ python -m ppci {} -h".format(cmd)) print() if __name__ == "__main__": main()
Remove the print from datashape
"""Error handling""" syntax_error = """ File {filename}, line {lineno} {line} {pointer} {error}: {msg} """ class DataShapeSyntaxError(SyntaxError): """ Makes datashape parse errors look like Python SyntaxError. """ def __init__(self, lexpos, filename, text, msg=None): self.lexpos = lexpos self.filename = filename self.text = text self.msg = msg or 'invalid syntax' self.lineno = text.count('\n', 0, lexpos) + 1 # Get the extent of the line with the error linestart = text.rfind('\n', 0, lexpos) if linestart < 0: linestart = 0 else: linestart = linestart + 1 lineend = text.find('\n', lexpos) if lineend < 0: lineend = len(text) self.line = text[linestart:lineend] self.col_offset = lexpos - linestart def __str__(self): pointer = ' ' * self.col_offset + '^' return syntax_error.format( filename=self.filename, lineno=self.lineno, line=self.line, pointer=pointer, msg=self.msg, error=self.__class__.__name__, ) def __repr__(self): return str(self)
"""Error handling""" syntax_error = """ File {filename}, line {lineno} {line} {pointer} {error}: {msg} """ class DataShapeSyntaxError(SyntaxError): """ Makes datashape parse errors look like Python SyntaxError. """ def __init__(self, lexpos, filename, text, msg=None): self.lexpos = lexpos self.filename = filename self.text = text self.msg = msg or 'invalid syntax' self.lineno = text.count('\n', 0, lexpos) + 1 # Get the extent of the line with the error linestart = text.rfind('\n', 0, lexpos) if linestart < 0: linestart = 0 else: linestart = linestart + 1 lineend = text.find('\n', lexpos) if lineend < 0: lineend = len(text) self.line = text[linestart:lineend] self.col_offset = lexpos - linestart print(str(self)) # REMOVEME def __str__(self): pointer = ' ' * self.col_offset + '^' return syntax_error.format( filename=self.filename, lineno=self.lineno, line=self.line, pointer=pointer, msg=self.msg, error=self.__class__.__name__, ) def __repr__(self): return str(self)
Fix assertion. … since the Formatter has to be inside store emulation to retrieve correct value.
<?php /** * @group category */ class SPM_ShopyMind_Test_DataMapper_Category extends EcomDev_PHPUnit_Test_Case { private $SUT; protected function setUp() { parent::setUp(); $this->SUT = new SPM_ShopyMind_DataMapper_Category(); } protected function tearDown() { parent::tearDown(); if (session_id()) { session_destroy(); } } /** * @loadFixture default */ public function testFieldsAreCorrectlyMapped() { $expected = array( 'shop_id_shop' => 2, 'id_category' => 3, 'id_parent_category' => 2, 'lang' => 'en_US', 'name' => 'Test Category 1', 'description' => 'this is a test category', 'link' => 'http://shopymind.test/catalog/category/view/s/test-category-1/id/3/', 'date_creation' => '2013-10-26 12:00:00', 'active' => '1', ); $scope = SPM_ShopyMind_Model_Scope::fromShopymindId('store-2'); $Action = new SPM_ShopyMind_Action_GetCategory($scope, 3); $category = $Action->process(true); $this->assertEquals($expected, $category); } }
<?php /** * @group category */ class SPM_ShopyMind_Test_DataMapper_Category extends EcomDev_PHPUnit_Test_Case { private $SUT; protected function setUp() { parent::setUp(); $this->SUT = new SPM_ShopyMind_DataMapper_Category(); } protected function tearDown() { parent::tearDown(); if (session_id()) { session_destroy(); } } /** * @loadFixture default */ public function testFieldsAreCorrectlyMapped() { $expected = array( 'shop_id_shop' => 2, 'id_category' => 3, 'id_parent_category' => 2, 'lang' => 'en_US', 'name' => 'Test Category 1', 'description' => 'this is a test category', 'link' => 'http://shopymind.test/catalog/category/view/s/test-category-1/id/3/', 'date_creation' => '2013-10-26 12:00:00', 'active' => '1', ); $scope = SPM_ShopyMind_Model_Scope::fromShopymindId('store-2'); $Action = new SPM_ShopyMind_Action_GetCategory($scope, 3); $category = $Action->process(false); $this->assertEquals($expected, $this->SUT->format($category)); } }
Remove change fn from nestedMenuCollection
"use strict"; angular.module('arethusa.relation').directive('nestedMenuCollection', function() { return { restrict: 'A', replace: 'true', scope: { current: '=', all: '=', property: '=', ancestors: '=', emptyVal: '@', labelAs: "=", }, link: function(scope, element, attrs) { scope.emptyLabel = ""; scope.emptyObj = {}; scope.labelView = function(labelObj) { if (scope.labelAs) { return labelObj[scope.labelAs]; } else { return labelObj.short; } }; }, template: '\ <ul>\ <li ng-if="emptyVal"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="emptyLabel"\ label-obj="emptyObj">\ </li>\ <li\ ng-repeat="label in all | keys"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="labelView(all[label])"\ label-as="labelAs"\ label-obj="all[label]">\ </li>\ </ul>\ ' }; });
"use strict"; angular.module('arethusa.relation').directive('nestedMenuCollection', function() { return { restrict: 'A', replace: 'true', scope: { current: '=', all: '=', property: '=', ancestors: '=', emptyVal: '@', labelAs: "=", change: "&" }, link: function(scope, element, attrs) { scope.emptyLabel = ""; scope.emptyObj = {}; scope.$watch('current[property]', function(newVal, oldVal) { if (newVal !== oldVal) { scope.change({ obj: scope.current }); } }); scope.labelView = function(labelObj) { if (scope.labelAs) { return labelObj[scope.labelAs]; } else { return labelObj.short; } }; }, template: '\ <ul>\ <li ng-if="emptyVal"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ change="change"\ label="emptyLabel"\ label-obj="emptyObj">\ </li>\ <li\ ng-repeat="label in all | keys"\ nested-menu\ property="property"\ rel-obj="current"\ ancestors="ancestors"\ label="labelView(all[label])"\ label-as="labelAs"\ label-obj="all[label]">\ </li>\ </ul>\ ' }; });
Send message to user with fixed id
"use strict"; var shared = require("./shared.js"); var UserPages = require("./UserPages.js"); var fs = require("fs"); var exec = require("sync-exec"); var EC = protractor.ExpectedConditions; var _ = require("lodash"); describe("user page", function() { var currentDate = Date.now().toString(); var subject = "title" + currentDate; var content = "content" + currentDate; it("is possible to send a message", function(done) { shared.loginOtherParticipant(); var annotatorPage = new UserPages.UserPage().get("0000000"); annotatorPage.sendMessage(subject, content); // expect the message widget to disappear var dropdown = element(by.css(".dropdown")); browser.wait(EC.elementToBeClickable(dropdown), 5000); expect(EC.elementToBeClickable(dropdown)).toBeTruthy(); done(); }); it("backend sends message as email", function(done) { var newMails = fs.readdirSync(browser.params.mail.queue_path + "/new"); var lastMail = newMails.length - 1 var mailpath = browser.params.mail.queue_path + "/new/" + newMails[lastMail]; shared.parseEmail(mailpath, function(mail) { expect(mail.text).toContain(content); expect(mail.subject).toContain(subject); expect(mail.from[0].address).toContain("noreply"); expect(mail.to[0].address).toContain("sysadmin"); done(); }); }); });
"use strict"; var shared = require("./shared.js"); var UserPages = require("./UserPages.js"); var fs = require("fs"); var exec = require("sync-exec"); var EC = protractor.ExpectedConditions; var _ = require("lodash"); describe("user page", function() { var currentDate = Date.now().toString(); var subject = "title" + currentDate; var content = "content" + currentDate; it("is possible to send a message", function(done) { shared.loginOtherParticipant(); var annotatorPage = new UserPages.UserPage().get("0000005"); annotatorPage.sendMessage(subject, content); // expect the message widget to disappear var dropdown = element(by.css(".dropdown")); browser.wait(EC.elementToBeClickable(dropdown), 5000); expect(EC.elementToBeClickable(dropdown)).toBeTruthy(); done(); }); it("backend sends message as email", function(done) { var newMails = fs.readdirSync(browser.params.mail.queue_path + "/new"); var lastMail = newMails.length - 1 var mailpath = browser.params.mail.queue_path + "/new/" + newMails[lastMail]; shared.parseEmail(mailpath, function(mail) { expect(mail.text).toContain(content); expect(mail.subject).toContain(subject); expect(mail.from[0].address).toContain("noreply"); expect(mail.to[0].address).toContain("participant"); done(); }); }); });
Fix compatibility issue with PHP 5.3
<?php namespace SlmQueue\Job; use Zend\Stdlib\Message; /** * This class is supposed to be extended. To create a job, just implements the missing "execute" method. If a queueing * system needs more information, you can extend this class (but for both Beanstalk and SQS this is enough) */ abstract class AbstractJob extends Message implements JobInterface { /** * Constructor * * @param mixed $content * @param array $metadata */ public function __construct($content = null, array $metadata = array()) { $this->content = $content; $this->metadata = $metadata; } /** * {@inheritDoc} */ public function setId($id) { $this->setMetadata('id', $id); return $this; } /** * {@inheritDoc} */ public function getId() { return $this->getMetadata('id'); } /** * The 'class' attribute that is saved allow to easily handle dependencies by pulling the job from * the JobPluginManager whenever it is popped from the queue * * @return string */ public function jsonSerialize() { $data = array( 'class' => get_called_class(), 'content' => $this->getContent() ); return json_encode($data); } }
<?php namespace SlmQueue\Job; use Zend\Stdlib\Message; /** * This class is supposed to be extended. To create a job, just implements the missing "execute" method. If a queueing * system needs more information, you can extend this class (but for both Beanstalk and SQS this is enough) */ abstract class AbstractJob extends Message implements JobInterface { /** * Constructor * * @param mixed $content * @param array $metadata */ public function __construct($content = null, array $metadata = array()) { $this->content = $content; $this->metadata = $metadata; } /** * {@inheritDoc} */ public function setId($id) { $this->setMetadata('id', $id); return $this; } /** * {@inheritDoc} */ public function getId() { return $this->getMetadata('id'); } /** * The 'class' attribute that is saved allow to easily handle dependencies by pulling the job from * the JobPluginManager whenever it is popped from the queue * * @return string */ public function jsonSerialize() { $data = array( 'class' => get_called_class(), 'content' => $this->getContent() ); return json_encode($data); } /** * {@inheritDoc} */ abstract public function execute(); }
Create route for new meal form
import React, { Component } from 'react'; import './App.css'; import Nav from './components/Nav' import Home from './components/Home' import HouseholdsContainer from './components/HouseholdsContainer' import Signup from './components/Signup' import Login from './components/Login' import { authenticate, authenticationFailure, logout } from './redux/modules/Auth/actions' import { connect } from 'react-redux' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import { Container } from 'semantic-ui-react' import NewHousehold from './components/NewHousehold' import NewMeal from './components/NewMeal' class App extends Component { componentDidMount() { const token = localStorage.getItem('token') if (token) { this.props.authenticate() } else { this.props.authenticationFailure() } } render() { return ( <Router> <div> <Container text> <Nav logout={this.props.logout} /> </Container> <Container> <Switch> <Route exact path="/" component={Home} /> <Route path="/households/new" component={NewHousehold} /> <Route path="/households" component={HouseholdsContainer} /> <Route path="/meals/new" component={NewMeal} /> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> </Switch> </Container> </div> </Router> ); } } export default connect(null, { authenticate, authenticationFailure, logout })(App);
import React, { Component } from 'react'; import './App.css'; import Nav from './components/Nav' import Home from './components/Home' import HouseholdsContainer from './components/HouseholdsContainer' import Signup from './components/Signup' import Login from './components/Login' import { authenticate, authenticationFailure, logout } from './redux/modules/Auth/actions' import { connect } from 'react-redux' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' import { Container } from 'semantic-ui-react' import NewHousehold from './components/NewHousehold' class App extends Component { componentDidMount() { const token = localStorage.getItem('token') if (token) { this.props.authenticate() } else { this.props.authenticationFailure() } } render() { return ( <Router> <div> <Container text> <Nav logout={this.props.logout} /> </Container> <Container> <Switch> <Route exact path="/" component={Home} /> <Route path="/households/new" component={NewHousehold} /> <Route path="/households" component={HouseholdsContainer} /> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> </Switch> </Container> </div> </Router> ); } } export default connect(null, { authenticate, authenticationFailure, logout })(App);