text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Split Protocol class in Protocol and ProtocolElement
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class ProtocolElement(object): __metaclass__ = ABCMeta @abstractmethod def __init__(self): ''' Constructor ''' def __repr__(self): # This works as long as we accept all properties as paramters in the # constructor params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(params)) def __str__(self): return str(self.to_bytes()) def __bytes__(self): return self.to_bytes() @abstractmethod def sanitize(self): ''' Check and optionally fix properties ''' @classmethod @abstractmethod def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' @abstractmethod def to_bytes(self): ''' Create bytes from properties ''' class Protocol(ProtocolElement): __metaclass__ = ABCMeta header_type = None @abstractmethod def __init__(self, next_header=None, payload=''): ''' Constructor ''' super(Protocol, self).__init__() self.next_header = next_header self.payload = payload
''' Created on 11 jan. 2013 @author: sander ''' from abc import abstractmethod, ABCMeta class Protocol(object): __metaclass__ = ABCMeta header_type = None @abstractmethod def __init__(self, next_header=None, payload=''): ''' Constructor ''' self.next_header = next_header self.payload = payload def __repr__(self): # This works as long as we accept all properties as paramters in the # constructor params = ['%s=%r' % (k, v) for k, v in self.__dict__.iteritems()] return '%s(%s)' % (self.__class__.__name__, ', '.join(params)) @abstractmethod def sanitize(self): ''' Check and optionally fix properties ''' @classmethod @abstractmethod def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' @abstractmethod def to_bytes(self): ''' Create bytes from properties ''' def __str__(self): return str(self.to_bytes()) def __bytes__(self): return bytes(self.to_bytes())
Add data fixtures bundle config
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(), new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(), new Ben\CoreBundle\BenCoreBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(), new Ben\CoreBundle\BenCoreBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
Add Component to StyleManager tests
var path = 'StyleManager/view/'; define([path + 'PropertyView', 'StyleManager/model/Property', 'DomComponents/model/Component'], function(PropertyView, Property, Component) { return { run : function(){ describe('PropertyView', function() { var $fixtures; var $fixture; var model; var view; before(function () { $fixtures = $("#fixtures"); $fixture = $('<div class="cssrule-fixture"></div>'); }); beforeEach(function () { component = new Component(); model = new Property(); view = new PropertyView({ model: model }); $fixture.empty().appendTo($fixtures); $fixture.html(view.render().el); }); afterEach(function () { //view.remove(); // strange errors ??? }); after(function () { $fixture.remove(); }); it('Rendered correctly', function() { var prop = view.el; $fixture.get(0).querySelector('.property').should.be.ok; prop.querySelector('.label').should.be.ok; }); it('Rendered correctly', function() { var prop = view.el; $fixture.get(0).querySelector('.property').should.be.ok; prop.querySelector('.label').should.be.ok; }); }); } }; });
var path = 'StyleManager/view/'; define([path + 'PropertyView', 'StyleManager/model/Property'], function(PropertyView, Property) { return { run : function(){ describe('PropertyView', function() { var $fixtures; var $fixture; var model; var view; before(function () { $fixtures = $("#fixtures"); $fixture = $('<div class="cssrule-fixture"></div>'); }); beforeEach(function () { model = new Property(); view = new PropertyView({ model: model }); $fixture.empty().appendTo($fixtures); $fixture.html(view.render().el); }); afterEach(function () { //view.remove(); // strange errors ??? }); after(function () { $fixture.remove(); }); it('Rendered correctly', function() { var prop = view.el; $fixture.get(0).querySelector('.property').should.be.ok; prop.querySelector('.label').should.be.ok; }); }); } }; });
Handle command-line parsing errors separately from command execution errors.
package org.musetest.commandline; import io.airlift.airline.*; import org.musetest.core.commandline.*; import org.reflections.*; import javax.imageio.spi.*; import java.util.*; /** * @author Christopher L Merrill (see LICENSE.txt for license details) */ public class Launcher { @SuppressWarnings("unchecked") public static void main(String[] args) { // dynamically lookup the commands using Java's ServiceRegistry. This looks at the META-INF/service files in jars on the classpath. Iterator<MuseCommand> commands = ServiceRegistry.lookupProviders(MuseCommand.class); List<Class<? extends Runnable>> implementors = new ArrayList<>(); while (commands.hasNext()) implementors.add((commands.next().getClass())); Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("muse") .withDescription("Muse command-line tools") .withDefaultCommand(Help.class) .withCommands(Help.class) .withCommands(implementors); Cli<Runnable> muse_parser = builder.build(); final Runnable command; try { command = muse_parser.parse(args); } catch (Exception e) { muse_parser.parse(new String[0]).run(); return; } try { command.run(); } catch (Exception e) { System.out.println(String.format("Command failed due to a %s.\n%s", e.getClass().getSimpleName(), e.getMessage())); e.printStackTrace(System.err); } } static { Reflections.log = null; } }
package org.musetest.commandline; import io.airlift.airline.*; import org.musetest.core.commandline.*; import org.reflections.*; import javax.imageio.spi.*; import java.util.*; /** * @author Christopher L Merrill (see LICENSE.txt for license details) */ public class Launcher { @SuppressWarnings("unchecked") public static void main(String[] args) { // dynamically lookup the commands using Java's ServiceRegistry. This looks at the META-INF/service files in jars on the classpath. Iterator<MuseCommand> commands = ServiceRegistry.lookupProviders(MuseCommand.class); List<Class<? extends Runnable>> implementors = new ArrayList<>(); while (commands.hasNext()) implementors.add((commands.next().getClass())); Cli.CliBuilder<Runnable> builder = Cli.<Runnable>builder("muse") .withDescription("Muse command-line tools") .withDefaultCommand(Help.class) .withCommands(Help.class) .withCommands(implementors); Cli<Runnable> muse_parser = builder.build(); try { muse_parser.parse(args).run(); } catch (Exception e) { muse_parser.parse(new String[0]).run(); } } static { Reflections.log = null; } }
Remove unnecessary if true/else false
"""utils.py""" import random from pyechonest import config as echonest_config from pyechonest import song as echonest_song import rfc3987 from gweetr import app from gweetr.exceptions import GweetrError echonest_config.ECHO_NEST_API_KEY = app.config['ECHO_NEST_API_KEY'] def fetch_track(track_params): """ Fetch a track from 7digital via the Echo Nest API. Available track parameters are listed at http://developer.echonest.com/docs/v4/song.html#search """ try: search_results = echonest_song.search( buckets=['id:7digital-US', 'tracks'], limit=True, results=app.config['ECHO_NEST_SONG_RESULTS'], **track_params ) except TypeError as exc: raise GweetrError("Received unknown track parameter: %s" % str(exc)) if search_results: song_obj = random.choice(search_results) tracks = song_obj.get_tracks('7digital-US') track_data = tracks[0] track = { 'title': song_obj.title, 'artist': song_obj.artist_name, 'url': track_data['preview_url'] } return track def is_valid_url(a_string): """Check if a string is a valid URL.""" return rfc3987.match(a_string, 'URI')
"""utils.py""" import random from pyechonest import config as echonest_config from pyechonest import song as echonest_song import rfc3987 from gweetr import app from gweetr.exceptions import GweetrError echonest_config.ECHO_NEST_API_KEY = app.config['ECHO_NEST_API_KEY'] def fetch_track(track_params): """ Fetch a track from 7digital via the Echo Nest API. Available track parameters are listed at http://developer.echonest.com/docs/v4/song.html#search """ try: search_results = echonest_song.search( buckets=['id:7digital-US', 'tracks'], limit=True, results=app.config['ECHO_NEST_SONG_RESULTS'], **track_params ) except TypeError as exc: raise GweetrError("Received unknown track parameter: %s" % str(exc)) if search_results: song_obj = random.choice(search_results) tracks = song_obj.get_tracks('7digital-US') track_data = tracks[0] track = { 'title': song_obj.title, 'artist': song_obj.artist_name, 'url': track_data['preview_url'] } return track def is_valid_url(a_string): """Check if a string is a valid URL.""" match_obj = rfc3987.match(a_string, 'URI') if match_obj: return True else: return False
Make floats something small due to imprecision on large values
<?php /** * Humbug * * @category Humbug * @package Humbug * @copyright Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com) * @license https://github.com/padraic/humbug/blob/master/LICENSE New BSD License */ namespace Humbug\Mutator\Number; use Humbug\Mutator\MutatorAbstract; class Float extends MutatorAbstract { /** * Replace 1 with 0, 0 with 1, or increment. * * @param array $tokens * @param int $index * @return array */ public function getMutation(array $tokens, $index) { $num = (float) $tokens[$index][1]; $replace = null; if ($num == 0) { $replace = 1.0; } elseif ($num == 1) { $replace = 0.0; } elseif ($num < 2) { $replace = $num + 1; } else { $replace = 1.0; } $tokens[$index] = [ T_DNUMBER, sprintf("%.2f", $replace) ]; return $tokens; } public static function mutates(array $tokens, $index) { $t = $tokens[$index]; if (is_array($t) && $t[0] == T_DNUMBER) { return true; } return false; } }
<?php /** * Humbug * * @category Humbug * @package Humbug * @copyright Copyright (c) 2015 Pádraic Brady (http://blog.astrumfutura.com) * @license https://github.com/padraic/humbug/blob/master/LICENSE New BSD License */ namespace Humbug\Mutator\Number; use Humbug\Mutator\MutatorAbstract; class Float extends MutatorAbstract { /** * Replace 1 with 0, 0 with 1, or increment. * * @param array $tokens * @param int $index * @return array */ public function getMutation(array $tokens, $index) { $num = (float) $tokens[$index][1]; $replace = null; if ($num == 0 || $tokens[$index][1] == 0) { $replace = 1.0; } elseif ($num == 1 || $tokens[$index][1] == 1) { $replace = 0.0; } else { $replace = $num + 1; } $tokens[$index] = [ T_DNUMBER, sprintf("%.2f", $replace) ]; return $tokens; } public static function mutates(array $tokens, $index) { $t = $tokens[$index]; if (is_array($t) && $t[0] == T_DNUMBER) { return true; } return false; } }
Drop __toString to allow exceptions
<?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } }
<?php namespace Kameli\Quickpay; use InvalidArgumentException; class Form { const FORM_ACTION = 'https://payment.quickpay.net'; /** * @var array */ protected $parameters = [ 'version' => 'v10', ]; /** * @var array */ protected static $requiredParameters = [ 'version', 'merchant_id', 'agreement_id', 'order_id', 'amount', 'currency', 'continueurl', 'cancelurl', ]; /** * @param array $parameters */ public function __construct(array $parameters) { $this->parameters = array_merge($this->parameters, $parameters); } /** * @return string */ public function action() { return static::FORM_ACTION; } /** * Render the form * @return string */ public function render() { $missingParameters = array_diff(static::$requiredParameters, array_keys($this->parameters)); if (! empty($missingParameters)) { $message = 'Missing arguments for Quickpay Form: ' . implode(', ', $missingParameters); throw new InvalidArgumentException($message); } $fields = []; foreach ($this->parameters as $parameter => $value) { $fields[] = sprintf('<input type="hidden" name="%s" value="%s">', $parameter, $value); } return implode("\n", $fields); } /** * @return string */ public function __toString() { return $this->render(); } }
Mod: Remove leading comments and allow control characters directly.
# -*- coding: utf-8 -*- """ JSON-LD extractor """ import json import re import lxml.etree import lxml.html HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)') class JsonLdExtractor(object): _xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]') def extract(self, htmlstring, base_url=None, encoding="UTF-8"): parser = lxml.html.HTMLParser(encoding=encoding) lxmldoc = lxml.html.fromstring(htmlstring, parser=parser) return self.extract_items(lxmldoc, base_url=base_url) def extract_items(self, document, base_url=None): return [item for items in map(self._extract_items, self._xp_jsonld(document)) for item in items if item] def _extract_items(self, node): script = node.xpath('string()') # now do remove possible leading HTML/JavaScript comment first, allow control characters to be loaded # TODO: `strict=False` can be configurable if needed data = json.loads(HTML_OR_JS_COMMENTLINE.sub('', script), strict=False) if isinstance(data, list): return data elif isinstance(data, dict): return [data]
# -*- coding: utf-8 -*- """ JSON-LD extractor """ import json import re import lxml.etree import lxml.html HTML_OR_JS_COMMENTLINE = re.compile('^\s*(//.*|<!--.*-->)') class JsonLdExtractor(object): _xp_jsonld = lxml.etree.XPath('descendant-or-self::script[@type="application/ld+json"]') def extract(self, htmlstring, base_url=None, encoding="UTF-8"): parser = lxml.html.HTMLParser(encoding=encoding) lxmldoc = lxml.html.fromstring(htmlstring, parser=parser) return self.extract_items(lxmldoc, base_url=base_url) def extract_items(self, document, base_url=None): return [item for items in map(self._extract_items, self._xp_jsonld(document)) for item in items if item] def _extract_items(self, node): script = node.xpath('string()') try: data = json.loads(script) except ValueError: # sometimes JSON-decoding errors are due to leading HTML or JavaScript comments try: data = json.loads(HTML_OR_JS_COMMENTLINE.sub('', script)) except ValueError: # ValueError again because json.JSONDecodeError(bases from ValueError) appears since Python 3.5 # some pages have JSON-LD data with control characters, json.loads should use strict=False data = json.loads(script, strict=False) if isinstance(data, list): return data elif isinstance(data, dict): return [data]
Fix padding on cliploader icon
import React from "react"; import { ClipLoader } from "halogenium"; import { Icon } from "../../base"; import { getTaskDisplayName } from "../../utils"; const JobStep = ({ step, isDone }) => { let hasBar; let stateIcon; let entryStyle; switch (step.state) { case "running": hasBar = isDone; stateIcon = isDone ? "check fa-fw" : ""; entryStyle = isDone ? "success" : "primary"; break; case "complete": hasBar = false; stateIcon = "check fa-fw"; entryStyle = "success"; break; case "error": case "cancelled": hasBar = false; stateIcon = "times fa-fw"; entryStyle = "danger"; break; default: return null; } const stepEntry = ( <div className="step-entry"> <div className="step-entry-icon"> {stateIcon.length ? <Icon name={stateIcon} bsStyle={entryStyle} /> : <ClipLoader size="14px" color="#07689d" style={{padding: "0 1.5px"}} /> } </div> <div className="step-entry-content"> {getTaskDisplayName(step.stage)} </div> <div className={hasBar ? `step-entry-bar-${entryStyle}` : "step-entry-nobar"} /> </div> ); return stepEntry; }; export default JobStep;
import React from "react"; import { ClipLoader } from "halogenium"; import { Icon } from "../../base"; import { getTaskDisplayName } from "../../utils"; const JobStep = ({ step, isDone }) => { let hasBar; let stateIcon; let entryStyle; switch (step.state) { case "running": hasBar = isDone; stateIcon = isDone ? "check fa-fw" : ""; entryStyle = isDone ? "success" : "primary"; break; case "complete": hasBar = false; stateIcon = "check fa-fw"; entryStyle = "success"; break; case "error": case "cancelled": hasBar = false; stateIcon = "times fa-fw"; entryStyle = "danger"; break; default: return null; } const stepEntry = ( <div className="step-entry"> <div className="step-entry-icon"> {stateIcon.length ? <Icon name={stateIcon} bsStyle={entryStyle} /> : <div><ClipLoader size="14px" color="#07689d" style={{padding: "3px 2px"}} /></div> } </div> <div className="step-entry-content"> {getTaskDisplayName(step.stage)} </div> <div className={hasBar ? `step-entry-bar-${entryStyle}` : "step-entry-nobar"} /> </div> ); return stepEntry; }; export default JobStep;
Fix gid not found bug
# -*- coding: utf-8 -*- ''' Set grains describing the minion process. ''' from __future__ import absolute_import, print_function, unicode_literals import os # Import salt libs import salt.utils.platform try: import pwd except ImportError: import getpass pwd = None try: import grp except ImportError: grp = None def _uid(): ''' Grain for the minion User ID ''' if salt.utils.platform.is_windows(): return None return os.getuid() def _username(): ''' Grain for the minion username ''' if pwd: username = pwd.getpwuid(os.getuid()).pw_name else: username = getpass.getuser() return username def _gid(): ''' Grain for the minion Group ID ''' if salt.utils.platform.is_windows(): return None return os.getgid() def _groupname(): ''' Grain for the minion groupname ''' if grp: try: groupname = grp.getgrgid(os.getgid()).gr_name except KeyError: groupname = '' else: groupname = '' return groupname def _pid(): return os.getpid() def grains(): ret = { 'username': _username(), 'groupname': _groupname(), 'pid': _pid(), } if not salt.utils.platform.is_windows(): ret['gid'] = _gid() ret['uid'] = _uid() return ret
# -*- coding: utf-8 -*- ''' Set grains describing the minion process. ''' from __future__ import absolute_import, print_function, unicode_literals import os # Import salt libs import salt.utils.platform try: import pwd except ImportError: import getpass pwd = None try: import grp except ImportError: grp = None def _uid(): ''' Grain for the minion User ID ''' if salt.utils.platform.is_windows(): return None return os.getuid() def _username(): ''' Grain for the minion username ''' if pwd: username = pwd.getpwuid(os.getuid()).pw_name else: username = getpass.getuser() return username def _gid(): ''' Grain for the minion Group ID ''' if salt.utils.platform.is_windows(): return None return os.getgid() def _groupname(): ''' Grain for the minion groupname ''' if grp: groupname = grp.getgrgid(os.getgid()).gr_name else: groupname = '' return groupname def _pid(): return os.getpid() def grains(): ret = { 'username': _username(), 'groupname': _groupname(), 'pid': _pid(), } if not salt.utils.platform.is_windows(): ret['gid'] = _gid() ret['uid'] = _uid() return ret
Fix BC with setCode -> setStatusCode
<?php /** * @author Patsura Dmitry http://github.com/ovr <[email protected]> */ namespace RestApp\Api\Controller; use Exception; use ReflectionExtension; /** * Class IndexController * @Path("/api") */ class IndexController extends \Owl\Mvc\Controller { /** * @Get * @Url("/", name="default") */ public function indexAction() { return array( 'info' => array( 'php' => array( 'version' => PHP_VERSION ), 'time' => time() ) ); } /** * @Get * @Url("/ping", name="api-ping") */ public function pingAction() { return ['pong']; } /** * @Get * @Url("/version", name="api-show-version") */ public function versionAction() { $ext = new ReflectionExtension('owl'); return [ 'version' => '0.1-dev', 'owl' => $ext->getVersion() ]; } public function errorAction() { return array( 'message' => 'Not found', 'uri' => $this->request->getUri() ); } public function exceptionAction(Exception $e) { if ($e->getCode() >= 400) { $this->response->getStatusCode($e->getCode()); } return array( $e->getMessage() ); } }
<?php /** * @author Patsura Dmitry http://github.com/ovr <[email protected]> */ namespace RestApp\Api\Controller; use Exception; use ReflectionExtension; /** * Class IndexController * @Path("/api") */ class IndexController extends \Owl\Mvc\Controller { /** * @Get * @Url("/", name="default") */ public function indexAction() { return array( 'info' => array( 'php' => array( 'version' => PHP_VERSION ), 'time' => time() ) ); } /** * @Get * @Url("/ping", name="api-ping") */ public function pingAction() { return ['pong']; } /** * @Get * @Url("/version", name="api-show-version") */ public function versionAction() { $ext = new ReflectionExtension('owl'); return [ 'version' => '0.1-dev', 'owl' => $ext->getVersion() ]; } public function errorAction() { return array( 'message' => 'Not found', 'uri' => $this->request->getUri() ); } public function exceptionAction(Exception $e) { if ($e->getCode() >= 400) { $this->response->setCode($e->getCode()); } return array( $e->getMessage() ); } }
Use target instead of srcElement Fixes bug in Firefox that prevents panels from being opened.
define([ 'dojo/_base/declare', 'dojo/on' ], function ( declare, on ) { return declare([], { // preventToggleElements: Node[] // these elements do not trigger a panel toggle when clicked preventToggleElements: null, constructor: function () { // summary: // add additional base class console.log('app/mapControls/_Panel:constructor', arguments); this.baseClass = this.baseClass + ' collapse-panel'; this.preventToggleElements = []; }, postCreate: function () { // summary: // set up clickable header that shows and collapses the body console.log('app/mapControls/_Panel:postCreate', arguments); this.preventToggleElements.push(this.closeBtn); this.preventToggleElements.push(this.closeSpan); var that = this; on(this.heading, 'click', function (evt) { if (that.preventToggleElements.indexOf(evt.target) === -1) { $(that.body).collapse('toggle'); } }); this.inherited(arguments); }, open: function () { // summary: // opens the body of the filter console.log('app/mapControls/Filter:open', arguments); $(this.body).collapse('show'); this.inherited(arguments); } }); });
define([ 'dojo/_base/declare', 'dojo/on' ], function ( declare, on ) { return declare([], { // preventToggleElements: Node[] // these elements do not trigger a panel toggle when clicked preventToggleElements: null, constructor: function () { // summary: // add additional base class console.log('app/mapControls/_Panel:constructor', arguments); this.baseClass = this.baseClass + ' collapse-panel'; this.preventToggleElements = []; }, postCreate: function () { // summary: // set up clickable header that shows and collapses the body console.log('app/mapControls/_Panel:postCreate', arguments); this.preventToggleElements.push(this.closeBtn); this.preventToggleElements.push(this.closeSpan); var that = this; on(this.heading, 'click', function (evt) { if (that.preventToggleElements.indexOf(evt.srcElement) === -1) { $(that.body).collapse('toggle'); } }); this.inherited(arguments); }, open: function () { // summary: // opens the body of the filter console.log('app/mapControls/Filter:open', arguments); $(this.body).collapse('show'); this.inherited(arguments); } }); });
Hide Webpack terminal spam on test errors
const webpackConfig = require('../webpack/webpack.test.babel'); const path = require('path'); module.exports = (config) => { config.set({ frameworks: ['mocha'], reporters: ['coverage', 'mocha'], browsers: process.env.TRAVIS // eslint-disable-line no-nested-ternary ? ['ChromeTravis'] : process.env.APPVEYOR ? ['IE'] : ['Chrome'], autoWatch: false, singleRun: true, files: [ { pattern: './test-bundler.js', watched: false, served: true, included: true, }, ], preprocessors: { ['./test-bundler.js']: ['webpack', 'sourcemap'], // eslint-disable-line no-useless-computed-key }, webpack: webpackConfig, // make Webpack bundle generation quiet webpackMiddleware: { noInfo: true, stats: 'errors-only', }, customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'], }, }, coverageReporter: { dir: path.join(process.cwd(), 'coverage'), reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir: 'html' }, { type: 'text-summary' }, ], }, }); };
const webpackConfig = require('../webpack/webpack.test.babel'); const path = require('path'); module.exports = (config) => { config.set({ frameworks: ['mocha'], reporters: ['coverage', 'mocha'], browsers: process.env.TRAVIS // eslint-disable-line no-nested-ternary ? ['ChromeTravis'] : process.env.APPVEYOR ? ['IE'] : ['Chrome'], autoWatch: false, singleRun: true, files: [ { pattern: './test-bundler.js', watched: false, served: true, included: true, }, ], preprocessors: { ['./test-bundler.js']: ['webpack', 'sourcemap'], // eslint-disable-line no-useless-computed-key }, webpack: webpackConfig, // make Webpack bundle generation quiet webpackMiddleware: { noInfo: true, }, customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'], }, }, coverageReporter: { dir: path.join(process.cwd(), 'coverage'), reporters: [ { type: 'lcov', subdir: 'lcov' }, { type: 'html', subdir: 'html' }, { type: 'text-summary' }, ], }, }); };
Allow sessionTokenAction to POST redirect
<?php namespace Payum\Bundle\PayumBundle\Controller; use Payum\Core\Reply\HttpPostRedirect; use Payum\Core\Request\Capture; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\HttpException; class CaptureController extends PayumController { public function doSessionTokenAction(Request $request) { if (false == $request->getSession()) { throw new HttpException(400, 'This controller requires session to be started.'); } if (false == $hash = $request->getSession()->get('payum_token')) { throw new HttpException(400, 'This controller requires token hash to be stored in the session.'); } $request->getSession()->remove('payum_token'); $redirectUrl = $this->generateUrl('payum_capture_do', array_replace( $request->query->all(), array( 'payum_token' => $hash, ) )); if ($request->isMethod('POST')) { throw new HttpPostRedirect($redirectUrl, $request->request->all()); } return $this->redirect($redirectUrl); } public function doAction(Request $request) { $token = $this->getPayum()->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute(new Capture($token)); $this->getPayum()->getHttpRequestVerifier()->invalidate($token); return $this->redirect($token->getAfterUrl()); } }
<?php namespace Payum\Bundle\PayumBundle\Controller; use Payum\Core\Request\Capture; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\HttpException; class CaptureController extends PayumController { public function doSessionTokenAction(Request $request) { if (false == $request->getSession()) { throw new HttpException(400, 'This controller requires session to be started.'); } if (false == $hash = $request->getSession()->get('payum_token')) { throw new HttpException(400, 'This controller requires token hash to be stored in the session.'); } $request->getSession()->remove('payum_token'); return $this->redirect($this->generateUrl('payum_capture_do', array_replace( $request->query->all(), array( 'payum_token' => $hash, ) ))); } public function doAction(Request $request) { $token = $this->getPayum()->getHttpRequestVerifier()->verify($request); $gateway = $this->getPayum()->getGateway($token->getGatewayName()); $gateway->execute(new Capture($token)); $this->getPayum()->getHttpRequestVerifier()->invalidate($token); return $this->redirect($token->getAfterUrl()); } }
Change google maps api text to include destination
require('dotenv').config(); const request = require('request-promise'); const googlemaps = { getResponse: (loc, placeStr, originalStr) => { // originalString is the text query! // var locRegex = /directions(.*)/gi; var locRegex = /directions(?:\s{1}to)*(.*)/gi; var location = locRegex.exec(originalStr); console.log('Location:', location); var destination = location[1]; var rGeocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?` + `latlng=${loc.lat},${loc.lon}&` + `result_type=street_address&` + `key=${process.env.googlemaps_api_key}`; console.log('rGeocodeUrl', rGeocodeUrl); return request(rGeocodeUrl) .then(res => { res = JSON.parse(res); var address = res.results[0].formatted_address; var data = `https://www.google.com/maps/embed/v1/directions?` + `&destination=${destination}` + `&avoid=tolls|highways` + `&key=${process.env.googlemaps_api_key}` + `&origin=${address}`; let apiResponse = { type: 'widget', api: 'googlemap', text: `Directions to ${destination}`, data: data }; return apiResponse; }); } }; module.exports = googlemaps;
require('dotenv').config(); const request = require('request-promise'); const googlemaps = { getResponse: (loc, placeStr, originalStr) => { // originalString is the text query! // var locRegex = /directions(.*)/gi; var locRegex = /directions(?:\s{1}to)*(.*)/gi; var location = locRegex.exec(originalStr); console.log('Location:', location); var destination = location[1]; var rGeocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?` + `latlng=${loc.lat},${loc.lon}&` + `result_type=street_address&` + `key=${process.env.googlemaps_api_key}`; console.log('rGeocodeUrl', rGeocodeUrl); return request(rGeocodeUrl) .then(res => { res = JSON.parse(res); var address = res.results[0].formatted_address; var data = `https://www.google.com/maps/embed/v1/directions?` + `&destination=${destination}` + `&avoid=tolls|highways` + `&key=${process.env.googlemaps_api_key}` + `&origin=${address}`; let apiResponse = { type: 'widget', api: 'googlemap', text: 'You can do this.', data: data }; return apiResponse; }); } }; module.exports = googlemaps;
Enable the all list payment
<?php namespace Morfeu\Bundle\PaymentBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Morfeu\Bundle\BusinessBundle\Enum\StatusPayment; class PaymentFilterType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $status = array( StatusPayment::PENDING => 'Pendente', StatusPayment::FINISHED => 'Finalizado', StatusPayment::ALL => 'Todos', ); $builder ->add('period', 'date', array( 'widget' => 'single_text', 'required' => false, 'format' => 'd/MM/yyyy', )) ->add('periodTo', 'date', array( 'widget' => 'single_text', 'format' => 'd/MM/yyyy', 'required' => false, )) ->add('status', 'choice', array( 'choices' => $status, 'required' => false, 'empty_value' => "Selecione uma opção" )); } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Morfeu\Bundle\BusinessBundle\Model\PaymentFilter' )); } /** * @return string */ public function getName() { return 'morfeu_filter_payment'; } }
<?php namespace Morfeu\Bundle\PaymentBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Morfeu\Bundle\BusinessBundle\Enum\StatusPayment; class PaymentFilterType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $status = array( StatusPayment::PENDING => 'Pendente', StatusPayment::FINISHED => 'Finalizado', ); $builder ->add('period', 'date', array( 'widget' => 'single_text', 'required' => false, 'format' => 'd/MM/yyyy', )) ->add('periodTo', 'date', array( 'widget' => 'single_text', 'format' => 'd/MM/yyyy', 'required' => false, )) ->add('status', 'choice', array( 'choices' => $status, 'empty_value' => "Selecione uma opção" )); } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Morfeu\Bundle\BusinessBundle\Model\PaymentFilter' )); } /** * @return string */ public function getName() { return 'morfeu_filter_payment'; } }
Add some logging at install time Otherwise, it's tough to know if this code executed.
/*global chrome, hwRules */ chrome.runtime.onInstalled.addListener(function(details) { // Install declarative content rules if (details.reason == 'update') { console.info('Upgrade detected, checking data format...'); // Upgrade stored data to a new format when a new version is installed. // Delay installing the rules until the data is upgraded in case the new rules code relies // on the new format. chrome.storage.local.get(null, function (items) { _upgradeData(items); console.info('Data upgraded, adding declarativeContent rules'); hwRules.resetRules(); }); } else { console.info('Adding declarativeContent rules for new install'); hwRules.resetRules(); } function _upgradeData(items) { Object.keys(items).filter(function (domain) { var settings = items[domain]; // For data from previous versions that doesn't have the create/access dates. // We'll use 0 as a special value to indicate that the date is not known. This will // allow us to know that these sites already have hashwords created for them, as // well as show a special string in the options page for such cases. if (settings.createDate == null) { settings.createDate = 0; settings.accessDate = 0; return true; } return false; }); chrome.storage.local.set(items); } }); // Just in case chrome.runtime.onStartup.addListener(hwRules.resetRules);
/*global chrome, hwRules */ chrome.runtime.onInstalled.addListener(function(details) { // Install declarative content rules if (details.reason == 'update') { // Upgrade stored data to a new format when a new version is installed. // Delay installing the rules until the data is upgraded in case the new rules code relies // on the new format. chrome.storage.local.get(null, function (items) { _upgradeData(items); hwRules.resetRules(); }); } else { hwRules.resetRules(); } function _upgradeData(items) { Object.keys(items).filter(function (domain) { var settings = items[domain]; // For data from previous versions that doesn't have the create/access dates. // We'll use 0 as a special value to indicate that the date is not known. This will // allow us to know that these sites already have hashwords created for them, as // well as show a special string in the options page for such cases. if (settings.createDate == null) { settings.createDate = 0; settings.accessDate = 0; return true; } return false; }); chrome.storage.local.set(items); } }); // Just in case chrome.runtime.onStartup.addListener(hwRules.resetRules);
Change order of assert arguments
package com.jedrzejewski.slisp.lexer; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class LexerTest { @Test public void testNextToken() { Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))"); List<Token> tokens = new LinkedList<Token>(); Token token; while ((token = lexer.getNextToken()) != null) { tokens.add(token); } List<Token> expected = Arrays.asList( new OpenBracket(), new Symbol("fn"), new OpenBracket(), new Symbol("zero?"), new Number(0), new CloseBracket(), new OpenBracket(), new Symbol("+"), new Number(2), new Number(3), new CloseBracket(), new CloseBracket()); org.junit.Assert.assertEquals(expected, tokens); } }
package com.jedrzejewski.slisp.lexer; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class LexerTest { @Test public void testNextToken() { Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))"); List<Token> tokens = new LinkedList<Token>(); Token token; while ((token = lexer.getNextToken()) != null) { tokens.add(token); } List<Token> expected = Arrays.asList( new OpenBracket(), new Symbol("fn"), new OpenBracket(), new Symbol("zero?"), new Number(0), new CloseBracket(), new OpenBracket(), new Symbol("+"), new Number(2), new Number(3), new CloseBracket(), new CloseBracket()); org.junit.Assert.assertEquals(tokens, expected); } }
Check margin keyword to Row/Column is not None
from __future__ import absolute_import, division, print_function, unicode_literals from PySide import QtGui def _Box(box, *a): for arg in a: if isinstance(arg, tuple): item = arg[0] else: item = arg arg = (item,) if isinstance(item, QtGui.QLayout): box.addLayout(*arg) if isinstance(item, QtGui.QWidget): box.addWidget(*arg) if item is None: box.addStretch() return box def Row(*a, **kw): """ :rtype: QtGui.QHBoxLayout """ margin = kw.pop('margin', None) box = QtGui.QHBoxLayout(**kw) _Box(box, *a) if margin is not None: box.setContentsMargins(margin, margin, margin, margin) return box def Column(*a, **kw): """ :rtype: QtGui.QVBoxLayout """ margin = kw.pop('margin', None) box = QtGui.QVBoxLayout(**kw) _Box(box, *a) if margin is not None: box.setContentsMargins(margin, margin, margin, margin) return box def setWidgetError(widget, exc): """ Add a subwidget to `widget` that displays the error message for the exception `exc` :param widget: :param exc: :return: """ layout = QtGui.QVBoxLayout() layout.addWidget(QtGui.QLabel(exc.message)) layout.addStretch() widget.setLayout(layout)
from __future__ import absolute_import, division, print_function, unicode_literals from PySide import QtGui def _Box(box, *a): for arg in a: if isinstance(arg, tuple): item = arg[0] else: item = arg arg = (item,) if isinstance(item, QtGui.QLayout): box.addLayout(*arg) if isinstance(item, QtGui.QWidget): box.addWidget(*arg) if item is None: box.addStretch() return box def Row(*a, **kw): """ :rtype: QHBoxLayout """ margin = kw.pop('margin', None) box = QtGui.QHBoxLayout(**kw) if margin: box.setContentsMargins((margin,) * 4) _Box(box, *a) return box def Column(*a, **kw): """ :rtype: QtGui.QVBoxLayout """ margin = kw.pop('margin', None) box = QtGui.QVBoxLayout(**kw) if margin: box.setContentsMargins((margin,) * 4) _Box(box, *a) return box def setWidgetError(widget, exc): """ Add a subwidget to `widget` that displays the error message for the exception `exc` :param widget: :param exc: :return: """ layout = QtGui.QVBoxLayout() layout.addWidget(QtGui.QLabel(exc.message)) layout.addStretch() widget.setLayout(layout)
Update sum error text to be more descriptive
package org.javarosa.xpath.expr; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.DataInstance; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.parser.XPathSyntaxException; public class XPathSumFunc extends XPathFuncExpr { public static final String NAME = "sum"; private static final int EXPECTED_ARG_COUNT = 1; public XPathSumFunc() { name = NAME; expectedArgCount = EXPECTED_ARG_COUNT; } public XPathSumFunc(XPathExpression[] args) throws XPathSyntaxException { super(NAME, args, EXPECTED_ARG_COUNT, true); } @Override public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) { if (evaluatedArgs[0] instanceof XPathNodeset) { return sum(((XPathNodeset)evaluatedArgs[0]).toArgList()); } else { throw new XPathTypeMismatchException("uses an invalid reference inside a sum function"); } } /** * sum the values in a nodeset; each element is coerced to a numeric value */ private static Double sum(Object argVals[]) { double sum = 0.0; for (Object argVal : argVals) { sum += FunctionUtils.toNumeric(argVal); } return sum; } }
package org.javarosa.xpath.expr; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.DataInstance; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.parser.XPathSyntaxException; public class XPathSumFunc extends XPathFuncExpr { public static final String NAME = "sum"; private static final int EXPECTED_ARG_COUNT = 1; public XPathSumFunc() { name = NAME; expectedArgCount = EXPECTED_ARG_COUNT; } public XPathSumFunc(XPathExpression[] args) throws XPathSyntaxException { super(NAME, args, EXPECTED_ARG_COUNT, true); } @Override public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) { if (evaluatedArgs[0] instanceof XPathNodeset) { return sum(((XPathNodeset)evaluatedArgs[0]).toArgList()); } else { throw new XPathTypeMismatchException("not a nodeset"); } } /** * sum the values in a nodeset; each element is coerced to a numeric value */ private static Double sum(Object argVals[]) { double sum = 0.0; for (Object argVal : argVals) { sum += FunctionUtils.toNumeric(argVal); } return sum; } }
Make the project actually compile under Java 7
package com.proxerme.library; import com.proxerme.library.api.ProxerApi; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Response; import okhttp3.mockwebserver.MockWebServer; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import java.io.IOException; /** * TODO: Describe class * * @author Ruben Gees */ public abstract class ApiTest { protected MockWebServer server; protected ProxerApi api; @Before public void setUp() throws IOException { server = new MockWebServer(); api = new ProxerApi.Builder("mockKey") .okHttp(new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { final HttpUrl oldUrl = chain.request().url(); final HttpUrl serverUrl = server.url(oldUrl.encodedPath()); final HttpUrl newUrl = oldUrl.newBuilder() .scheme(serverUrl.scheme()) .host(serverUrl.host()) .port(serverUrl.port()) .build(); return chain.proceed(chain.request().newBuilder().url(newUrl).build()); } }).build()) .build(); server.start(); } @After public void tearDown() throws IOException { server.shutdown(); } @NotNull protected String fromResource(@NotNull final String file) throws IOException { return Okio.buffer(Okio.source(getClass().getClassLoader().getResourceAsStream(file))).readUtf8(); } }
package com.proxerme.library; import com.proxerme.library.api.ProxerApi; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockWebServer; import okio.Okio; import org.jetbrains.annotations.NotNull; import org.junit.After; import org.junit.Before; import java.io.IOException; /** * TODO: Describe class * * @author Ruben Gees */ public abstract class ApiTest { protected MockWebServer server; protected ProxerApi api; @Before public void setUp() throws IOException { server = new MockWebServer(); api = new ProxerApi.Builder("mockKey") .okHttp(new OkHttpClient.Builder() .addInterceptor(chain -> { final HttpUrl oldUrl = chain.request().url(); final HttpUrl serverUrl = server.url(oldUrl.encodedPath()); final HttpUrl newUrl = oldUrl.newBuilder() .scheme(serverUrl.scheme()) .host(serverUrl.host()) .port(serverUrl.port()) .build(); return chain.proceed(chain.request().newBuilder().url(newUrl).build()); }).build()) .build(); server.start(); } @After public void tearDown() throws IOException { server.shutdown(); } @NotNull protected String fromResource(@NotNull final String file) throws IOException { return Okio.buffer(Okio.source(getClass().getClassLoader().getResourceAsStream(file))).readUtf8(); } }
Remove NavLink: unexistent in v2; Create two auxiliary components to apply the correct CSS class(es) to the links.
import React from 'react' import { Link } from 'gatsby' import styles from './navigation.module.styl' // this is only active when the location pathname is exactly // the same as the href. const isActive = ({ location, href }) => { const decodedURI = decodeURI(location.pathname) const isCurrent = decodedURI === href return { className: `${styles.navLink} ${isCurrent ? styles.active : ''}` } } const ExactNavLink = props => <Link getProps={isActive} {...props} /> // this link will be active when itself or deeper routes // are current const isPartiallyActive = ({ location, href }) => { const decodedURI = decodeURI(location.pathname) const isPartiallyCurrent = decodedURI.startsWith(href) return { className: `${styles.navLink} ${isPartiallyCurrent ? styles.active : ''}` } } const PartialNavLink = props => <Link getProps={isPartiallyActive} {...props} /> export default ({ sports }) => ( <nav> <ol className={`${styles.sportsList}`}> {sports.map(({ node }, idx) => ( <li key={idx} className={`${styles.sportItem}`}> <h3 className={styles.noMargin}> <PartialNavLink to={`/${node.name}`}>{node.name}</PartialNavLink> </h3> <ol className={`${styles.countriesList}`}> {node.countries.map((country, idx) => ( <li key={idx} className={`${styles.countryItem}`}> <h3 className={styles.noMargin}> <ExactNavLink to={`/${node.name}/${country.name}`}> {country.name} </ExactNavLink> </h3> </li> ))} </ol> </li> ))} </ol> </nav> )
import React from 'react' import { NavLink } from 'gatsby' import styles from './navigation.module.styl' export default ({ sports }) => ( <nav> <ol className={`${styles.sportsList}`}> {sports.map(({ node }, idx) => ( <li key={idx} className={`${styles.sportItem}`}> <h3 className={styles.noMargin}> <NavLink to={`/${node.name}`} activeClassName={styles.active} className={styles.navLink} > {node.name} </NavLink> </h3> <ol className={`${styles.countriesList}`}> {node.countries.map((country, idx) => ( <li key={idx} className={`${styles.countryItem}`}> <h3 className={styles.noMargin}> <NavLink to={`/${node.name}/${country.name}`} activeClassName={styles.active} className={styles.navLink} > {country.name} </NavLink> </h3> </li> ))} </ol> </li> ))} </ol> </nav> )
Fix default editor not working for dynamic content
(function () { var updateUrl = window.IVOAZ_CONTENT_EDITABLE_UPDATE_URL; var current, timeout; var htmlTags = document.getElementsByTagName('html'); if (0 === htmlTags.length) { return; } document.addEventListener('mouseup', onMouseUp); document.addEventListener('mousedown', function (event) { var el = event.target , found; while (el && !(found = el.classList.contains('ivoaz-content-editable'))) { el = el.parentElement; } onMouseDown(event, found ? el : undefined); }); function onMouseDown(event, target) { target = target || event.currentTarget; if (current && current !== target) { save(); current = undefined; } if (!target.classList.contains('ivoaz-content-editable')) { return; } event.stopPropagation(); if (current) { return; } timeout = setTimeout(function () { current = target; edit(); }, 1000); } function onMouseUp(event) { if (timeout) { clearTimeout(timeout); timeout = undefined; } } function edit() { current.contentEditable = true; current.focus(); } function save() { var request = new XMLHttpRequest(); request.open('PUT', updateUrl.replace(':id', current.dataset.ivoazContentEditableId), true); request.setRequestHeader('Content-Type', 'application/json'); request.setRequestHeader('Accept', 'application/json'); request.send(JSON.stringify({ text: current.innerHTML })); current.contentEditable = false; } })();
(function () { var updateUrl = window.IVOAZ_CONTENT_EDITABLE_UPDATE_URL; var current, timeout; var htmlTags = document.getElementsByTagName('html'); if (0 === htmlTags.length) { return; } var html = htmlTags[0]; html.addEventListener('mousedown', onMouseDown); html.addEventListener('mouseup', onMouseUp); var contents = document.getElementsByClassName('ivoaz-content-editable'); for (var i=0; i < contents.length; ++i) { contents[i].addEventListener('mousedown', onMouseDown); } function onMouseDown(event) { var target = event.currentTarget; if (current && current !== target) { save(); current = undefined; } if (!target.classList.contains('ivoaz-content-editable')) { return; } event.stopPropagation(); if (current) { return; } timeout = setTimeout(function () { current = target; edit(); }, 1000); } function onMouseUp(event) { if (timeout) { clearTimeout(timeout); timeout = undefined; } } function edit() { current.contentEditable = true; current.focus(); } function save() { var request = new XMLHttpRequest(); request.open('PUT', updateUrl.replace(':id', current.dataset.ivoazContentEditableId), true); request.setRequestHeader('Content-Type', 'application/json'); request.setRequestHeader('Accept', 'application/json'); request.send(JSON.stringify({ text: current.innerHTML })); current.contentEditable = false; } })();
Fix console is undefined on IE 8
jQuery(function ($) { function d(event) { event.keyCode === 13 && button.click(); } function click() { image.attr('src', src + (src.indexOf('?') < 0 ? '?' : '&') + '_=' + +new Date()); imgv.val(''); (user.val() ? imgv : user).focus(); } function enable() { button.removeAttr('disabled'); } function disable() { button.attr('disabled', true); } var div = $('#findpassword'), user = div.find('[name="username"]'), button = div.find('[type="button"]'), image = div.find('img'), imgv = div.find('[name="imgVerify"]'); var src = image.attr('src'); image.click(click); imgv.bind('keypress', d); user.bind('keypress', d); button.click(function () { var uid = user.val(), vcode = imgv.val(); if (!uid) { alert('请输入用户名'); user.focus(); } else if (!vcode) { alert('请输入验证码'); imgv.focus(); } else { disable(); $.post('resetPassword.json', {username: uid, verify: vcode}) .always(click, enable).fail(function (result) { alert(result.responseJSON && result.responseJSON.message || result.responseText || 'Error Occur'); }).success(function (result) { alert(result.message); }); } }); });
jQuery(function ($) { function d(event) { event.keyCode === 13 && button.click(); } function click() { image.attr('src', src + (src.indexOf('?') < 0 ? '?' : '&') + '_=' + +new Date()); imgv.val(''); (user.val() ? imgv : user).focus(); } function enable() { button.removeAttr('disabled'); } function disable() { button.attr('disabled', true); } var div = $('#findpassword'), user = div.find('[name="username"]'), button = div.find('[type="button"]'), image = div.find('img'), imgv = div.find('[name="imgVerify"]'); var src = image.attr('src'); image.click(click); imgv.bind('keypress', d); user.bind('keypress', d); button.click(function () { var uid = user.val(), vcode = imgv.val(); if (!uid) { alert('请输入用户名'); user.focus(); } else if (!vcode) { alert('请输入验证码'); imgv.focus(); } else { disable(); $.post('resetPassword.json', {username: uid, verify: vcode}) .always(click, enable).fail(function (result) { console.log(arguments); alert(result.responseJSON && result.responseJSON.message || result.responseText || 'Error Occur'); }).success(function (result) { alert(result.message); }); } }); });
Change version to 1.2.1 (dev)
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { 'name': u"Asset Streamline", 'version': u"1.2.1", 'author': u"XCG Consulting", 'category': u"Custom Module", 'description': u"""Includes several integrity fixes and optimizations over the standard module. """, 'website': u"", 'depends': [ 'base', 'account_streamline', 'analytic_structure' 'account_asset', 'oemetasl', ], 'data': [ 'data/asset_sequence.xml', 'security/ir.model.access.csv', 'wizard/account_asset_close_view.xml', 'wizard/account_asset_suspend_view.xml', 'wizard/account_asset_change_values_view.xml', 'wizard/account_asset_depreciation_wizard.xml', 'wizard/account_asset_change_duration_view.xml', 'views/account_asset_view.xml', ], 'demo': [ 'demo/account_asset_demo.xml' ], 'css': [ 'static/src/css/account_asset_streamline.css' ], 'test': [], 'installable': True, 'active': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { 'name': u"Asset Streamline", 'version': u"1.0", 'author': u"XCG Consulting", 'category': u"Custom Module", 'description': u"""Includes several integrity fixes and optimizations over the standard module. """, 'website': u"", 'depends': [ 'base', 'account_streamline', 'analytic_structure' 'account_asset', 'oemetasl', ], 'data': [ 'data/asset_sequence.xml', 'security/ir.model.access.csv', 'wizard/account_asset_close_view.xml', 'wizard/account_asset_suspend_view.xml', 'wizard/account_asset_change_values_view.xml', 'wizard/account_asset_depreciation_wizard.xml', 'wizard/account_asset_change_duration_view.xml', 'views/account_asset_view.xml', ], 'demo': [ 'demo/account_asset_demo.xml' ], 'css': [ 'static/src/css/account_asset_streamline.css' ], 'test': [], 'installable': True, 'active': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Test wrapt.document for Read the Docs
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', 'wrapt.decorator', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from codecs import open import os.path as osp from setuptools import setup, find_packages import strumenti here = osp.abspath(osp.dirname(__file__)) with open(osp.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='strumenti', version='1.0.0', description='Common tools universally applicable to Python 3 packages.', author='Timothy Helton', author_email='[email protected]', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Build Tools', ], keywords='common tools utility', packages=find_packages(exclude=['docs', 'tests*']), install_requires=[ 'matplotlib', 'numpy', 'Pint', 'psycopg2', 'pytest', 'termcolor', 'wrapt', ], package_dir={'strumenti': 'strumenti'}, include_package_data=True, ) if __name__ == '__main__': pass
Throw an exception when try to mutate data on ImmutableDataObjectInterface instance. Access data from DataObjectInterface instance and ImmutableDataObjectInterface instance.
<?php /** * * (c) Marco Bunge <[email protected]> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. * * Date: 12.02.2016 * Time: 10:02 * */ namespace Blast\Db\Data; class Helper { /** * receive data from object * * @param $object * @return array */ public static function receiveDataFromObject($object) { $data = []; if ($object instanceof DataObjectInterface || $object instanceof ImmutableDataObjectInterface) { $data = $object->getData(); } elseif ($object instanceof \ArrayObject) { $data = $object->getArrayCopy(); } elseif (is_object($object)) { $data = (array) $object; } return $data; } /** * receive data from object * * @param $object * @param array $data * @return array */ public static function replaceDataFromObject($object, $data = []) { if ($object instanceof DataObjectInterface) { $object->setData($data); } elseif ($object instanceof ImmutableDataObjectInterface) { throw new \InvalidArgumentException('Helper can not replace data. Given object is immutable!'); } elseif ($object instanceof \ArrayObject) { $object->exchangeArray($data); } elseif (is_object($object)) { foreach($data as $key => $value){ $object->$key = $value; } } } }
<?php /** * * (c) Marco Bunge <[email protected]> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. * * Date: 12.02.2016 * Time: 10:02 * */ namespace Blast\Db\Data; class Helper { /** * receive data from object * * @param $object * @return array */ public static function receiveDataFromObject($object) { $data = []; if ($object instanceof DataObjectInterface) { $data = $object->getData(); } elseif ($object instanceof \ArrayObject) { $data = $object->getArrayCopy(); } elseif (is_object($object)) { $data = (array) $object; } return $data; } /** * receive data from object * * @param $object * @param array $data * @return array */ public static function replaceDataFromObject($object, $data = []) { if ($object instanceof DataObjectInterface) { $object->setData($data); } elseif ($object instanceof \ArrayObject) { $object->exchangeArray($data); } elseif (is_object($object)) { foreach($data as $key => $value){ $object->$key = $value; } } } }
Add documentation to SenderBase plugin
import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): MAPPING = [ ('project', Project), ('service', Service), ] def _send(self, target, alert, data): ''' Sender specific implmentation This function will receive some kind of target value, such as an email address or post endpoint and an individual alert combined with some additional alert meta data ''' raise NotImplementedError() def send(self, data): ''' Send out an alert This handles looping through the alerts from Alert Manager and checks to see if there are any notification senders configured for the combination of project/service and sender type. See tests/examples/alertmanager.json for an example payload ''' sent = 0 for alert in data['alerts']: for label, klass in self.MAPPING: logger.debug('Checking for %s', label) if label in alert['labels']: logger.debug('Checking for %s %s', label, klass) for obj in klass.objects.filter(name=alert['labels'][label]): for sender in obj.sender.filter(sender=self.__module__): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service') return sent def test(self, target, alert): ''' Send out test notification Combine a simple test alert from our view, with the remaining required parameters for our sender child classes ''' logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
import logging from promgen.models import Project, Service logger = logging.getLogger(__name__) class SenderBase(object): MAPPING = [ ('project', Project), ('service', Service), ] def send(self, data): sent = 0 for alert in data['alerts']: for label, klass in self.MAPPING: logger.debug('Checking for %s', label) if label in alert['labels']: logger.debug('Checking for %s %s', label, klass) for obj in klass.objects.filter(name=alert['labels'][label]): for sender in obj.sender.filter(sender=self.__module__): logger.debug('Sending to %s', sender) if self._send(sender.value, alert, data): sent += 1 if sent == 0: logger.debug('No senders configured for project or service') return sent def test(self, target, alert): logger.debug('Sending test message to %s', target) self._send(target, alert, {'externalURL': ''})
Allow middleware to also be non-function callables
<?php namespace Lstr\Sprintf; class ParsedExpression { /** * @var string */ private $parsed_format; /** * @var array */ private $parameter_map; /** * @param string $parsed_format * @param array $parameter_map */ public function __construct($parsed_format, array $parameter_map) { $this->parsed_format = $parsed_format; $this->parameter_map = $parameter_map; } /** * @param array $parameters * @param callable|null $middleware * @return string * @throws Exception */ public function format(array $parameters, callable $middleware = null) { if (!$middleware) { $middleware = function ($name, $value, array $options) { return $value; }; } $parsed_parameters = []; foreach ($this->parameter_map as $param_mapping) { $param_name = $param_mapping['name']; if (!array_key_exists($param_name, $parameters)) { throw new Exception( "The '{$param_name}' parameter was in the format string but was not provided" ); } $parsed_parameters[] = call_user_func( $middleware, $param_name, $parameters[$param_name], [] ); } return vsprintf($this->parsed_format, $parsed_parameters); } }
<?php namespace Lstr\Sprintf; class ParsedExpression { /** * @var string */ private $parsed_format; /** * @var array */ private $parameter_map; /** * @param string $parsed_format * @param array $parameter_map */ public function __construct($parsed_format, array $parameter_map) { $this->parsed_format = $parsed_format; $this->parameter_map = $parameter_map; } /** * @param array $parameters * @param callable|null $middleware * @return string * @throws Exception */ public function format(array $parameters, callable $middleware = null) { if (!$middleware) { $middleware = function ($name, $value, array $options) { return $value; }; } $parsed_parameters = []; foreach ($this->parameter_map as $param_mapping) { $param_name = $param_mapping['name']; if (!array_key_exists($param_name, $parameters)) { throw new Exception( "The '{$param_name}' parameter was in the format string but was not provided" ); } $parsed_parameters[] = $middleware($param_name, $parameters[$param_name], []); } return vsprintf($this->parsed_format, $parsed_parameters); } }
Prepare "Main Summary" job for backfill Set the max number of active runs so we don't overwhelm the system, and rewind the start date by a couple of days to test that the scheduler does the right thing.
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': '[email protected]', 'depends_on_past': False, 'start_date': datetime(2016, 6, 25), 'email': ['[email protected]', '[email protected]'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 2, 'retry_delay': timedelta(minutes=30), } dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily', max_active_runs=10) # Make sure all the data for the given day has arrived before running. t0 = BashOperator(task_id="delayed_start", bash_command="sleep 1800", dag=dag) t1 = EMRSparkOperator(task_id="main_summary", job_name="Main Summary View", execution_timeout=timedelta(hours=10), instance_count=10, env={"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"}, uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh", dag=dag) # Wait a little while after midnight to start for a given day. t1.set_upstream(t0)
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': '[email protected]', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['[email protected]', '[email protected]'], 'email_on_failure': True, 'email_on_retry': True, 'retries': 2, 'retry_delay': timedelta(minutes=30), } dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily') # Make sure all the data for the given day has arrived before running. t0 = BashOperator(task_id="delayed_start", bash_command="sleep 1800", dag=dag) t1 = EMRSparkOperator(task_id="main_summary", job_name="Main Summary View", execution_timeout=timedelta(hours=10), instance_count=10, env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.private_output_bucket }}"}, uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh", dag=dag) # Wait a little while after midnight to start for a given day. t1.set_upstream(t0)
Rewrite Account tests to ES2015
'use strict'; const assert = require('assert'); const sinon = require('sinon'); const Account = require('../../lib/endpoints/account'); const Request = require('../../lib/request'); describe('endpoints/account', () => { describe('changePassword', () => { it('should set the request URL', () => { const request = new Request(); const account = new Account(request); const stub = sinon.stub(request, 'post', (url) => { assert.strictEqual(url, '/account/changepassword'); }); account.changePassword(); assert.ok(stub.called); }); it('should set the request body', () => { const request = new Request(); const account = new Account(request); const expected = { password: 'password', }; const stub = sinon.stub(request, 'post', (url, data) => { assert.deepEqual(data, expected); }); account.changePassword(expected); assert.ok(stub.called); }); }); describe('info', () => { it('should set the request URL', () => { const request = new Request(); const account = new Account(request); const stub = sinon.stub(request, 'get', (url) => { assert.strictEqual(url, '/account/info'); }); account.info(); assert.ok(stub.called); }); }); });
'use strict'; var assert = require('assert'); var sinon = require('sinon'); var Account = require('../../lib/endpoints/account'); var Request = require('../../lib/request'); describe('endpoints/account', function () { describe('changePassword', function () { it('should set the request URL', function () { var request = new Request(); var account; var stub; stub = sinon.stub(request, 'post', function (url) { assert.strictEqual(url, '/account/changepassword'); }); account = new Account(request); account.changePassword(); assert.ok(stub.called); }); it('should set the request body', function () { var request = new Request(); var account; var stub; var expected = { password: 'password', }; stub = sinon.stub(request, 'post', function (url, data) { assert.deepEqual(data, expected); }); account = new Account(request); account.changePassword(expected); assert.ok(stub.called); }); }); describe('info', function () { it('should set the request URL', function () { var request = new Request(); var account; var stub; stub = sinon.stub(request, 'get', function (url) { assert.strictEqual(url, '/account/info'); }); account = new Account(request); account.info(); assert.ok(stub.called); }); }); });
Allow to override test client
'use strict'; require('../helper'); var assert = require('assert'); var appServer = require('../../app/server'); function response(code) { return { status: code }; } var RESPONSE = { OK: response(200), CREATED: response(201) }; function TestClient(config) { this.config = config || {}; this.server = appServer(); } module.exports = TestClient; TestClient.prototype.getResult = function(query, override, callback) { if (!callback) { callback = override; override = {}; } assert.response( this.server, { url: this.getUrl(override), headers: { host: this.getHost(override), 'Content-Type': 'application/json' }, method: 'POST', data: JSON.stringify({ q: query }) }, RESPONSE.OK, function (err, res) { if (err) { return callback(err); } var result = JSON.parse(res.body); return callback(null, result.rows || []); } ); }; TestClient.prototype.getHost = function(override) { return override.host || this.config.host || 'vizzuality.cartodb.com'; }; TestClient.prototype.getUrl = function(override) { return '/api/v2/sql?api_key=' + (override.apiKey || this.config.apiKey || '1234'); };
'use strict'; require('../helper'); var assert = require('assert'); var appServer = require('../../app/server'); function response(code) { return { status: code }; } var RESPONSE = { OK: response(200), CREATED: response(201) }; function TestClient(config) { this.config = config || {}; this.server = appServer(); } module.exports = TestClient; TestClient.prototype.getResult = function(query, callback) { assert.response( this.server, { url: this.getUrl(), headers: { host: this.getHost(), 'Content-Type': 'application/json' }, method: 'POST', data: JSON.stringify({ q: query }) }, RESPONSE.OK, function (err, res) { if (err) { return callback(err); } var result = JSON.parse(res.body); return callback(null, result.rows || []); } ); }; TestClient.prototype.getHost = function() { return this.config.host || 'vizzuality.cartodb.com'; }; TestClient.prototype.getUrl = function() { return '/api/v2/sql?api_key=' + (this.config.apiKey || '1234'); };
Use name() instead of toString() for enum value. The javadoc for Enum notes that name() should be used when correctness depends on getting the exact name of the enum constant which will not vary from release to release. The javadoc further encourages overriding the toString() method when appropriate to provide a more user-friendly name. This commit fixes the DefaultEnumConverterFactory in cases where the toString() method is overridden to return something other than the enum constant.
package org.sql2o.converters; /** * Default implementation of {@link EnumConverterFactory}, * used by sql2o to convert a value from the database into an {@link Enum}. */ public class DefaultEnumConverterFactory implements EnumConverterFactory { public <E extends Enum> Converter<E> newConverter(final Class<E> enumType) { return new Converter<E>() { @SuppressWarnings("unchecked") public E convert(Object val) throws ConverterException { if (val == null) { return null; } try { if (val instanceof String){ return (E)Enum.valueOf(enumType, val.toString()); } else if (val instanceof Number){ return enumType.getEnumConstants()[((Number)val).intValue()]; } } catch (Throwable t) { throw new ConverterException("Error converting value '" + val.toString() + "' to " + enumType.getName(), t); } throw new ConverterException("Cannot convert type '" + val.getClass().getName() + "' to an Enum"); } public Object toDatabaseParam(Enum val) { return val.name(); } }; } }
package org.sql2o.converters; /** * Default implementation of {@link EnumConverterFactory}, * used by sql2o to convert a value from the database into an {@link Enum}. */ public class DefaultEnumConverterFactory implements EnumConverterFactory { public <E extends Enum> Converter<E> newConverter(final Class<E> enumType) { return new Converter<E>() { @SuppressWarnings("unchecked") public E convert(Object val) throws ConverterException { if (val == null) { return null; } try { if (val instanceof String){ return (E)Enum.valueOf(enumType, val.toString()); } else if (val instanceof Number){ return enumType.getEnumConstants()[((Number)val).intValue()]; } } catch (Throwable t) { throw new ConverterException("Error converting value '" + val.toString() + "' to " + enumType.getName(), t); } throw new ConverterException("Cannot convert type '" + val.getClass().getName() + "' to an Enum"); } public Object toDatabaseParam(Enum val) { return val.toString(); } }; } }
Update format for group members view
import _ from 'lodash' import React from 'react' import {connect} from 'react-redux' import {compose, withHandlers, withProps, withState} from 'recompose' import GroupMembersList from './GroupMembersList' import {addMemberToGroup} from '../actions/groups' const mapStateToProps = ({groups}) => ({ groups }) const enhance = compose( connect(mapStateToProps), withProps(({match}) => ({ groupId: match.params.groupId })), withState('newGroupMember', 'updateNewGroupMember', ''), withHandlers({ onNewGroupMemberChange: props => event => { props.updateNewGroupMember(event.target.value) }, onNewGroupMemberSubmit: props => event => { event.preventDefault() props.dispatch(addMemberToGroup({ groupId: props.groupId, memberId: props.newGroupMember, })) } }), ) const GroupMembersView = ({ groups, groupId, onNewGroupMemberSubmit, onNewGroupMemberChange, newGroupMember, }) => ( <div> <GroupMembersList groupId={groupId} memberIds={ Object.keys( _.get(groups, `${groupId}.members`, {}) ) } /> <form onSubmit={onNewGroupMemberSubmit}> <textarea placeholder='Add New Member' value={newGroupMember} onChange={onNewGroupMemberChange} /> <input type='submit' value='submit' /> </form> </div> ) export default enhance(GroupMembersView)
import _ from 'lodash' import React from 'react' import {connect} from 'react-redux' import {compose, withHandlers, withProps, withState} from 'recompose' import GroupMembersList from './GroupMembersList' import {addMemberToGroup} from '../actions/groups' const mapStateToProps = ({groups}) => ({ groups }) const enhance = compose( connect(mapStateToProps), withProps(({match}) => ({ groupId: match.params.groupId })), withState('newMember', 'updateNewMember', ''), withHandlers({ onNewMemberChange: props => event => { props.updateNewMember(event.target.value) }, onNewGroupMemberSubmit: props => event => { event.preventDefault() props.dispatch(addMemberToGroup({ groupId: props.groupId, memberId: props.newMember, })) } }), ) const GroupMembersView = ({groups, groupId, onNewGroupMemberSubmit, onNewMemberChange, newMember}) => ( <div> <GroupMembersList groupId={groupId} memberIds={ Object.keys( _.get(groups, `${groupId}.members`, {}) ) } /> <form onSubmit={onNewGroupMemberSubmit}> <textarea placeholder='Add New Member' value={newMember} onChange={onNewMemberChange} /> <input type='submit' value='submit' /> </form> </div> ) export default enhance(GroupMembersView)
Fix code style in optional parent interface implementation
<?php /* * This file is part of the Active Collab DatabaseStructure project. * * (c) A51 doo <[email protected]>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\DatabaseStructure\Behaviour\ParentInterface; use ActiveCollab\DatabaseObject\Entity\EntityInterface; use ActiveCollab\DatabaseStructure\Behaviour\ParentInterface; use LogicException; /** * @property \ActiveCollab\DatabaseObject\PoolInterface $pool */ trait OptionalImplementation { public function getParent(bool $use_cache = true): ?EntityInterface { if ($id = $this->getParentId()) { return $this->pool->getById($this->getParentType(), $id, $use_cache); } else { return null; } } /** * @param EntityInterface|null $value * @return ParentInterface|$this */ public function &setParent(?EntityInterface $value): ParentInterface { if ($value === null) { $this->setParentType(null); $this->setParentId(null); } else { if (!$value->isLoaded()) { throw new LogicException('Parent needs to be saved to the database.'); } $this->setParentType(get_class($value)); $this->setParentId($value->getId()); } return $this; } abstract public function getParentType(): ?string; abstract public function &setParentType(?string $value); abstract public function getParentId(): ?int; abstract public function &setParentId(?int $value); }
<?php /* * This file is part of the Active Collab DatabaseStructure project. * * (c) A51 doo <[email protected]>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\DatabaseStructure\Behaviour\ParentInterface; use ActiveCollab\DatabaseObject\Entity\EntityInterface; use ActiveCollab\DatabaseStructure\Behaviour\ParentInterface; use LogicException; /** * @property \ActiveCollab\DatabaseObject\PoolInterface $pool */ trait OptionalImplementation { public function getParent(bool $use_cache = true): ?EntityInterface { if ($id = $this->getParentId()) { return $this->pool->getById($this->getParentType(), $id, $use_cache); } else { return null; } } /** * @param EntityInterface|null $value * @return ParentInterface|$this */ public function &setParent(?EntityInterface $value): ParentInterface { if ($value === null) { $this->setParentType(null); $this->setParentId(null); } else { if (!$value->isLoaded()) { throw new LogicException('Parent needs to be saved to the database.'); } $this->setParentType(get_class($value)); $this->setParentId($value->getId()); } return $this; } abstract public function getParentType(): ?string; abstract public function &setParentType(?string $value); abstract public function getParentId(): ?int; abstract public function &setParentId(?int $value); }
Allow theme to be changed
import Router from '@ember/routing/router'; export function initialize() { const isEmbedded = window !== window.top; if (isEmbedded) { Router.reopen({ notifyTopFrame: function() { window.top.postMessage({ action: 'did-transition', url: this.currentURL }) }.on('didTransition'), willTranstionNotify: function(transition) { const router = window.ls('router'); window.top.postMessage({ action: 'before-navigation', target: transition.targetName, url: router.urlFor(transition.targetName) }) }.on('willTransition') }); // Add listener for post messages to change the route in the application window.addEventListener('message', (event) => { const msg = event.data || {}; // Navigate when asked to if (msg.action === 'navigate') { const router = window.ls('router'); // If the route being asked for is already loaded, then if (router.currentRouteName === msg.name) { window.top.postMessage({ action: 'did-transition', url: router.urlFor(msg.name) }) } router.transitionTo(msg.name); } else if (msg.action == 'set-theme') { const userTheme = window.ls('userTheme'); if (userTheme) { userTheme.setTheme( msg.name, false); } } }); } } export default { name: 'route-spy', initialize, };
import Router from '@ember/routing/router'; export function initialize() { const isEmbedded = window !== window.top; if (isEmbedded) { Router.reopen({ notifyTopFrame: function() { window.top.postMessage({ action: 'did-transition', url: this.currentURL }) }.on('didTransition'), willTranstionNotify: function(transition) { const router = window.ls('router'); window.top.postMessage({ action: 'before-navigation', target: transition.targetName, url: router.urlFor(transition.targetName) }) }.on('willTransition') }); // Add listener for post messages to change the route in the application window.addEventListener('message', (event) => { const msg = event.data || {}; // Navigate when asked to if (msg.action === 'navigate') { const router = window.ls('router'); // If the route being asked for is already loaded, then if (router.currentRouteName === msg.name) { window.top.postMessage({ action: 'did-transition', url: router.urlFor(msg.name) }) } router.transitionTo(msg.name); } }); } } export default { name: 'route-spy', initialize, };
Fix to remove Activity as necessary arg
package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } }
package com.peak.salut; import android.util.Log; import com.arasthel.asyncjob.AsyncJob; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.net.Socket; public class BackgroundDataJob implements AsyncJob.OnBackgroundJob{ private Salut salutInstance; private Socket clientSocket; private String data; public BackgroundDataJob(Salut salutInstance, Socket clientSocket) { this.clientSocket = clientSocket; this.salutInstance = salutInstance; } @Override public void doOnBackground() { try { //If this code is reached, a client has connected and transferred data. Log.v(Salut.TAG, "A device is sending data..."); BufferedInputStream bufferedRead = new BufferedInputStream(clientSocket.getInputStream()); DataInputStream dataStreamFromOtherDevice = new DataInputStream(bufferedRead); data = dataStreamFromOtherDevice.readUTF(); dataStreamFromOtherDevice.close(); Log.d(Salut.TAG, "\nSuccessfully received data.\n"); if(!data.isEmpty()) { salutInstance.dataReceiver.currentContext.runOnUiThread(new Runnable() { @Override public void run() { salutInstance.dataReceiver.dataCallback.onDataReceived(data); } }); } } catch(Exception ex) { Log.e(Salut.TAG, "An error occurred while trying to receive data."); ex.printStackTrace(); } finally { try { clientSocket.close(); } catch (Exception ex) { Log.e(Salut.TAG, "Failed to close data socket."); } } } }
Fix typo on Master Alchemist dishonor action chat message
const DrawCard = require('../../drawcard.js'); const { CardTypes } = require('../../Constants'); class MasterAlchemist extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Honor or dishonor a character', cost: ability.costs.payFateToRing(1, ring => ring.element === 'fire'), condition: () => this.game.isDuringConflict(), target: { activePromptTitle: 'Choose a character to honor or dishonor', cardType: CardTypes.Character, gameAction: ability.actions.chooseAction({ messages: { 'Honor this character': '{0} chooses to honor {1}', 'Dishonor this character': '{0} chooses to dishonor {1}' }, choices: { 'Honor this character': ability.actions.honor(), 'Dishonor this character': ability.actions.dishonor() } }) } }); } } MasterAlchemist.id = 'master-alchemist'; module.exports = MasterAlchemist;
const DrawCard = require('../../drawcard.js'); const { CardTypes } = require('../../Constants'); class MasterAlchemist extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Honor or dishonor a character', cost: ability.costs.payFateToRing(1, ring => ring.element === 'fire'), condition: () => this.game.isDuringConflict(), target: { activePromptTitle: 'Choose a character to honor or dishonor', cardType: CardTypes.Character, gameAction: ability.actions.chooseAction({ messages: { 'Honor this character': '{0} chooses to honor {1}', 'Dishonor this character': '{0} chooses to honor {1}' }, choices: { 'Honor this character': ability.actions.honor(), 'Dishonor this character': ability.actions.dishonor() } }) } }); } } MasterAlchemist.id = 'master-alchemist'; module.exports = MasterAlchemist;
Remove let keyword in order to support <=0.12
'use strict' var Hoek = require("hoek"); var requireDir = require('require-dir'); var internals = {}; var defaultOptions = {}; internals.settings = {}; internals.runThroughPlugins = function (pluginsPaths, options, server) { if (pluginsPaths) { if (pluginsPaths.register) { var name = pluginsPaths.register.attributes.name; var pluginOptions = {}; if (options.pluginOptions) { if (options.pluginOptions[name]) { pluginOptions = options.pluginOptions[name]; } } internals.registerPlugin(pluginsPaths, pluginOptions, server); } else { Object.keys(pluginsPaths).forEach( function (key) { var nextPlugin = pluginsPaths[key]; internals.runThroughPlugins(nextPlugin, options, server); }); } } }; internals.registerPlugin = function (plugin, options, server) { server.register({ register: plugin, options: options }, function (err) { }); }; exports.register = function (server, options, next) { internals.settings = Hoek.applyToDefaults(defaultOptions, options); for(var path of options.paths) { var services = requireDir(path, {recurse: true}); internals.runThroughPlugins(services, internals.settings, server); } next(); }; exports.register.attributes = { name: 'plugins-loader' };
'use strict' var Hoek = require("hoek"); var requireDir = require('require-dir'); var internals = {}; var defaultOptions = {}; internals.settings = {}; internals.runThroughPlugins = function (pluginsPaths, options, server) { if (pluginsPaths) { if (pluginsPaths.register) { let name = pluginsPaths.register.attributes.name; let pluginOptions = {}; if (options.pluginOptions) { if (options.pluginOptions[name]) { pluginOptions = options.pluginOptions[name]; } } internals.registerPlugin(pluginsPaths, pluginOptions, server); } else { Object.keys(pluginsPaths).forEach( function (key) { let nextPlugin = pluginsPaths[key]; internals.runThroughPlugins(nextPlugin, options, server); }); } } }; internals.registerPlugin = function (plugin, options, server) { server.register({ register: plugin, options: options }, function (err) { }); }; exports.register = function (server, options, next) { internals.settings = Hoek.applyToDefaults(defaultOptions, options); for(let path of options.paths) { let services = requireDir(path, {recurse: true}); internals.runThroughPlugins(services, internals.settings, server); } next(); }; exports.register.attributes = { name: 'plugins-loader' };
Handle case where screensEnabled isn't available (in Snack)
/* @flow */ import * as React from 'react'; import { Platform, StyleSheet, View } from 'react-native'; import { Screen, screensEnabled } from 'react-native-screens'; type Props = { isVisible: boolean, children: React.Node, style?: any, }; const FAR_FAR_AWAY = 3000; // this should be big enough to move the whole view out of its container export default class ResourceSavingScene extends React.Component<Props> { render() { if (screensEnabled && screensEnabled()) { const { isVisible, ...rest } = this.props; return <Screen active={isVisible ? 1 : 0} {...rest} />; } const { isVisible, children, style, ...rest } = this.props; return ( <View style={[styles.container, style]} collapsable={false} removeClippedSubviews={ // On iOS, set removeClippedSubviews to true only when not focused // This is an workaround for a bug where the clipped view never re-appears Platform.OS === 'ios' ? !isVisible : true } pointerEvents={isVisible ? 'auto' : 'none'} {...rest} > <View style={isVisible ? styles.attached : styles.detached}> {children} </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, overflow: 'hidden', }, attached: { flex: 1, }, detached: { flex: 1, top: FAR_FAR_AWAY, }, });
/* @flow */ import * as React from 'react'; import { Platform, StyleSheet, View } from 'react-native'; import { Screen, screensEnabled } from 'react-native-screens'; type Props = { isVisible: boolean, children: React.Node, style?: any, }; const FAR_FAR_AWAY = 3000; // this should be big enough to move the whole view out of its container export default class ResourceSavingScene extends React.Component<Props> { render() { if (screensEnabled()) { const { isVisible, ...rest } = this.props; return <Screen active={isVisible ? 1 : 0} {...rest} />; } const { isVisible, children, style, ...rest } = this.props; return ( <View style={[styles.container, style]} collapsable={false} removeClippedSubviews={ // On iOS, set removeClippedSubviews to true only when not focused // This is an workaround for a bug where the clipped view never re-appears Platform.OS === 'ios' ? !isVisible : true } pointerEvents={isVisible ? 'auto' : 'none'} {...rest} > <View style={isVisible ? styles.attached : styles.detached}> {children} </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, overflow: 'hidden', }, attached: { flex: 1, }, detached: { flex: 1, top: FAR_FAR_AWAY, }, });
Check config and show what required options not exists
/* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!util.isString(options[required_option])){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); };
/* * grunt-browser-extension * https://github.com/addmitriev/grunt-browser-extension * * Copyright (c) 2015 Aleksey Dmitriev * Licensed under the MIT license. */ 'use strict'; var util = require('util'); var path = require('path'); var fs = require('fs-extra'); module.exports = function (grunt) { var BrowserExtension = require('./lib/browser-extension')(grunt); grunt.registerMultiTask('browser_extension', 'Grunt plugin to create any browser website extension', function () { if(this.target){ var options = this.options(); var required_options = []; for(var required_options_id in required_options){ if(required_options_id){ var required_option = required_options[required_options_id]; if(!options[required_option]){ grunt.fail.fatal("Please set up all required options. All options must be string value! You have not setted " + required_option); } } } var pluginRoot = path.join(path.dirname(fs.realpathSync(__filename)), '../'); var bExt = new BrowserExtension(pluginRoot, options, this.target, grunt); bExt.copyUserFiles(); grunt.verbose.ok('User files copied'); bExt.copyBrowserFiles(); grunt.verbose.ok('Extension files copied'); bExt.buildNsisIE(); grunt.verbose.ok('NSIS installer for IE builded'); bExt.build(); grunt.verbose.ok('Extensions builded'); } }); };
Allow broadcaster's labels to be localized
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], broadcaster: ['label'], button: ['accesskey'], key: ['key', 'keycode'], menu: ['label', 'accesskey'], menuitem: ['label', 'accesskey'], tab: ['label'], textbox: ['placeholder'], toolbarbutton: ['label', 'tooltiptext'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], key: ['key', 'keycode'], menu: ['label', 'accesskey'], menuitem: ['label', 'accesskey'], tab: ['label'], textbox: ['placeholder'], toolbarbutton: ['label', 'tooltiptext'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
Use two digit numbers to ensure PHP isn't converting the array to a string
<?php class ArrTest extends PHPUnit_Framework_TestCase { function testFlatten() { $this->assertEquals( array('a', 'b', 'c', 'd'), Missing\Arr::flatten(array( array('a','b'), 'c', array(array(array('d'))), )) ); } function testSortByInt() { $this->assertEquals( array('a', 'a', 'ab', 'abc', 'abcd'), Missing\Arr::sort_by( array('abcd', 'ab', 'a', 'abc', 'a'), function ($a) { return strlen($a); } ) ); } function testSortByString() { $this->assertEquals( array('a333', 'b22', 'c1', 'd55555'), Missing\Arr::sort_by( array('d55555', 'b22', 'a333', 'c1'), function ($a) { return $a; } ) ); } function testSortByArray() { $this->assertEquals( array(array(2, 'b'), array(2, 'c'), array(19, 'a')), Missing\Arr::sort_by( array(array(19, 'a'), array(2, 'c'), array(2, 'b')), function ($a) { return $a; } ) ); } function testSortByTriggersError() { $this->setExpectedException('PHPUnit_Framework_Error'); Missing\Arr::sort_by(function(){}, array()); } }
<?php class ArrTest extends PHPUnit_Framework_TestCase { function testFlatten() { $this->assertEquals( array('a', 'b', 'c', 'd'), Missing\Arr::flatten(array( array('a','b'), 'c', array(array(array('d'))), )) ); } function testSortByInt() { $this->assertEquals( array('a', 'a', 'ab', 'abc', 'abcd'), Missing\Arr::sort_by( array('abcd', 'ab', 'a', 'abc', 'a'), function ($a) { return strlen($a); } ) ); } function testSortByString() { $this->assertEquals( array('a333', 'b22', 'c1', 'd55555'), Missing\Arr::sort_by( array('d55555', 'b22', 'a333', 'c1'), function ($a) { return $a; } ) ); } function testSortByArray() { $this->assertEquals( array(array(1, 'b'), array(1, 'c'), array(2, 'a')), Missing\Arr::sort_by( array(array(2, 'a'), array(1, 'c'), array(1, 'b')), function ($a) { return $a; } ) ); } function testSortByTriggersError() { $this->setExpectedException('PHPUnit_Framework_Error'); Missing\Arr::sort_by(function(){}, array()); } }
Fix param sent to the API Signed-off-by: soupette <[email protected]>
import { isEmpty, pickBy, transform } from 'lodash'; import request from './request'; const findMatchingPermissions = (userPermissions, permissions) => { return transform( userPermissions, (result, value) => { const associatedPermission = permissions.find( perm => perm.action === value.action && perm.subject === value.subject ); if (associatedPermission) { result.push(value); } }, [] ); }; const formatPermissionsForRequest = permissions => permissions.map(permission => pickBy(permission, (value, key) => { return ['action', 'subject'].includes(key) && !isEmpty(value); }) ); const shouldCheckPermissions = permissions => !isEmpty(permissions) && permissions.every(perm => !isEmpty(perm.conditions)); const hasPermissions = async (userPermissions, permissions, signal) => { if (!permissions || !permissions.length) { return true; } const matchingPermissions = findMatchingPermissions(userPermissions, permissions); if (shouldCheckPermissions(matchingPermissions)) { let hasPermission = false; try { const { data } = await request('/admin/permissions/check', { method: 'POST', body: { permissions: formatPermissionsForRequest(matchingPermissions), }, signal, }); hasPermission = data.every(v => v === true); } catch (err) { console.error('Error while checking permissions', err); } return hasPermission; } return matchingPermissions.length > 0; }; export default hasPermissions; export { findMatchingPermissions, formatPermissionsForRequest, shouldCheckPermissions };
import { isEmpty, pickBy, transform } from 'lodash'; import request from './request'; const findMatchingPermissions = (userPermissions, permissions) => { return transform( userPermissions, (result, value) => { const associatedPermission = permissions.find( perm => perm.action === value.action && perm.subject === value.subject ); if (associatedPermission) { result.push(value); } }, [] ); }; const formatPermissionsForRequest = permissions => permissions.map(permission => pickBy(permission, (value, key) => { return ['action', 'subject', 'fields'].includes(key) && !isEmpty(value); }) ); const shouldCheckPermissions = permissions => !isEmpty(permissions) && permissions.every(perm => !isEmpty(perm.conditions)); const hasPermissions = async (userPermissions, permissions, signal) => { if (!permissions || !permissions.length) { return true; } const matchingPermissions = findMatchingPermissions(userPermissions, permissions); if (shouldCheckPermissions(matchingPermissions)) { let hasPermission = false; try { const { data } = await request('/admin/permissions/check', { method: 'POST', body: { permissions: formatPermissionsForRequest(matchingPermissions), }, signal, }); hasPermission = data.every(v => v === true); } catch (err) { console.error('Error while checking permissions', err); } return hasPermission; } return matchingPermissions.length > 0; }; export default hasPermissions; export { findMatchingPermissions, formatPermissionsForRequest, shouldCheckPermissions };
Split send_message out in to _send_message to reuse functionality later
import requests from .error import PushoverCompleteError class PushoverAPI(object): def __init__(self, token): self.token = token def send_message(self, user, message, device=None, title=None, url=None, url_title=None, priority=None, retry=None, expire=None, timestamp=None, sound=None, html=False): if priority == 2: if retry is None or expire is None: raise PushoverCompleteError('Must specify `retry` and `expire` with priority 2.') payload = { 'token': self.token, 'user': user, 'message': message, 'device': device, 'title': title, 'url': url, 'url_title': url_title, 'priority': priority, 'retry': retry, 'expire': expire, 'timestamp': timestamp, 'sound': sound, 'html': html } headers = {'Content-type': 'application/x-www-form-urlencoded'} r = requests.post( 'https://api.pushover.net/1/messages.json', data=payload, headers=headers def get_sounds(self): resp = requests.get( urljoin(PUSHOVER_API_URL, 'sounds.json'), data={'token': self.token} ) sounds = resp.json().get('sounds', None) if sounds: return sounds else: raise PushoverCompleteError('Could not retrieve sounds')
import requests from .error import PushoverCompleteError class PushoverAPI(object): def __init__(self, token): self.token = token def send_message(self, user, message, device=None, title=None, url=None, url_title=None, priority=None, retry=None, expire=None, timestamp=None, sound=None, html=False): if priority == 2: if retry is None or expire is None: raise PushoverCompleteError('Must specify `retry` and `expire` with priority 2.') payload = { 'token': self.token, 'user': user, 'message': message, 'device': device, 'title': title, 'url': url, 'url_title': url_title, 'priority': priority, 'retry': retry, 'expire': expire, 'timestamp': timestamp, 'sound': sound, 'html': html } headers = {'Content-type': 'application/x-www-form-urlencoded'} r = requests.post( 'https://api.pushover.net/1/messages.json', data=payload, headers=headers ) return r
Optimize pending order screen load
function openerp_pos_ncf_widgets(instance, module) { //module is instance.point_of_sale var QWeb = instance.web.qweb; var _t = instance.web._t; module.PosWidget = module.PosWidget.extend({ // This method instantiates all the screens, widgets, etc. If you want to add new screens change the // startup screen, etc, override this method. build_widgets: function () { var self = this; this._super(); if (false) {// TODO: implement configurable parameter for the POS to allow unpaid orders. // -------- New Screens definitions. this.orderlist_screen = new module.PendingOrderListScreenWidget(this, {}); this.orderlist_screen.appendTo(this.$('.screens')); // -------- Misc. this.pendingorders_button = new module.HeaderButtonWidget(this, { label: _t('Ordenes Pendientes'), action: function () { self.screen_selector.set_current_screen('orderlist', {}, true); } }); this.pendingorders_button.appendTo(this.$('.pos-rightheader')); // -------- Adding Pending Order Screen to screen_selector. this.screen_selector.add_screen('orderlist', this.orderlist_screen); } } }); }
function openerp_pos_ncf_widgets(instance, module) { //module is instance.point_of_sale var QWeb = instance.web.qweb; var _t = instance.web._t; module.PosWidget = module.PosWidget.extend({ start: function() { var self = this; this._super(); }, // This method instantiates all the screens, widgets, etc. If you want to add new screens change the // startup screen, etc, override this method. build_widgets: function () { var self = this; this._super(); // -------- New Screens definitions. this.orderlist_screen = new module.PendingOrderListScreenWidget(this, {}); this.orderlist_screen.appendTo(this.$('.screens')); // -------- Misc. if (false) {// TODO: implement configurable parameter for the POS to allow unpaid orders. this.pendingorders_button = new module.HeaderButtonWidget(this, { label: _t('Ordenes Pendientes'), action: function () { self.screen_selector.set_current_screen('orderlist', {}, true); } }); this.pendingorders_button.appendTo(this.$('.pos-rightheader')); } // -------- Adding Pending Order Screen to screen_selector. this.screen_selector.add_screen('orderlist', this.orderlist_screen); } }); }
Remove unused conditon which cant hold anyway
package name.abuchen.portfolio.util; public class Isin { private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$ public static final String PATTERN = "[A-Z]{2}[A-Z0-9]{9}\\d"; //$NON-NLS-1$ private Isin() { } public static final boolean isValid(String isin) // NOSONAR { if (isin == null || isin.length() != 12) return false; int sum = 0; boolean even = false; for (int ii = 11; ii >= 0; ii--) { int v = CHARACTERS.indexOf(isin.charAt(ii)); if (v < 0) return false; int digit = v % 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; if (v >= 10) { digit = v / 10 * (even ? 2 : 1); sum += digit; even = !even; } } return sum % 10 == 0; } }
package name.abuchen.portfolio.util; public class Isin { private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$ public static final String PATTERN = "[A-Z]{2}[A-Z0-9]{9}\\d"; //$NON-NLS-1$ private Isin() { } public static final boolean isValid(String isin) // NOSONAR { if (isin == null || isin.length() != 12) return false; int sum = 0; boolean even = false; for (int ii = 11; ii >= 0; ii--) { int v = CHARACTERS.indexOf(isin.charAt(ii)); if (v < 0) return false; int digit = v % 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; if (v >= 10) { digit = v / 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; } } return sum % 10 == 0; } }
Add a paint-event test to the main page
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Initializes a new instance of the `Page` class. */ public function Page() { $this->Template = new BootstrapTemplate($this); $this->Renderer->Paint->Add(\Closure::fromCallable(array($this, 'OnItemPaint'))); } private function OnItemPaint($sender, PaintEventArgs $e) { if ($e->Item instanceof MenuItem) { if ($e->Item->Name == 'home') { $e->Cancel = true; } } } /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <div class="container"> <h1>Hello</h1> World </div>'; } } } ?>
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <div class="container"> <h1>Hello</h1> World </div>'; } /** * @ignore */ public function __Initialize() : array { return array('Template' => new BootstrapTemplate($this)); } } } ?>
Disable CGC simprocedures, it's unhelpful at the moment
import angr import simuvex class DrillerTransmit(simuvex.SimProcedure): ''' CGC's transmit simprocedure which supports errors ''' def run(self, fd, buf, count, tx_bytes): if self.state.mode == 'fastpath': # Special case for CFG generation self.state.store_mem(tx_bytes, count, endness='Iend_LE') return self.state.se.BVV(0, self.state.arch.bits) if ABSTRACT_MEMORY in self.state.options: data = self.state.mem_expr(buf, count) self.state.posix.write(fd, data, count) self.state.store_mem(tx_bytes, count, endness='Iend_LE') else: if self.state.satisfiable(extra_constraints=[count != 0]): data = self.state.mem_expr(buf, count) self.state.posix.write(fd, data, count) self.data = data else: self.data = None self.size = count self.state.store_mem(tx_bytes, count, endness='Iend_LE', condition=tx_bytes != 0) # TODO: transmit failure transmit_return = self.state.se.BV("transmit_return", self.state.arch.bits) self.state.add_constraints(transmit_return >= -1) self.state.add_constraints(transmit_return <= 0) return transmit_return # disable simprocedures for CGC simprocedures = []
import angr import simuvex class DrillerTransmit(simuvex.SimProcedure): ''' CGC's transmit simprocedure which supports errors ''' def run(self, fd, buf, count, tx_bytes): if self.state.mode == 'fastpath': # Special case for CFG generation self.state.store_mem(tx_bytes, count, endness='Iend_LE') return self.state.se.BVV(0, self.state.arch.bits) if ABSTRACT_MEMORY in self.state.options: data = self.state.mem_expr(buf, count) self.state.posix.write(fd, data, count) self.state.store_mem(tx_bytes, count, endness='Iend_LE') else: if self.state.satisfiable(extra_constraints=[count != 0]): data = self.state.mem_expr(buf, count) self.state.posix.write(fd, data, count) self.data = data else: self.data = None self.size = count self.state.store_mem(tx_bytes, count, endness='Iend_LE', condition=tx_bytes != 0) # TODO: transmit failure transmit_return = self.state.se.BV("transmit_return", self.state.arch.bits) self.state.add_constraints(transmit_return >= -1) self.state.add_constraints(transmit_return <= 0) return transmit_return simprocedures = [("transmit", DrillerTransmit)]
Update the retries count of a queued message when it is changed back from deferred
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH) def normal_priority(self): """ Return a QuerySet of normal priority queued messages. """ return self.filter(priority=constants.PRIORITY_NORMAL) def low_priority(self): """ Return a QuerySet of low priority queued messages. """ return self.filter(priority=constants.PRIORITY_LOW) def non_deferred(self): """ Return a QuerySet containing all non-deferred queued messages. """ return self.filter(deferred=False) def deferred(self): """ Return a QuerySet of all deferred messages in the queue. """ return self.filter(deferred=True) def retry_deferred(self, new_priority=None): """ Reset the deferred flag for all deferred messages so they will be retried. """ count = self.deferred().count() update_kwargs = dict(deferred=False, retries=models.F('retries')+1) if new_priority is not None: update_kwargs['priority'] = new_priority self.deferred().update(**update_kwargs) return count
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH) def normal_priority(self): """ Return a QuerySet of normal priority queued messages. """ return self.filter(priority=constants.PRIORITY_NORMAL) def low_priority(self): """ Return a QuerySet of low priority queued messages. """ return self.filter(priority=constants.PRIORITY_LOW) def non_deferred(self): """ Return a QuerySet containing all non-deferred queued messages. """ return self.filter(deferred=False) def deferred(self): """ Return a QuerySet of all deferred messages in the queue. """ return self.filter(deferred=True) def retry_deferred(self, new_priority=None): """ Reset the deferred flag for all deferred messages so they will be retried. """ count = self.deferred().count() update_kwargs = dict(deferred=False) if new_priority is not None: update_kwargs['priority'] = new_priority self.deferred().update(**update_kwargs) return count
Use native system dialog instead of input type=file
// @flow import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import Dropzone from 'react-dropzone'; import styles from './Server.css'; const { dialog } = require('electron').remote; class Server extends Component { static propTypes = { start: PropTypes.func.isRequired, shutdown: PropTypes.func.isRequired, servers: PropTypes.arrayOf(PropTypes.object).isRequired }; handleDrop = (files: Object) => { const file = files && files[0]; if (!file || !file.path) return; this.props.start(file.path); } handleClick = () => { dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'] }, filePaths => { if (!filePaths || !filePaths[0]) return; this.props.start(filePaths[0]); }); } render() { const { shutdown, servers } = this.props; return ( <div className={styles.container}> <h1>Server</h1> <div> <Link to="/"> <i className="fa fa-arrow-left fa-3x" /> </Link> </div> <div> {servers.map(server => ( <div key={server.id}> {server.baseDir} <button onClick={() => shutdown(server.id)}>Shutdown</button> </div> ))} </div> <div> <div> <Dropzone onDrop={this.handleDrop} disableClick multiple={false}> <button onClick={this.handleClick}>Drop folder here</button> </Dropzone> </div> </div> </div> ); } } export default Server;
// @flow import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import Dropzone from 'react-dropzone'; import styles from './Server.css'; class Server extends Component { static propTypes = { start: PropTypes.func.isRequired, shutdown: PropTypes.func.isRequired, servers: PropTypes.arrayOf(PropTypes.object).isRequired }; handleDrop = (files: Object) => { const file = files[0]; if (!file || !file.path) return; this.props.start(file.path); } render() { const { shutdown, servers } = this.props; return ( <div className={styles.container}> <h1>Server</h1> <div> <Link to="/"> <i className="fa fa-arrow-left fa-3x" /> </Link> </div> <div> {servers.map(server => ( <div key={server.id}> {server.baseDir} <button onClick={() => shutdown(server.id)}>Shutdown</button> </div> ))} </div> <div> <div> <Dropzone onDrop={this.handleDrop} multiple={false}> <div>Drop folder here</div> </Dropzone> </div> </div> </div> ); } } export default Server;
Fix doctrine issues after first request is made.
<?php namespace Codeception\Lib\Connector; class Symfony2 extends \Symfony\Component\HttpKernel\Client { private static $hasPerformedRequest; public $persistentServices = []; protected function doRequest($request) { $services = []; if (self::$hasPerformedRequest) { $services = $this->persistServices(); $this->kernel = clone $this->kernel; } else { self::$hasPerformedRequest = true; } $this->kernel->boot(); $container = $this->kernel->getContainer(); if ($this->kernel->getContainer()->has('profiler')) { $container->get('profiler')->enable(); } $this->injectPersistedServices($services); return parent::doRequest($request); } /** * @param $services * @return array */ protected function persistServices() { $services = []; foreach ($this->persistentServices as $serviceName) { if (!$this->kernel->getContainer()->has($serviceName)) { continue; } $services[$serviceName] = $this->kernel->getContainer()->get($serviceName); } return $services; } /** * @param $services * @param $container */ protected function injectPersistedServices($services) { foreach ($services as $serviceName => $service) { $this->kernel->getContainer()->set($serviceName, $service); } } }
<?php namespace Codeception\Lib\Connector; class Symfony2 extends \Symfony\Component\HttpKernel\Client { private static $hasPerformedRequest; public $persistentServices = []; protected function doRequest($request) { $services = []; if (self::$hasPerformedRequest) { $services = $this->persistServices(); $this->kernel->shutdown(); } else { self::$hasPerformedRequest = true; } $this->kernel->boot(); $container = $this->kernel->getContainer(); if ($this->kernel->getContainer()->has('profiler')) { $container->get('profiler')->enable(); } $this->injectPersistedServices($services); return parent::doRequest($request); } /** * @param $services * @return array */ protected function persistServices() { $services = []; foreach ($this->persistentServices as $serviceName) { if (!$this->kernel->getContainer()->has($serviceName)) { continue; } $services[$serviceName] = $this->kernel->getContainer()->get($serviceName); } return $services; } /** * @param $services * @param $container */ protected function injectPersistedServices($services) { foreach ($services as $serviceName => $service) { $this->kernel->getContainer()->set($serviceName, $service); } } }
Fix users access zone comment description git-svn-id: 4cd2d1688610a87757c9f4de95975a674329c79f@1148 b8ca103b-dd03-488c-9448-c80b36131af2
<? $access_zone = $sub0; if($access_zone) $zone = sql::row("ks_access_zones", compact('access_zone')); if($action == "zone_manage") try { $data = array( 'access_zone' => $_POST['access_zone'], 'access_zone_parent' => $_POST['access_zone_parent'], 'zone_descr' => $_POST['zone_descr'], ); if(!$data['access_zone_parent']) //si la zone est racine $data['access_zone_parent'] = $data['access_zone']; if(!$zone){ if(sql::row("ks_access_zones", array('access_zone'=>$data['access_zone']))) throw rbx::error("Une zone du meme nom existe deja."); $res = sql::insert("ks_access_zones", $data); if(!$res) throw rbx::error("&err_sql;"); rbx::ok("Une nouvelle zone {$data['access_zone']} a été créée"); jsx::js_eval("Jsx.open('/?$href_fold/list', 'access_zone_box',this)"); jsx::$rbx = false; } else { sql::replace("ks_access_zones", $data, compact('access_zone')); rbx::ok("Modification enregistrées"); jsx::js_eval(jsx::PARENT_RELOAD); } }catch(rbx $e){rbx::error("Impossible de proceder à l'enregistrement de la zone.");}
<? $access_zone = $sub0; if($access_zone) $zone = sql::row("ks_access_zones", compact('access_zone')); if($action == "zone_manage") try { $data = array( 'access_zone' => $_POST['access_zone'], 'access_zone_parent' => $_POST['access_zone_parent'], 'zone_descr' => rte_clean($_POST['zone_descr']), ); if(!$data['access_zone_parent']) //si la zone est racine $data['access_zone_parent'] = $data['access_zone']; if(!$zone){ if(sql::row("ks_access_zones", array('access_zone'=>$data['access_zone']))) throw rbx::error("Une zone du meme nom existe deja."); $res = sql::insert("ks_access_zones", $data); if(!$res) throw rbx::error("&err_sql;"); rbx::ok("Une nouvelle zone {$data['access_zone']} a été créée"); jsx::js_eval("Jsx.open('/?$href_fold/list', 'access_zone_box',this)"); jsx::$rbx = false; } else { sql::replace("ks_access_zones", $data, compact('access_zone')); rbx::ok("Modification enregistrées"); jsx::js_eval(jsx::PARENT_RELOAD); } }catch(rbx $e){rbx::error("Impossible de proceder à l'enregistrement de la zone.");}
Change test due to change in default sort order.
package com.bbn.bue.common.diff; import com.bbn.bue.common.evaluation.FMeasureCounts; import com.google.common.collect.ImmutableMap; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; public class FMeasureTableRendererTest { @Test public void testFMeasureTableRenderer() { final FMeasureTableRenderer renderer = FMeasureTableRenderer.create(); final Map<String, FMeasureCounts> data = ImmutableMap.of( "foo", FMeasureCounts.from(1, 2, 3), "bar", FMeasureCounts.from(4, 5, 6)); final String expected= "Name TP FP FN P R F1\n"+ "===============================================================================\n"+ "bar 4.0 5.0 6.0 44.44 40.00 42.11\n"+ "foo 1.0 2.0 3.0 33.33 25.00 28.57\n"; final String result = renderer.render(data); assertEquals(expected, result); } }
package com.bbn.bue.common.diff; import com.bbn.bue.common.evaluation.FMeasureCounts; import com.google.common.collect.ImmutableMap; import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; public class FMeasureTableRendererTest { @Test public void testFMeasureTableRenderer() { final FMeasureTableRenderer renderer = FMeasureTableRenderer.create(); final Map<String, FMeasureCounts> data = ImmutableMap.of( "foo", FMeasureCounts.from(1, 2, 3), "bar", FMeasureCounts.from(4, 5, 6)); final String expected= "Name TP FP FN P R F1\n"+ "===============================================================================\n"+ "foo 1.0 2.0 3.0 33.33 25.00 28.57\n"+ "bar 4.0 5.0 6.0 44.44 40.00 42.11\n"; final String result = renderer.render(data); assertEquals(expected, result); } }
Make an anonymous JS func now named for re-usability.
'use strict'; // We assume this JS is sourced at the end of any HTML, avoiding the // need for a $(document).ready(…) call. But it really needs the // document fully loaded to operated properly. // TODO: put this in our own namespace, not in the window… common_init(); start_checking_for_needed_updates(); function update_needed() { console.log('update needed…') } function handle_modal(e) { e.preventDefault(); var url = $(this).attr('href'); if (url.indexOf('#') == 0) { $(url).modal('open'); } else { $.get(url, function(data) { $(data).modal().on("shown", function () { //$('input:visible:enabled:first').focus(); //$first_input.select(); var $first_input = $('input:visible:enabled').first(); $first_input.focus(function() { // OMG. Thanks http://stackoverflow.com/a/10576409/654755 this.selectionStart = this.selectionEnd = this.value.length; }); $first_input.focus(); }).on('hidden', function () { $(this).remove(); }); }); } } // Support for AJAX loaded modal window. // Focuses on first input textbox after it loads the window. $('[data-toggle="modal"]').click(handle_modal);
'use strict'; // We assume this JS is sourced at the end of any HTML, avoiding the // need for a $(document).ready(…) call. But it really needs the // document fully loaded to operated properly. // TODO: put this in our own namespace, not in the window… common_init(); start_checking_for_needed_updates(); function update_needed() { console.log('update needed…') } // Support for AJAX loaded modal window. // Focuses on first input textbox after it loads the window. $('[data-toggle="modal"]').click(function(e) { e.preventDefault(); var url = $(this).attr('href'); if (url.indexOf('#') == 0) { $(url).modal('open'); } else { $.get(url, function(data) { $(data).modal().on("shown", function () { //$('input:visible:enabled:first').focus(); //$first_input.select(); var $first_input = $('input:visible:enabled').first(); $first_input.focus(function() { // OMG. Thanks http://stackoverflow.com/a/10576409/654755 this.selectionStart = this.selectionEnd = this.value.length; }); $first_input.focus(); }).on('hidden', function () { $(this).remove(); }); }); } });
Add a wrapping div around control as a placeholder.
var Controls = Datagrid.Controls = Backbone.View.extend({ initialize: function() { this.pager = this.options.pager; this.left = this._resolveView(this.options.left); this.middle = this._resolveView(this.options.middle); this.right = this._resolveView(this.options.right); }, render: function() { this.$el.empty(); _.chain(['left', 'middle', 'right']) .filter(function(position) { return this[position]; }, this) .each(function(position) { $('<div></div>', {'class': 'control ' + position}) .append(this[position].render().el) .appendTo(this.$el); }, this); return this; }, remove: function() { Datagrid.__super__.remove.call(this); _.each(this.subviews, function(subview) { subview.remove(); }); return this; }, _resolveView: function(options) { if (!options) { return null; } var view; if (options.prototype && options.prototype.render) { view = options; options = {}; } // Resolve view from options else if (typeof options === 'object') { view = options.control; if (!view || !view.prototype || !view.prototype.render) { throw new TypeError('Invalid view passed to controls.'); } } else { throw new TypeError('Invalid view passed to controls.'); } _.extend(options, {pager: this.pager}); return new view(options); } });
var Controls = Datagrid.Controls = Backbone.View.extend({ initialize: function() { this.pager = this.options.pager; this.left = this._resolveView(this.options.left); this.middle = this._resolveView(this.options.middle); this.right = this._resolveView(this.options.right); }, render: function() { this.$el.empty(); _.chain(['left', 'middle', 'right']) .filter(function(position) { return this[position]; }, this) .each(function(position) { this.$el.append(this[position].render().el); }, this); return this; }, remove: function() { Datagrid.__super__.remove.call(this); _.each(this.subviews, function(subview) { subview.remove(); }); return this; }, _resolveView: function(options) { if (!options) { return null; } var view; if (options.prototype && options.prototype.render) { view = options; options = {}; } // Resolve view from options else if (typeof options === 'object') { view = options.control; if (!view || !view.prototype || !view.prototype.render) { throw new TypeError('Invalid view passed to controls.'); } } else { throw new TypeError('Invalid view passed to controls.'); } _.extend(options, {pager: this.pager}); return new view(options); } });
Make failIfDiff work with dict keys and values.
""" Code originally from: http://www.aminus.org/blogs/index.php/2009/01/09/assertnodiff """ import difflib from pprint import pformat class DiffTestCaseMixin(object): def get_diff_msg(self, first, second, fromfile='First', tofile='Second'): """Return a unified diff between first and second.""" # Force inputs to iterables for diffing. # use pformat instead of str or repr to output dicts and such # in a stable order for comparison. if isinstance(first, (tuple, list)): first = [pformat(d) for d in first] elif isinstance(first, dict): first = ["%s:%s" % (pformat(key), pformat(val)) for key,val in first.iteritems()] else: first = [pformat(first)] if isinstance(second, (tuple, list)): second = [pformat(d) for d in second] elif isinstance(second, dict): second = ["%s:%s" % (pformat(key), pformat(val)) for key,val in second.iteritems()] else: second = [pformat(second)] diff = difflib.unified_diff( first, second, fromfile=fromfile, tofile=tofile) # Add line endings. return '\n' + ''.join([d + '\n' for d in diff]) def failIfDiff(self, first, second, fromfile='First', tofile='Second'): """If not first == second, fail with a unified diff.""" if not first == second: msg = self.get_diff_msg(first, second, fromfile, tofile) raise self.failureException, msg
""" Code originally from: http://www.aminus.org/blogs/index.php/2009/01/09/assertnodiff """ import difflib from pprint import pformat class DiffTestCaseMixin(object): def get_diff_msg(self, first, second, fromfile='First', tofile='Second'): """Return a unified diff between first and second.""" # Force inputs to iterables for diffing. # use pformat instead of str or repr to output dicts and such # in a stable order for comparison. if isinstance(first, (tuple, list, dict)): first = [pformat(d) for d in first] else: first = [pformat(first)] if isinstance(second, (tuple, list, dict)): second = [pformat(d) for d in second] else: second = [pformat(second)] diff = difflib.unified_diff( first, second, fromfile=fromfile, tofile=tofile) # Add line endings. return ''.join([d + '\n' for d in diff]) def failIfDiff(self, first, second, fromfile='First', tofile='Second'): """If not first == second, fail with a unified diff.""" if not first == second: msg = self.get_diff_msg(first, second, fromfile, tofile) raise self.failureException, msg
Add more info log output Partial reimplementation of #39
"use strict"; const path = require("path"); const rollup = require("rollup"); function createPreprocessor(options, preconfig, basePath, logger) { const cache = new Map(); const log = logger.create("preprocessor.rollup"); return async function preprocess(original, file, done) { const location = path.relative(basePath, file.path); try { const config = Object.assign({}, options, preconfig.options, { input: file.path, cache: cache.get(file.path) }); const bundle = await rollup.rollup(config); cache.set(file.path, bundle.cache); log.info("Generating bundle for ./%s", location); const { output } = await bundle.generate(config); for (const result of output) { if (!result.isAsset) { const { code, map } = result; const { sourcemap } = config.output; file.sourceMap = map; const processed = sourcemap === "inline" ? code + `\n//# sourceMappingURL=${map.toUrl()}\n` : code; return done(null, processed); } } log.warn("Nothing was processed."); done(null, original); } catch (error) { log.error("Failed to process ./%s\n\n%s\n", location, error.stack); done(error, null); } }; } createPreprocessor.$inject = [ "config.rollupPreprocessor", "args", "config.basePath", "logger" ]; module.exports = { "preprocessor:rollup": ["factory", createPreprocessor] };
"use strict"; const path = require("path"); const rollup = require("rollup"); function createPreprocessor(options, preconfig, basePath, logger) { const cache = new Map(); const log = logger.create("preprocessor.rollup"); return async function preprocess(original, file, done) { try { const config = Object.assign({}, options, preconfig.options, { input: file.path, cache: cache.get(file.path) }); const bundle = await rollup.rollup(config); cache.set(file.path, bundle.cache); const { output } = await bundle.generate(config); for (const result of output) { if (!result.isAsset) { const { code, map } = result; const { sourcemap } = config.output; file.sourceMap = map; const processed = sourcemap === "inline" ? code + `\n//# sourceMappingURL=${map.toUrl()}\n` : code; return done(null, processed); } } log.warn("Nothing was processed."); done(null, original); } catch (error) { const location = path.relative(basePath, file.path); log.error("Failed to process ./%s\n\n%s\n", location, error.stack); done(error, null); } }; } createPreprocessor.$inject = [ "config.rollupPreprocessor", "args", "config.basePath", "logger" ]; module.exports = { "preprocessor:rollup": ["factory", createPreprocessor] };
Use class cache in factory
<?php namespace Jackalope; use InvalidArgumentException; use ReflectionClass; /** * Jackalope implementation factory. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License */ class Factory implements FactoryInterface { /** * @var array */ protected $classCache = array(); /** * @var array */ protected $reflectionCache = array(); /** * {@inheritDoc} */ public function get($name, array $params = array()) { if (isset($this->classCache[$name])) { $name = $this->classCache[$name]; } else { $originalName = $name; if (class_exists('Jackalope\\' . $name)) { $name = 'Jackalope\\' . $name; } elseif (! class_exists($name)) { throw new InvalidArgumentException("Neither class Jackalope\\$name nor class $name found. Please check your autoloader and the spelling of $name"); } $this->classCache[$originalName] = $name; } if (0 === strpos($name, 'Jackalope\\')) { array_unshift($params, $this); } if (! count($params)) { return new $name; } if (isset($this->reflectionCache[$name])) { $class = $this->reflectionCache[$name]; } else { $class = new ReflectionClass($name); $this->reflectionCache[$name] = $class; } return $class->newInstanceArgs($params); } }
<?php namespace Jackalope; use InvalidArgumentException; use ReflectionClass; /** * Jackalope implementation factory. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License */ class Factory implements FactoryInterface { /** * @var array */ protected $reflectionCache = array(); /** * {@inheritDoc} */ public function get($name, array $params = array()) { if (class_exists('Jackalope\\' . $name)) { $name = 'Jackalope\\' . $name; } elseif (! class_exists($name)) { throw new InvalidArgumentException("Neither class Jackalope\\$name nor class $name found. Please check your autoloader and the spelling of $name"); } if (0 === strpos($name, 'Jackalope\\')) { array_unshift($params, $this); } if (! count($params)) { return new $name; } if (isset($this->reflectionCache[$name])) { $class = $this->reflectionCache[$name]; } else { $class = new ReflectionClass($name); $this->reflectionCache[$name] = $class; } return $class->newInstanceArgs($params); } }
Set the correct prefix for searching places
define(["backbone", "underscore", "places/models/CategoryModel", "moxie.conf"], function(Backbone, _, Category, conf) { var CategoryCollection = Backbone.Collection.extend({ model: Category, url: conf.endpoint + conf.pathFor('places_categories'), parse: function(data) { var flattened_cats = []; function flatten_categories(prefix, depth, cats) { depth++; for (var i=0; i < cats.length; i++) { var cat_data = cats[i]; // Since the top level type is simply '/' we need this logic to stop us prefixing with '//' // TODO: Test var new_prefix = (prefix.length > 1) ? prefix + '/' + cat_data.type : prefix + cat_data.type; cat_data.type_prefixed = new_prefix; cat_data.depth = depth; if (cat_data.types) { cat_data.hasTypes = true; flatten_categories(new_prefix, depth, cat_data.types); } // Don't include the recursive structure in the models flattened_cats.push(_.omit(cat_data, ['types'])); } } data.type = data.type || '/'; flatten_categories('', 0, [data]); return flattened_cats; } }); return CategoryCollection; });
define(["backbone", "underscore", "places/models/CategoryModel", "moxie.conf"], function(Backbone, _, Category, conf) { var CategoryCollection = Backbone.Collection.extend({ model: Category, url: conf.endpoint + conf.pathFor('places_categories'), parse: function(data) { console.log(data); var flattened_cats = []; function flatten_categories(prefix, depth, cats) { depth++; for (var i=0; i < cats.length; i++) { var cat_data = cats[i]; var new_prefix = prefix + cat_data.type + '/'; cat_data.type_prefixed = new_prefix; cat_data.depth = depth; if (cat_data.types) { cat_data.hasTypes = true; flatten_categories(new_prefix, depth, cat_data.types); } // Don't include the recursive structure in the models flattened_cats.push(_.omit(cat_data, ['types'])); } } data.type = ''; flatten_categories('', 0, [data]); return flattened_cats; } }); return CategoryCollection; });
Rename default extension to `tpl`, shorter
var _ = require('underscore'); var fs = require('fs'); var path = require('path'); var cache = {}; // Set the default template extension. Override as necessary. _.templateExtension = 'tpl'; // Set the special express property for templating to work. _.__express = function (abs, options, cb) { var sync = !cb; try { // Helper function for sub-templating, store the original value for nested // sub-templates. var dir = path.dirname(abs); options.include = function (rel) { var resolved = path.resolve(dir, rel + '.' + _.templateExtension); var include = options.include; var str = _.__express(resolved, options); options.include = include; return str; }; // Check cache... var fn = options.cache && cache[abs]; if (!fn) { if (sync) { var data = fs.readFileSync(abs, 'utf8'); fn = cache[abs] = _.template(data, null, options); } else { return fs.readFile(abs, 'utf8', function (er, data) { if (er) return cb(er); fn = cache[abs] = _.template(data, null, options); cb(null, fn(options)); }); } } // Run and return template var str = fn(options); if (sync) return str; cb(null, str); } catch (er) { if (sync) throw er; cb(er); } };
var _ = require('underscore'); var fs = require('fs'); var path = require('path'); var cache = {}; // Set the default template extension. Override as necessary. _.templateExtension = 'underscore'; // Set the special express property for templating to work. _.__express = function (abs, options, cb) { var sync = !cb; try { // Helper function for sub-templating, store the original value for nested // sub-templates. var dir = path.dirname(abs); options.include = function (rel) { var resolved = path.resolve(dir, rel + '.' + _.templateExtension); var include = options.include; var str = _.__express(resolved, options); options.include = include; return str; }; // Check cache... var fn = options.cache && cache[abs]; if (!fn) { if (sync) { var data = fs.readFileSync(abs, 'utf8'); fn = cache[abs] = _.template(data, null, options); } else { return fs.readFile(abs, 'utf8', function (er, data) { if (er) return cb(er); fn = cache[abs] = _.template(data, null, options); cb(null, fn(options)); }); } } // Run and return template var str = fn(options); if (sync) return str; cb(null, str); } catch (er) { if (sync) throw er; cb(er); } };
Return code for about command
<?php namespace Distill\Cli\Command; use Distill\Distill; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class AboutCommand extends Command { /** * App version. * @var string */ protected $appVersion; /** * Constructor. * @param string $appVersion App version */ public function __construct($appVersion) { parent::__construct(); $this->appVersion = $appVersion; } /** * {@inheritdoc} */ protected function configure() { $this ->setName('about') ->setDescription('Extracts files from a compressed archive') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(sprintf("\n <info>Distill CLI</info> <comment>%s</comment>", $this->appVersion)); $output->writeln(" ~~~~~~~~~~~~~~~~~~~~"); $output->writeln(" Command line tool to extract files from compressed archives. Supports bz2, gz, phar, rar, tar, tar.bz2, tar.gz, tar.xz, 7z, xz and zip archives.\n"); $output->writeln(" Available commands:"); $output->writeln(" <info>extract <dir-name></info> Extracts files from compressed archives."); $output->writeln(" Example: <comment>$ distill-cli extract example.tar.gz example/</comment>\n"); return 0; } }
<?php namespace Distill\Cli\Command; use Distill\Distill; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class AboutCommand extends Command { /** * App version. * @var string */ protected $appVersion; /** * Constructor. * @param string $appVersion App version */ public function __construct($appVersion) { parent::__construct(); $this->appVersion = $appVersion; } /** * {@inheritdoc} */ protected function configure() { $this ->setName('about') ->setDescription('Extracts files from a compressed archive') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(sprintf("\n <info>Distill CLI</info> <comment>%s</comment>", $this->appVersion)); $output->writeln(" ~~~~~~~~~~~~~~~~~~~~"); $output->writeln(" Command line tool to extract files from compressed archives. Supports bz2, gz, phar, rar, tar, tar.bz2, tar.gz, tar.xz, 7z, xz and zip archives.\n"); $output->writeln(" Available commands:"); $output->writeln(" <info>extract <dir-name></info> Extracts files from compressed archives."); $output->writeln(" Example: <comment>$ distill-cli extract example.tar.gz example/</comment>\n"); } }
:green_heart: Fix broken input email test
'use strict'; const InputEmail = require('../../lib/install/input-email'); const InputEmailElement = require('../../lib/elements/atom/input-email-element'); describe('InputEmail', () => { let step, view, promise; beforeEach(() => { view = new InputEmailElement(); step = new InputEmail(view); }); describe('when started with an email', () => { beforeEach(() => { promise = step.start({email: '[email protected]'}); }); it('fills the input with the provided email', () => { expect(view.querySelector('input').value).toEqual('[email protected]'); }); describe('submitting the step', () => { it('resolves the pending promise', () => { view.form.dispatchEvent(new Event('submit')); waitsForPromise(() => promise.then(data => { expect(data.email).toEqual('[email protected]'); })); }); }); }); describe('when started without an email', () => { beforeEach(() => { promise = step.start(); }); it('leaves the input empty', () => { expect(view.querySelector('input').value).toEqual(''); }); describe('submitting the step without a valid email', () => { it('does not validate the form and reports an error', () => { const spy = jasmine.createSpy(); view.onDidSubmit(spy); view.submit.dispatchEvent(new Event('click')); expect(spy).not.toHaveBeenCalled(); expect(view.querySelector('input:invalid')).toExist(); }); }); }); });
'use strict'; const InputEmail = require('../../lib/install/input-email'); const InputEmailElement = require('../../lib/elements/atom/input-email-element'); describe('InputEmail', () => { let step, view, promise; beforeEach(() => { view = new InputEmailElement(); step = new InputEmail(view); }); describe('when started with an email', () => { beforeEach(() => { promise = step.start({email: '[email protected]'}); }); it('fills the input with the provided email', () => { expect(view.querySelector('input').value).toEqual('[email protected]'); }); describe('submitting the step', () => { it('resolves the pending promise', () => { view.submit.dispatchEvent(new Event('click')); waitsForPromise(() => promise.then(data => { expect(data.email).toEqual('[email protected]'); })); }); }); }); describe('when started without an email', () => { beforeEach(() => { promise = step.start(); }); it('leaves the input empty', () => { expect(view.querySelector('input').value).toEqual(''); }); describe('submitting the step without a valid email', () => { it('does not validate the form and reports an error', () => { const spy = jasmine.createSpy(); view.onDidSubmit(spy); view.submit.dispatchEvent(new Event('click')); expect(spy).not.toHaveBeenCalled(); expect(view.querySelector('input:invalid')).toExist(); }); }); }); });
[2.7][DX] Use constant message contextualisation for deprecations
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\PropertyAccess; /** * Entry point of the PropertyAccess component. * * @author Bernhard Schussek <[email protected]> */ final class PropertyAccess { /** * Creates a property accessor with the default configuration. * * @return PropertyAccessor */ public static function createPropertyAccessor() { return self::createPropertyAccessorBuilder()->getPropertyAccessor(); } /** * Creates a property accessor builder. * * @return PropertyAccessorBuilder */ public static function createPropertyAccessorBuilder() { return new PropertyAccessorBuilder(); } /** * Alias of {@link createPropertyAccessor}. * * @return PropertyAccessor * * @deprecated since version 2.3, to be removed in 3.0. * Use {@link createPropertyAccessor()} instead. */ public static function getPropertyAccessor() { @trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.3 and will be removed in 3.0. Use the createPropertyAccessor() method instead.', E_USER_DEPRECATED); return self::createPropertyAccessor(); } /** * This class cannot be instantiated. */ private function __construct() { } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\PropertyAccess; /** * Entry point of the PropertyAccess component. * * @author Bernhard Schussek <[email protected]> */ final class PropertyAccess { /** * Creates a property accessor with the default configuration. * * @return PropertyAccessor */ public static function createPropertyAccessor() { return self::createPropertyAccessorBuilder()->getPropertyAccessor(); } /** * Creates a property accessor builder. * * @return PropertyAccessorBuilder */ public static function createPropertyAccessorBuilder() { return new PropertyAccessorBuilder(); } /** * Alias of {@link createPropertyAccessor}. * * @return PropertyAccessor * * @deprecated since version 2.3, to be removed in 3.0. * Use {@link createPropertyAccessor()} instead. */ public static function getPropertyAccessor() { @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the createPropertyAccessor() method instead.', E_USER_DEPRECATED); return self::createPropertyAccessor(); } /** * This class cannot be instantiated. */ private function __construct() { } }
Use statement + output added
<?php namespace KevinVR\FootbelProcessorBundle\Command; use KevinVR\FootbelProcessorBundle\Processor\ResourceFileProcessor; use PhpAmqpLib\Message\AMQPMessage; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ResourceProcessorAllCommand extends ContainerAwareCommand { protected function configure() { $this->setName('resource:process:all'); } protected function execute(InputInterface $input, OutputInterface $output) { try { $queueworker = $this->getContainer()->get('rabbit_worker'); } catch (\Exception $e) { $output->writeln('Cannot connect to the queue!'); exit(1); } $em = $this->getContainer()->get('doctrine')->getManager(); $resourceRepository = $em->getRepository("FootbelBackendBundle:Resource"); $resources = $resourceRepository->findResourcesToProcess(); foreach ($resources as $resource) { $resourceFileProcessor = new ResourceFileProcessor( $resource, $queueworker, $em ); $resourceFileProcessor->process(); } $output->writeln('All resources processed!'); exit(0); } }
<?php namespace KevinVR\FootbelProcessorBundle\Command; use PhpAmqpLib\Message\AMQPMessage; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ResourceProcessorAllCommand extends ContainerAwareCommand { protected function configure() { $this->setName('resource:process:all'); } protected function execute(InputInterface $input, OutputInterface $output) { try { $queueworker = $this->getContainer()->get('rabbit_worker'); } catch (\Exception $e) { // @TODO: Logging! exit(1); } $em = $this->getContainer()->get('doctrine')->getManager(); $resourceRepository = $em->getRepository("FootbelBackendBundle:Resource"); $resources = $resourceRepository->findResourcesToProcess(); foreach ($resources as $resource) { $resourceFileProcessor = new ResourceFileProcessor( $resource, $queueworker, $em ); $resourceFileProcessor->process(); } exit(0); } }
Fix file-loader exclusion in react-app-rewire-less
const path = require('path'); const { getLoader } = require('react-app-rewired'); function createRewireLess(lessLoaderOptions = {}) { return function(config, env) { const lessExtension = /\.less$/; const fileLoader = getLoader( config.module.rules, rule => rule.loader && typeof rule.loader === 'string' && rule.loader.indexOf(`${path.sep}file-loader${path.sep}`) !== -1, ); fileLoader.exclude.push(lessExtension); const cssRules = getLoader( config.module.rules, rule => String(rule.test) === String(/\.css$/) ); let lessRules; if (env === 'production') { lessRules = { test: lessExtension, loader: [ // TODO: originally this part is wrapper in extract-text-webpack-plugin // which we cannot do, so some things like relative publicPath // will not work. // https://github.com/timarney/react-app-rewired/issues/33 ...cssRules.loader, { loader: 'less-loader', options: lessLoaderOptions } ] }; } else { lessRules = { test: lessExtension, use: [ ...cssRules.use, { loader: 'less-loader', options: lessLoaderOptions } ] }; } config.module.rules.push(lessRules); return config; }; } const rewireLess = createRewireLess(); rewireLess.withLoaderOptions = createRewireLess; module.exports = rewireLess;
const path = require('path'); const { getLoader } = require('react-app-rewired'); function createRewireLess(lessLoaderOptions = {}) { return function(config, env) { const lessExtension = /\.less$/; const fileLoader = getLoader( config.module.rules, rule => rule.loader && typeof rule.loader === 'string' && rule.loader.endsWith(`file-loader${path.sep}index.js`) ); fileLoader.exclude.push(lessExtension); const cssRules = getLoader( config.module.rules, rule => String(rule.test) === String(/\.css$/) ); let lessRules; if (env === 'production') { lessRules = { test: lessExtension, loader: [ // TODO: originally this part is wrapper in extract-text-webpack-plugin // which we cannot do, so some things like relative publicPath // will not work. // https://github.com/timarney/react-app-rewired/issues/33 ...cssRules.loader, { loader: 'less-loader', options: lessLoaderOptions } ] }; } else { lessRules = { test: lessExtension, use: [ ...cssRules.use, { loader: 'less-loader', options: lessLoaderOptions } ] }; } config.module.rules.push(lessRules); return config; }; } const rewireLess = createRewireLess(); rewireLess.withLoaderOptions = createRewireLess; module.exports = rewireLess;
Delete method added in FileObject
from irma.database.nosqlhandler import NoSQLDatabase from bson import ObjectId class FileObject(object): _uri = None _dbname = None _collection = None def __init__(self, dbname=None, id=None): if dbname: self._dbname = dbname self._dbfile = None if id: self._id = ObjectId(id) self.load() def _exists(self, hashvalue): db = NoSQLDatabase(self._dbname, self._uri) return db.exists_file(self._dbname, self._collection, hashvalue) def load(self): db = NoSQLDatabase(self._dbname, self._uri) self._dbfile = db.get_file(self._dbname, self._collection, self._id) def save(self, data, name): db = NoSQLDatabase(self._dbname, self._uri) self._id = db.put_file(self._dbname, self._collection, data, name, '', []) def delete(self): db = NoSQLDatabase(self._dbname, self._uri) db.remove(self._dbname, self._collection, self._id) @property def name(self): """Get the filename""" return self._dbfile.filename @property def length(self): """Get file length""" return self._dbfile_length @property def data(self): """Get the data""" return self._dbfile.read() @property def id(self): """Return str version of ObjectId""" if not self._id: return None else: return str(self._id)
from irma.database.nosqlhandler import NoSQLDatabase from bson import ObjectId class FileObject(object): _uri = None _dbname = None _collection = None def __init__(self, dbname=None, id=None): if dbname: self._dbname = dbname self._dbfile = None if id: self._id = ObjectId(id) self.load() def _exists(self, hashvalue): db = NoSQLDatabase(self._dbname, self._uri) return db.exists_file(self._dbname, self._collection, hashvalue) def load(self): db = NoSQLDatabase(self._dbname, self._uri) self._dbfile = db.get_file(self._dbname, self._collection, self._id) def save(self, data, name): db = NoSQLDatabase(self._dbname, self._uri) self._id = db.put_file(self._dbname, self._collection, data, name, '', []) @property def name(self): """Get the filename""" return self._dbfile.filename @property def length(self): """Get file length""" return self._dbfile_length @property def data(self): """Get the data""" return self._dbfile.read() @property def id(self): """Return str version of ObjectId""" if not self._id: return None else: return str(self._id)
Refactor introduction to make it the same as the other tests
"""" Introduction Adventure Author: Ignacio Avas ([email protected]) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" def __init__(self, candidate_code, file_name='<inline>'): """Init the test""" super(TestOutput, self).__init__() self.candidate_code = candidate_code self.file_name = file_name def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() @staticmethod def mock_print(stringy): "Mock function" pass def runTest(self): "Makes a simple test of the output" code = compile(self.candidate_code, self.file_name, 'exec', optimize=0) exec(code) self.assertEqual( self.__mockstdout.getvalue().lower().strip(), 'hello world', "Should have printed 'Hello World'" ) class Adventure(BaseAdventure): title = _('Introduction') @classmethod def test(cls, sourcefile): """Test against the provided file""" suite = unittest.TestSuite() raw_program = codecs.open(sourcefile).read() suite.addTest(TestOutput(raw_program, sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError()
"""" Introduction Adventure Author: Ignacio Avas ([email protected]) """ import codecs import io import sys import unittest from story.adventures import AdventureVerificationError, BaseAdventure from story.translation import gettext as _ class TestOutput(unittest.TestCase): "Introduction Adventure test" def __init__(self, sourcefile): "Inits the test" super(TestOutput, self).__init__() self.sourcefile = sourcefile def setUp(self): self.__old_stdout = sys.stdout sys.stdout = self.__mockstdout = io.StringIO() def tearDown(self): sys.stdout = self.__old_stdout self.__mockstdout.close() @staticmethod def mock_print(stringy): "Mock function" pass def runTest(self): "Makes a simple test of the output" raw_program = codecs.open(self.sourcefile).read() code = compile(raw_program, self.sourcefile, 'exec', optimize=0) exec(code) self.assertEqual( self.__mockstdout.getvalue().lower().strip(), 'hello world', "Should have printed 'Hello World'" ) class Adventure(BaseAdventure): "Introduction Adventure" title = _('Introduction') @classmethod def test(cls, sourcefile): "Test against the provided file" suite = unittest.TestSuite() suite.addTest(TestOutput(sourcefile)) result = unittest.TextTestRunner().run(suite) if not result.wasSuccessful(): raise AdventureVerificationError()
Allow for requirements without a hash
import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'.git(?=(#|$))', '.git@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'\@([0-9a-f]*)(?=(#|$))', '@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
Set up environment specific connection to rabbitmq
# -*- coding: utf-8 -*- import time import json import sys import pika import os from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection host = os.environ['CLOUDAMQP_URL'] connection = pika.BlockingConnection(pika.ConnectionParameters(host=host)) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
# -*- coding: utf-8 -*- import time import json import sys import pika from tweepy.streaming import StreamListener class Listener(StreamListener): def __init__(self): #setup rabbitMQ Connection connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = connection.channel() #set max queue size args = {"x-max-length": 2000} self.channel.queue_declare(queue='social_data', arguments=args) def on_data(self, data): try: data = json.loads(data) if data["text"]: self.verify(data) time.sleep(5) return True except BaseException, e: print("failed in ondata, ", str(e)) time.sleep(5) pass def on_error(self, status): print(status) def verify(self, data): print "Incoming tweet from " + data["user"]["screen_name"] tweet = data["text"] # enqueue the tweet self.channel.basic_publish(exchange='', routing_key='social_data', body=data["text"])
Set initial EVL applications query to month
define([ 'vehicle-licensing/collections/services', 'extensions/views/timeseries-graph/timeseries-graph', 'extensions/views/tabs', 'extensions/views/graph/headline', ], function (ServicesCollection, TimeseriesGraph, Tabs, Headline) { return function (selector, id, type) { if ($('.lte-ie8').length) { // do not attempt to show graphs in legacy IE return; } var serviceName = { 'sorn': 'Applications', 'tax-disc': 'Applications' }; var serviceCollection = new ServicesCollection([], { seriesList: [{ id: id, title: serviceName[type] }] }); serviceCollection.query.set('period', 'month'); serviceCollection.fetch(); new TimeseriesGraph({ el: $(selector), collection: serviceCollection }); var tabs = new Tabs({ el: $(selector + '-nav'), model: serviceCollection.query, attr: 'period', tabs: [ {id: "month", name: "Monthly"}, {id: "week", name: "Weekly"} ] }); tabs.render(); var headline = new Headline({ el: $(selector + '-headline'), model: serviceCollection.query, prefix: 'Applications' }); headline.render(); }; });
define([ 'vehicle-licensing/collections/services', 'extensions/views/timeseries-graph/timeseries-graph', 'extensions/views/tabs', 'extensions/views/graph/headline', ], function (ServicesCollection, TimeseriesGraph, Tabs, Headline) { return function (selector, id, type) { if ($('.lte-ie8').length) { // do not attempt to show graphs in legacy IE return; } var serviceName = { 'sorn': 'Applications', 'tax-disc': 'Applications' }; var serviceCollection = new ServicesCollection([], { seriesList: [{ id: id, title: serviceName[type] }] }); serviceCollection.query.set('period', 'week'); serviceCollection.fetch(); new TimeseriesGraph({ el: $(selector), collection: serviceCollection }); var tabs = new Tabs({ el: $(selector + '-nav'), model: serviceCollection.query, attr: 'period', tabs: [ {id: "month", name: "Monthly"}, {id: "week", name: "Weekly"} ] }); tabs.model.set(tabs.attr, "month"); // Default to monthly tab tabs.render(); var headline = new Headline({ el: $(selector + '-headline'), model: serviceCollection.query, prefix: 'Applications' }); headline.render(); }; });
Split input text on init
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: self.text = tab_separated_text self.__raise_error_if_carriage_returns() else: self.text = tab_separated_text self.__create_internal_structure() @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.__rows) def __iter__ (self): return iter(self.__rows) def __getitem__ (self, key): return self.__rows[key] def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) def __raise_error_if_carriage_returns (self): if "\r" in self.text: raise self.InputStrContainsCarriageReturn def __create_internal_structure (self): if self.text: self.__rows = [tuple(r.split("\t")) for r in self.text.rstrip("\n").split("\n")] else: self.__rows = []
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class Table: class InputStrContainsCarriageReturn (RuntimeError): pass def __init__ (self, tab_separated_text = None): if tab_separated_text: self.text = tab_separated_text.rstrip("\n") self.__raise_error_if_carriage_returns() else: self.text = tab_separated_text @property def rows (self): return len(self) @property def cols (self): return len(self.text.split("\n")[0].split("\t")) if self.text else 0 def __len__ (self): return len(self.text.split("\n")) if self.text else 0 def __iter__ (self): if self.text: for row in self.text.split("\n"): yield(tuple(row.split("\t"))) else: return iter(()) def __getitem__ (self, key): if self.text: return tuple(self.text.split("\n")[key].split("\t")) else: raise IndexError def __repr__ (self): return "<{} {}>".format(self.__class__.__name__, repr(self.text)) def __raise_error_if_carriage_returns (self): if "\r" in self.text: raise self.InputStrContainsCarriageReturn
Change test because yes/no fits better for checkbox FormDynamic-code changed because checkbox in german added "Am" instead of "Yes". This updates the test to fit the new text.
<?php /** * @group Kwc_FormDynamic */ class Kwc_FormDynamic_Basic_Test extends Kwc_TestAbstract { public function setUp() { parent::setUp('Kwc_FormDynamic_Basic_Root'); } public function testIt() { $c = $this->_root->getComponentById('root_form-form')->getComponent(); $postData = array( 'form_root_form-paragraphs-1' => '', 'form_root_form-paragraphs-2' => 'asdfasdf', 'form_root_form-paragraphs-3' => '', 'form_root_form-paragraphs-4' => 'Def', 'form_root_form-paragraphs-5-post' => '1', 'form_root_form-paragraphs-6' => 'on', 'form_root_form-paragraphs-6-post' => '1', 'root_form-form' => 'submit', 'root_form-form-post' => 'post', ); $c->processInput($postData); $this->assertEquals($c->getErrors(), array()); $row = $c->getFormRow(); $text = $row->sent_mail_content_text; $this->assertContains('Required: asdfasdf', $text); $this->assertContains('Check: No', $text); $this->assertContains('CheckDefault: Yes', $text); } }
<?php /** * @group Kwc_FormDynamic */ class Kwc_FormDynamic_Basic_Test extends Kwc_TestAbstract { public function setUp() { parent::setUp('Kwc_FormDynamic_Basic_Root'); } public function testIt() { $c = $this->_root->getComponentById('root_form-form')->getComponent(); $postData = array( 'form_root_form-paragraphs-1' => '', 'form_root_form-paragraphs-2' => 'asdfasdf', 'form_root_form-paragraphs-3' => '', 'form_root_form-paragraphs-4' => 'Def', 'form_root_form-paragraphs-5-post' => '1', 'form_root_form-paragraphs-6' => 'on', 'form_root_form-paragraphs-6-post' => '1', 'root_form-form' => 'submit', 'root_form-form-post' => 'post', ); $c->processInput($postData); $this->assertEquals($c->getErrors(), array()); $row = $c->getFormRow(); $text = $row->sent_mail_content_text; $this->assertContains('Required: asdfasdf', $text); $this->assertContains('Check: off', $text); $this->assertContains('CheckDefault: on', $text); } }
Fix double space in doc string. Refs #9995
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Routing\Exception; use Cake\Core\Exception\Exception; /** * Exception raised when a URL cannot be reverse routed * or when a URL cannot be parsed. */ class MissingRouteException extends Exception { /** * {@inheritDoc} */ protected $_messageTemplate = 'A route matching "%s" could not be found.'; /** * Message template to use when the requested method is included. * * @var string */ protected $_messageTemplateWithMethod = 'A "%s" route matching "%s" could not be found.'; /** * {@inheritDoc} */ public function __construct($message, $code = 404) { if (is_array($message)) { if (isset($message['message'])) { $this->_messageTemplate = $message['message']; } elseif (isset($message['method']) && $message['method']) { $this->_messageTemplate = $this->_messageTemplateWithMethod; } } parent::__construct($message, $code); } }
<?php /** * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @since 3.0.0 * @license http://www.opensource.org/licenses/mit-license.php MIT License */ namespace Cake\Routing\Exception; use Cake\Core\Exception\Exception; /** * Exception raised when a URL cannot be reverse routed * or when a URL cannot be parsed. */ class MissingRouteException extends Exception { /** * {@inheritDoc} */ protected $_messageTemplate = 'A route matching "%s" could not be found.'; /** * Message template to use when the requested method is included. * * @var string */ protected $_messageTemplateWithMethod = 'A "%s" route matching "%s" could not be found.'; /** * {@inheritDoc} */ public function __construct($message, $code = 404) { if (is_array($message)) { if (isset($message['message'])) { $this->_messageTemplate = $message['message']; } elseif (isset($message['method']) && $message['method']) { $this->_messageTemplate = $this->_messageTemplateWithMethod; } } parent::__construct($message, $code); } }
Exclude some no longer relevant categories
<?php get_header(); if (have_posts()) { while (have_posts()) { the_post(); ?> <div class="blogPost"> <?php the_content(); ?> <?php if (is_page("tags")) { ?> <ul class="tagList"> <?php wp_list_categories( array( "hierarchical" => 1, "title_li" => __(""), "show_count" => 1, "depth" => 0, "exclude" => "1,2,6,7,9,10,11,19,72,100,104,148" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "yearly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "monthly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "daily" ) ); ?> </ul> <?php } ?> </div> <?php } } get_footer(); ?>
<?php get_header(); if (have_posts()) { while (have_posts()) { the_post(); ?> <div class="blogPost"> <?php the_content(); ?> <?php if (is_page("tags")) { ?> <ul class="tagList"> <?php wp_list_categories( array( "hierarchical" => 1, "title_li" => __(""), "show_count" => 1, "depth" => 0, "exclude" => "1,7,9,11,19,100,104,148" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "yearly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "monthly" ) ); ?> </ul> <ul class="tagList"> <?php wp_get_archives( array( "type" => "daily" ) ); ?> </ul> <?php } ?> </div> <?php } } get_footer(); ?>
Use relative import for default settings
# -*- coding: utf8 -*- """ LibCrowdsData ------------- Global data repository page for LibCrowds. """ import os import json from . import default_settings from flask import current_app as app from flask.ext.plugins import Plugin __plugin__ = "LibCrowdsData" __version__ = json.load(open(os.path.join(os.path.dirname(__file__), 'info.json')))['version'] class LibCrowdsData(Plugin): """Libcrowds data plugin class.""" def setup(self): """Setup the plugin.""" self.load_config() self.setup_blueprint() def load_config(self): """Configure the plugin.""" settings = [key for key in dir(default_settings) if key.isupper()] for s in settings: if not app.config.get(s): app.config[s] = getattr(default_settings, s) def setup_blueprint(self): """Setup blueprint.""" from .blueprint import DataBlueprint here = os.path.dirname(os.path.abspath(__file__)) template_folder = os.path.join(here, 'templates') static_folder = os.path.join(here, 'static') blueprint = DataBlueprint(template_folder=template_folder, static_folder=static_folder) app.register_blueprint(blueprint, url_prefix="/data")
# -*- coding: utf8 -*- """ LibCrowdsData ------------- Global data repository page for LibCrowds. """ import os import json import default_settings from flask import current_app as app from flask.ext.plugins import Plugin __plugin__ = "LibCrowdsData" __version__ = json.load(open(os.path.join(os.path.dirname(__file__), 'info.json')))['version'] class LibCrowdsData(Plugin): """Libcrowds data plugin class.""" def setup(self): """Setup the plugin.""" self.load_config() self.setup_blueprint() def load_config(self): """Configure the plugin.""" settings = [key for key in dir(default_settings) if key.isupper()] for s in settings: if not app.config.get(s): app.config[s] = getattr(default_settings, s) def setup_blueprint(self): """Setup blueprint.""" from .blueprint import DataBlueprint here = os.path.dirname(os.path.abspath(__file__)) template_folder = os.path.join(here, 'templates') static_folder = os.path.join(here, 'static') blueprint = DataBlueprint(template_folder=template_folder, static_folder=static_folder) app.register_blueprint(blueprint, url_prefix="/data")
Fix where uri path is empty
<?php namespace Web\Route\Rules; use Web\Route\Abstraction\AbstractRule; class UriRule extends AbstractRule { /** * Count the number of pattern segments for this rule. */ public function complexity() { return substr_count($this->pattern, '/'); } /** * @return string */ protected function resolveExpressionFromPattern() { $parts = explode('/', $this->pattern); foreach ($parts as &$part) { $match = array(); if (preg_match('/^(\:|\?)([a-z_]{1}[a-z\d\-_]*)$/i', $part, $match)) { $optional = $match[1] === '?' ? '?' : ''; $name = $match[2]; $this->params[$name] = ''; $part = '([^\/\?]+)' . $optional; $this->captureKeys[] = $name; } else { $part = preg_quote($part, '/'); } } return '/^' . implode('\/', $parts) . '(?:\/([^\/\?]+))*(?:\?.+)?$/i'; } /** * @param string $value * * @return string */ public function clean($value) { return '/' . ltrim(filter_var(urldecode($value), FILTER_SANITIZE_STRING), '/'); } /** * @param string $value * * @return string */ public function validate($value) { return $value; } }
<?php namespace Web\Route\Rules; use Web\Route\Abstraction\AbstractRule; class UriRule extends AbstractRule { /** * Count the number of pattern segments for this rule. */ public function complexity() { return substr_count($this->pattern, '/'); } /** * @return string */ protected function resolveExpressionFromPattern() { $parts = explode('/', $this->pattern); foreach ($parts as &$part) { $match = array(); if (preg_match('/^(\:|\?)([a-z_]{1}[a-z\d\-_]*)$/i', $part, $match)) { $optional = $match[1] === '?' ? '?' : ''; $name = $match[2]; $this->params[$name] = ''; $part = '([^\/\?]+)' . $optional; $this->captureKeys[] = $name; } else { $part = preg_quote($part, '/'); } } return '/^' . implode('\/', $parts) . '(?:\/([^\/\?]+))*(?:\?.+)?$/i'; } /** * @param string $value * * @return string */ public function clean($value) { return filter_var(urldecode($value), FILTER_SANITIZE_STRING); } /** * @param string $value * * @return string */ public function validate($value) { return $value; } }
Allow either a string (a (relative) url) or <link href> object passed to the exhibit json importer.
/*================================================== * Exhibit.ExhibitJSONImporter *================================================== */ Exhibit.ExhibitJSONImporter = { }; Exhibit.importers["application/json"] = Exhibit.ExhibitJSONImporter; Exhibit.ExhibitJSONImporter.load = function(link, database, cont) { var url = typeof link == "string" ? link : link.href; url = Exhibit.Persistence.resolveURL(url); var fError = function(statusText, status, xmlhttp) { Exhibit.UI.hideBusyIndicator(); Exhibit.UI.showHelp(Exhibit.l10n.failedToLoadDataFileMessage(url)); if (cont) cont(); }; var fDone = function(xmlhttp) { Exhibit.UI.hideBusyIndicator(); try { var o = null; try { o = eval("(" + xmlhttp.responseText + ")"); } catch (e) { Exhibit.UI.showJsonFileValidation(Exhibit.l10n.badJsonMessage(url, e), url); } if (o != null) { database.loadData(o, Exhibit.Persistence.getBaseURL(url)); } } catch (e) { SimileAjax.Debug.exception("Error loading Exhibit JSON data from " + url, e); } finally { if (cont) cont(); } }; Exhibit.UI.showBusyIndicator(); SimileAjax.XmlHttp.get(url, fError, fDone); };
/*================================================== * Exhibit.ExhibitJSONImporter *================================================== */ Exhibit.ExhibitJSONImporter = { }; Exhibit.importers["application/json"] = Exhibit.ExhibitJSONImporter; Exhibit.ExhibitJSONImporter.load = function(link, database, cont) { var url = Exhibit.Persistence.resolveURL(link.href); var fError = function(statusText, status, xmlhttp) { Exhibit.UI.hideBusyIndicator(); Exhibit.UI.showHelp(Exhibit.l10n.failedToLoadDataFileMessage(url)); if (cont) cont(); }; var fDone = function(xmlhttp) { Exhibit.UI.hideBusyIndicator(); try { var o = null; try { o = eval("(" + xmlhttp.responseText + ")"); } catch (e) { Exhibit.UI.showJsonFileValidation(Exhibit.l10n.badJsonMessage(url, e), url); } if (o != null) { database.loadData(o, Exhibit.Persistence.getBaseURL(url)); } } catch (e) { SimileAjax.Debug.exception("Error loading Exhibit JSON data from " + url, e); } finally { if (cont) cont(); } }; Exhibit.UI.showBusyIndicator(); SimileAjax.XmlHttp.get(url, fError, fDone); };
Update results on situation change in IE Partial fix of #106 Still need to update the UI
'use strict'; angular.module('ddsApp').service('ResultatService', function($http, droitsDescription) { // Si la valeur renvoyée par l'API vaut null, cela signifie par convention que l'aide a été injectée et non recaculée par le simulateur function sortDroits(droitsCalcules) { var droitsEligibles = {}, droitsInjectes = {}, droitsNonEligibles = {}; _.forEach(droitsDescription, function(description, droitKey) { if (droitsCalcules[droitKey]) { droitsEligibles[droitKey] = description; droitsEligibles[droitKey].montant = droitsCalcules[droitKey]; } else if (droitsCalcules[droitKey] === null) { droitsInjectes[droitKey] = description; } else { droitsNonEligibles[droitKey] = description; } }); return { droitsEligibles: droitsEligibles, droitsInjectes: droitsInjectes, droitsNonEligibles: droitsNonEligibles }; } return { simulate: function(situation) { return $http.get('/api/situations/' + situation._id + '/simulation', { params: { cacheBust: Date.now() } }).then(function(response) { return sortDroits(response.data); }); }, sortDroits: sortDroits }; });
'use strict'; angular.module('ddsApp').service('ResultatService', function($http, droitsDescription) { // Si la valeur renvoyée par l'API vaut null, cela signifie par convention que l'aide a été injectée et non recaculée par le simulateur function sortDroits(droitsCalcules) { var droitsEligibles = {}, droitsInjectes = {}, droitsNonEligibles = {}; _.forEach(droitsDescription, function(description, droitKey) { if (droitsCalcules[droitKey]) { droitsEligibles[droitKey] = description; droitsEligibles[droitKey].montant = droitsCalcules[droitKey]; } else if (droitsCalcules[droitKey] === null) { droitsInjectes[droitKey] = description; } else { droitsNonEligibles[droitKey] = description; } }); return { droitsEligibles: droitsEligibles, droitsInjectes: droitsInjectes, droitsNonEligibles: droitsNonEligibles }; } return { simulate: function(situation) { return $http.get('/api/situations/' + situation._id + '/simulation').then(function(response) { return sortDroits(response.data); }); }, sortDroits: sortDroits }; });
Set default page size to 10 events.
import React from 'react' import EventBets from '../templates/event-bets' import EventHeading from '../templates/event-heading' import styles from './index.module.styl' export default ({ data }) => ( <ol className={styles['events-list']}> { data.allMongodbPlacardDevEvents.edges.map(({ node }, idx) => ( <li key={idx} className={styles['event-item']}> <EventHeading event={node} /> <EventBets betTypes={node.betTypes} /> </li> )) } </ol> ) export const query = graphql` query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 10) { allMongodbPlacardDevEvents( filter: { sport: { eq: $sport }, country: { eq: $country } }, sort: { fields: [date], order: ASC }, skip: $skip, limit: $limit ) { edges { node { code home away date sport country competition betTypes { name options { name value } } } } } } `
import React from 'react' import EventBets from '../templates/event-bets' import EventHeading from '../templates/event-heading' import styles from './index.module.styl' export default ({ data }) => ( <ol className={styles['events-list']}> { data.allMongodbPlacardDevEvents.edges.map(({ node }, idx) => ( <li key={idx} className={styles['event-item']}> <EventHeading event={node} /> <EventBets betTypes={node.betTypes} /> </li> )) } </ol> ) export const query = graphql` query EventsListQuery($sport: String, $country: String, $skip: Int = 0, $limit: Int = 20) { allMongodbPlacardDevEvents( filter: { sport: { eq: $sport }, country: { eq: $country } }, sort: { fields: [date], order: ASC }, skip: $skip, limit: $limit ) { edges { node { code home away date sport country competition betTypes { name options { name value } } } } } } `
Reset image, even after error
$('#tiny_inner_image').bind('change', function (event) { formElement = document.getElementById("tinymce_file_uploader"); data = new FormData(formElement); ed = tinymce.get('news_type_text'); var tmpMsg = flashes.info('', 'Bild wird hochgeladen'); ed.getBody().setAttribute('contenteditable', 'false'); var tinyContainer = $('.mce-tinymce.mce-container.mce-panel'); tinyContainer.css({opacity: 0.5}); $.ajax({ url: $('#tinymce_file_uploader').attr('action'), type: 'POST', data: data, contentType: false, processData: false, success: function (response) { if (typeof(tinymce) != 'undefined') { ed.selection.setContent(response); flashes.success('', 'Bild wurde hochgeladen'); } }, error: function (response) { if (response.status == 400) { flashes.danger('', response.responseText); } else { flashes.danger('', 'Bild konnte nicht hochgeladen werden'); } }, complete: function () { $('#tiny_inner_image').closest('form').get(0).reset(); ed.getBody().setAttribute('contenteditable', 'true'); tmpMsg.alert('close'); tinyContainer.css({opacity: 1}); } }); });
$('#tiny_inner_image').bind('change', function (event) { formElement = document.getElementById("tinymce_file_uploader"); data = new FormData(formElement); ed = tinymce.get('news_type_text'); var tmpMsg = flashes.info('', 'Bild wird hochgeladen'); ed.getBody().setAttribute('contenteditable', 'false'); var tinyContainer = $('.mce-tinymce.mce-container.mce-panel'); tinyContainer.css({opacity: 0.5}); $.ajax({ url: $('#tinymce_file_uploader').attr('action'), type: 'POST', data: data, contentType: false, processData: false, success: function (response) { if (typeof(tinymce) != 'undefined') { ed.selection.setContent(response); // Remove uploaded image, so it is possibly to reupload the same $('#tiny_inner_image').closest('form').get(0).reset(); flashes.success('', 'Bild wurde hochgeladen'); } }, error: function (response) { if (response.status == 400) { flashes.danger('', response.responseText); } else { flashes.danger('', 'Bild konnte nicht hochgeladen werden'); } }, complete: function () { ed.getBody().setAttribute('contenteditable', 'true'); tmpMsg.alert('close'); tinyContainer.css({opacity: 1}); } }); });
Add actual image rather than link to travis
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; var schema = Schema.create(); scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
// https://github.com/json-schema/JSON-Schema-Test-Suite/blob/develop/tests/draft4/required.json var scenerios = [ { "description": "required validation", "schema": { "properties": { "foo": {}, "bar": {} }, "required": ["foo"] }, "tests": [ { "description": "present required property is valid", "data": {"foo": 1}, "valid": true }, { "description": "non-present required property is invalid", "data": {"bar": 1}, "valid": false } ] }, { "description": "required default validation", "schema": { "properties": { "foo": {} } }, "tests": [ { "description": "not required by default", "data": {}, "valid": true } ] } ]; import { test } from 'ember-qunit'; import Schema from 'ember-cli-json-schema/schema'; scenerios.map(function(scenerio){ module(scenerio.description); scenerio.tests.map(function(_test){ test(_test.description, function() { var schema = Schema.create(); schema.load("test", scenerio.schema); var obj = schema.createObject("test", _test.data); equal(obj.get('isValid'), _test.valid); }); }); });
Add more unit test cases
package org.pdxfinder.services.constants; import org.junit.Test; import org.pdxfinder.BaseTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DataUrlTest extends BaseTest { private final static String ASSERTION_ERROR = "Unknown Data Url Found: "; @Test public void given_DataUrlEnumListCount_EnsureListIntegrity() { final int DATA_URL_COUNT = 3; assertEquals(DATA_URL_COUNT, DataUrl.values().length); } @Test public void given_DataUrl_When_EnumListIsChanged_Then_Error() { boolean expected = true; String message = ""; for (DataUrl option : DataUrl.values()) { switch (option) { case HUGO_FILE_URL: break; case DISEASES_BRANCH_URL: break; case ONTOLOGY_URL: break; default: message = String.format("%s %s", ASSERTION_ERROR, option); expected = false; } assertTrue(message, expected); } } }
package org.pdxfinder.services.constants; import org.junit.Test; import org.pdxfinder.BaseTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DataUrlTest extends BaseTest { private final static String ASSERTION_ERROR = "Unknown Data Url Found: "; @Test public void given_DataUrlEnumListCount_EnsureListIntegrity() { final int DATA_URL_COUNT = 8; assertEquals(DATA_URL_COUNT, DataUrl.values().length); } @Test public void given_DataUrl_When_EnumListIsChanged_Then_Error() { boolean expected = true; String message = ""; for (DataUrl option : DataUrl.values()) { switch (option) { case HUGO_FILE_URL: break; case DISEASES_BRANCH_URL: break; case ONTOLOGY_URL: break; default: message = String.format("%s %s", ASSERTION_ERROR, option); expected = false; } assertTrue(message, expected); } } }
Enable hover table styling only if row click handler is defined
import cc from 'classcat' import React from 'react' import PropTypes from 'prop-types' import './style.scss' function DataTable ({ className, click, cols, records }) { if (!cols.length) { return null } const tableClassName = cc([ 'table', 'table-bordered', { 'table-hover': !!click }, 'DataTable', className ]) return ( <div className="table-responsive"> <table className={tableClassName}> <thead> <tr> {cols.map(({ classes, title }, index) => ( <th key={index} className={classes} scope="col" > {title} </th> ))} </tr> </thead> <tbody> {records.map((row, index) => ( <tr key={index} onClick={() => click && click(row, index)} className="DataTable__row" > {cols.map(({ classes, value }, colIndex) => ( <td key={colIndex} className={classes}>{value(row)}</td> ))} </tr> ))} </tbody> </table> </div> ) } DataTable.propTypes = { className: PropTypes.string, click: PropTypes.func, cols: PropTypes.arrayOf(PropTypes.object), records: PropTypes.arrayOf(PropTypes.object) } DataTable.defaultProps = { className: undefined, click: undefined, cols: [], records: [] } export default DataTable
import cc from 'classcat' import React from 'react' import PropTypes from 'prop-types' import './style.scss' function DataTable ({ className, click, cols, records }) { if (!cols.length) { return null } const tableClassName = cc([ 'table', 'table-bordered', 'table-hover', 'DataTable', className ]) return ( <div className="table-responsive"> <table className={tableClassName}> <thead> <tr> {cols.map(({ classes, title }, index) => ( <th key={index} className={classes} scope="col" > {title} </th> ))} </tr> </thead> <tbody> {records.map((row, index) => ( <tr key={index} onClick={() => click && click(row, index)} className="DataTable__row" > {cols.map(({ classes, value }, colIndex) => ( <td key={colIndex} className={classes}>{value(row)}</td> ))} </tr> ))} </tbody> </table> </div> ) } DataTable.propTypes = { className: PropTypes.string, click: PropTypes.func, cols: PropTypes.arrayOf(PropTypes.object), records: PropTypes.arrayOf(PropTypes.object) } DataTable.defaultProps = { className: undefined, click: undefined, cols: [], records: [] } export default DataTable
Remove config access from buildCommand
<?php namespace Lawstands\Hermes; class Channel { /** * Channel command. * * @var $command */ private $command; /** * Channel constructor. * @param array $config * @param $data * @param bool $async */ public function __construct(array $config, $data, $async = true) { $data = self::formatData($data, $config['formatter']); $this->buildCommand($config['type'], $config['path'], $data, $async); } /** * Execute channel command. * * @return string */ public function execute() { return shell_exec($this->command); } /** * Build channel command. * * @param $type * @param $path * @param $data * @param $async * @return string */ private function buildCommand($type, $path, $data, $async) { $redirect = $async ? '&>/dev/null' : ''; $this->command = "{$type} {$path} {$data} {$redirect}"; } /** * Format channel data. * * @param $data * @param $formatter * @return mixed */ private static function formatData($data, $formatter) { $formatter = new $formatter; return $formatter->format($data); } }
<?php namespace Lawstands\Hermes; class Channel { /** * Channel command. * * @var $command */ private $command; /** * Channel constructor. * @param array $config * @param $data * @param bool $async */ public function __construct(array $config, $data, $async = true) { $data = self::formatData($data, $config['formatter']); $this->buildCommand($config, $data, $async); } /** * Execute channel command. * * @return string */ public function execute() { return shell_exec($this->command); } /** * Build channel command. * * @param $config * @param $data * @param $async * @return string */ private function buildCommand($config, $data, $async) { $redirect = $async ? '&>/dev/null' : ''; $this->command = "{$config['type']} {$config['path']} {$data} {$redirect}"; } /** * Format channel data. * * @param $data * @param $formatter * @return mixed */ private static function formatData($data, $formatter) { $formatter = new $formatter; return $formatter->format($data); } }
Remove redundant and incorrect test
<?php namespace Mockery\Generator\StringManipulation\Pass; use Mockery as m; use Mockery\Generator\StringManipulation\Pass\ClassNamePass; use Mockery\Generator\MockConfiguration; class ClassNamePassTest extends \PHPUnit_Framework_TestCase { const CODE = "namespace Mockery; class Mock {}"; public function setup() { $this->pass = new ClassNamePass(); } /** * @test */ public function shouldRemoveNamespaceDefinition() { $config = new MockConfiguration; $code = $this->pass->apply(static::CODE, $config); $this->assertNotContains('namespace Mockery;', $code); } /** * @test */ public function shouldReplaceNamespaceIfClassNameIsNamespaced() { $config = new MockConfiguration(); $config->setName("Dave\Dave"); $code = $this->pass->apply(static::CODE, $config); $this->assertNotContains('namespace Mockery;', $code); $this->assertContains('namespace Dave;', $code); } /** * @test */ public function shouldReplaceClassNameWithSpecifiedName() { $config = new MockConfiguration(); $config->setName("Dave"); $code = $this->pass->apply(static::CODE, $config); $this->assertContains('class Dave', $code); } }
<?php namespace Mockery\Generator\StringManipulation\Pass; use Mockery as m; use Mockery\Generator\StringManipulation\Pass\ClassNamePass; use Mockery\Generator\MockConfiguration; class ClassNamePassTest extends \PHPUnit_Framework_TestCase { const CODE = "namespace Mockery; class Mock {}"; public function setup() { $this->pass = new ClassNamePass(); } /** * @test */ public function shouldRemoveNamespaceDefinition() { $config = new MockConfiguration; $code = $this->pass->apply(static::CODE, $config); $this->assertNotContains('namespace Mockery;', $code); } /** * @test */ public function shouldReplaceNamespaceIfClassNameIsNamespaced() { $config = new MockConfiguration(); $config->setName("Dave\Dave"); $code = $this->pass->apply(static::CODE, $config); $this->assertNotContains('namespace Mockery;', $code); $this->assertContains('namespace Dave;', $code); } /** * @test */ public function shouldReplaceClassNameWithSpecifiedName() { $config = new MockConfiguration(); $config->setName("Dave"); $code = $this->pass->apply(static::CODE, $config); $this->assertContains('class Dave', $code); } /** * @test */ public function shouldReplaceClassNameWithGeneratedNameIfNotSpecified() { $config = m::mock("Mockery\Generator\MockConfiguration", array( "generateName" => "Dave", ))->shouldIgnoreMissing(); $code = $this->pass->apply(static::CODE, $config); $this->assertContains('class Dave', $code); } }
Make sure javascript gets minified every time the build runs.
/** * grunt * CoffeeScript example */ module.exports = function(grunt){ grunt.initConfig({ lint: { files: ['grunt.js', 'src/*.js'] }, coffee: { compile: { options: { bare: true }, files: { 'src/sidetap_loader.js': 'src/coffee/sidetap_loader.coffee', 'src/sidetap_standard.js': 'src/coffee/sidetap_standard.coffee', 'src/sidetap_ios.js': 'src/coffee/sidetap_ios.coffee', 'src/sidetap.js': ['src/coffee/sidetap_standard.coffee','src/coffee/sidetap_ios.coffee','src/coffee/sidetap_loader.coffee'] } } }, less: { compile: { files: { 'src/sidetap.css': 'src/less/sidetap.less' } } }, watch: { dist1: { files: 'src/coffee/*', tasks: 'coffee min' }, dist2: { files: 'src/less/*', tasks: 'less' } }, min: { dist: { src: ['src/sidetap.js'], dest: 'src/sidetap.min.js' } } }); grunt.loadNpmTasks('grunt-contrib'); grunt.registerTask('build', 'coffee less min'); grunt.registerTask('default', 'coffee less min'); };
/** * grunt * CoffeeScript example */ module.exports = function(grunt){ grunt.initConfig({ lint: { files: ['grunt.js', 'src/*.js'] }, coffee: { compile: { options: { bare: true }, files: { 'src/sidetap_loader.js': 'src/coffee/sidetap_loader.coffee', 'src/sidetap_standard.js': 'src/coffee/sidetap_standard.coffee', 'src/sidetap_ios.js': 'src/coffee/sidetap_ios.coffee', 'src/sidetap.js': ['src/coffee/sidetap_standard.coffee','src/coffee/sidetap_ios.coffee','src/coffee/sidetap_loader.coffee'] } } }, less: { compile: { files: { 'src/sidetap.css': 'src/less/sidetap.less' } } }, watch: { dist1: { files: 'src/coffee/*', tasks: 'coffee' }, dist2: { files: 'src/less/*', tasks: 'less' } }, min: { dist: { src: ['src/sidetap.js'], dest: 'src/sidetap.min.js' } } }); grunt.loadNpmTasks('grunt-contrib'); grunt.registerTask('build', 'coffee less'); grunt.registerTask('default', 'coffee less min'); };
CA-40618: Change path to the supplemental pack Signed-off-by: Javier Alvarez-Valle <[email protected]>
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/opt/dell/srvadmin/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
import subprocess, sys, os.path class DRAC_NO_SUPP_PACK(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class DRAC_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def run2(command): run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Wait for the process to return out, err = [ e.splitlines() for e in run.communicate() ] return run.returncode, out, err drac_path='/usr/sbin/racadm' def DRAC( power_on_ip, user, password): if( not os.path.exists(drac_path)): raise DRAC_NO_SUPP_PACK() cmd='%s -r %s -u %s -p %s serveraction powerup' % (drac_path, power_on_ip, user, password) retcode,out,err=run2(cmd) if(len(err)==0): return str(True) else: raise DRAC_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print DRAC(ip,user,password) if __name__ == "__main__": main()
Add extra spaces to improve readability
(function () { 'use strict'; var path = require('path'), loadConfig = require(path.join(__dirname, 'grunt/load')), config = {}; module.exports = function (grunt) { config = { pkg: grunt.file.readJSON('package.json'), scaffold: { dev: { path: 'dev', assets: 'dev/assets', partials: 'dev/partials', templates: 'dev/templates' }, staging: { path: 'staging', assets: 'staging/assets' }, build: { path: 'build', assets: 'build/assets' }, grunt: 'grunt', tmp: { path: '.tmp', assets: '.tmp/assets' } }, timestamp: '<%= new Date().getTime() %>', banner: '/*! <%= pkg.projectName %> - v<%= pkg.version %> - by <%= pkg.developers %> - <%= grunt.template.today("dd/mm/yyyy") %> */\n', }; grunt.util._.extend(config, loadConfig(path.join(__dirname, 'grunt/options/'))); grunt.initConfig(config); require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); grunt.loadNpmTasks('assemble'); grunt.loadTasks('grunt/tasks/'); }; })();
(function () { 'use strict'; var path = require('path'), loadConfig = require(path.join(__dirname, 'grunt/load')), config = {}; module.exports = function (grunt) { config = { pkg: grunt.file.readJSON('package.json'), scaffold: { dev: { path: 'dev', assets: 'dev/assets', partials: 'dev/partials', templates: 'dev/templates' }, staging: { path: 'staging', assets: 'staging/assets' }, build: { path: 'build', assets: 'build/assets' }, grunt: 'grunt', tmp: { path: '.tmp', assets: '.tmp/assets' } }, timestamp: '<%= new Date().getTime() %>', banner: '/*! <%= pkg.projectName %> - v<%= pkg.version %> - by <%= pkg.developers %> - <%= grunt.template.today("dd/mm/yyyy") %> */\n', }; grunt.util._.extend(config, loadConfig(path.join(__dirname, 'grunt/options/'))); grunt.initConfig(config); require('load-grunt-tasks')(grunt); require('time-grunt')(grunt); grunt.loadNpmTasks('assemble'); grunt.loadTasks('grunt/tasks/'); }; })();
Remove Node interfaces (use origin id for objects)
import graphene from graphene_django.types import DjangoObjectType, ObjectType from graphene_django_extras import ( DjangoFilterPaginateListField, LimitOffsetGraphqlPagination ) from apps.employees import models class EmployeeType(DjangoObjectType): class Meta: model = models.Employee filter_fields = { 'first_name': ['icontains', 'istartswith'], 'last_name': ['icontains', 'istartswith'], 'position': ['exact'], 'id': ['exact'] } class PositionType(DjangoObjectType): """ Position graphQL type. Implemented total_employees and employees objects. """ employees = DjangoFilterPaginateListField( EmployeeType, pagination=LimitOffsetGraphqlPagination() ) total_employees = graphene.Int() def resolve_total_employees(self, info): return self.employees.count() def resolve_employees(self, info): return self.employees.all() class Meta: model = models.Position filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'id': ['exact'] } class SpecializationType(DjangoObjectType): class Meta: model = models.Specialization filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'id': ['exact'], }
import graphene from graphene_django.types import DjangoObjectType, ObjectType from graphene_django_extras import ( DjangoFilterPaginateListField, LimitOffsetGraphqlPagination ) from apps.employees import models class EmployeeType(DjangoObjectType): class Meta: model = models.Employee filter_fields = { 'first_name': ['icontains', 'istartswith'], 'last_name': ['icontains', 'istartswith'], 'position': ['exact'], 'id': ['exact'] } interfaces = (graphene.relay.Node,) class PositionType(DjangoObjectType): """ Position graphQL type. Implemented total_employees and employees objects. """ employees = DjangoFilterPaginateListField( EmployeeType, pagination=LimitOffsetGraphqlPagination() ) total_employees = graphene.Int() def resolve_total_employees(self, info): return self.employees.count() def resolve_employees(self, info): return self.employees.all() class Meta: model = models.Position filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'id': ['exact'] } interfaces = (graphene.relay.Node,) class SpecializationType(DjangoObjectType): class Meta: model = models.Specialization filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'id': ['exact'], } interfaces = (graphene.relay.Node,)
Load the gapi client drive library and change when promise is resolved
/** @jsx React.DOM */ var GoogleApiAuthForm = React.createClass({ render: function () { return ( <form role="form" onSubmit={this.handleSubmit}> <div className="form-group"> <label for="client_id">Client Id</label> <input ref="clientId" id="client_id" className="form-control" type="text" name="client_id" placeholder="Google API Client ID" /> </div> <button className="btn btn-lg btn-primary" type="submit"> Authenticate </button> </form> ); }, handleSubmit: function(ev) { ev.preventDefault(); var scopes = ['https://www.googleapis.com/auth/drive.readonly']; var clientId = this.refs.clientId.getDOMNode().value.trim(); (function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes}, handleAuthResult); })(); function handleAuthResult(result) { // FIXME: Handle fail result gapi.client.load('drive', 'v2').then(function() {console.log('loaded')}); React.renderComponent(<FilesList />, document.getElementById('app')); } } }); var FilesList = React.createClass({ render: function () { return <div> Files here! </div> } }); React.renderComponent(<GoogleApiAuthForm />, document.getElementById('app'));
/** @jsx React.DOM */ var GoogleApiAuthForm = React.createClass({ getInitialState: function() { return {apiKey: null, clientId: null}; }, render: function () { return ( <form role="form" onSubmit={this.handleSubmit}> <div className="form-group"> <label for="client_id">Client Id</label> <input ref="clientId" id="client_id" className="form-control" type="text" name="client_id" placeholder="Google API Client ID" /> </div> <button className="btn btn-lg btn-primary" type="submit"> Authenticate </button> </form> ); }, handleSubmit: function(ev) { ev.preventDefault(); var scopes = ['https://www.googleapis.com/auth/drive.readonly']; var clientId = this.refs.clientId.getDOMNode().value.trim(); function checkAuth() { gapi.auth.authorize({client_id: clientId, scope: scopes}, handleAuthResult); } checkAuth() function handleAuthResult(result) { console.log(result); } } }); React.renderComponent(<GoogleApiAuthForm />, document.getElementById('app'));
Change input from previous processing not from a file
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logs): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logs : list List of every line of original logs. """ self.logtype = logtype self.logs = logs def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype) preprocess.preprocess_text(self.logs) events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(range(preprocess.loglength), 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
from pygraphc.preprocess.PreprocessLog import PreprocessLog from pygraphc.similarity.StringSimilarity import StringSimilarity from itertools import combinations class LogTextSimilarity(object): """A class for calculating cosine similarity between a log pair. This class is intended for non-graph based clustering method. """ def __init__(self, logtype, logfile): """The constructor of class LogTextSimilarity. Parameters ---------- logtype : str Type for event log, e.g., auth, syslog, etc. logfile : str Log filename. """ self.logtype = logtype self.logfile = logfile def get_cosine_similarity(self): """Get cosine similarity from a pair of log lines in a file. Returns ------- cosine_similarity : dict Dictionary of cosine similarity in non-graph clustering. Key: (log_id1, log_id2), value: cosine similarity distance. """ preprocess = PreprocessLog(self.logtype, self.logfile) preprocess.preprocess_text() events = preprocess.events_text # calculate cosine similarity cosines_similarity = {} for log_pair in combinations(preprocess.loglength, 2): cosines_similarity[log_pair] = StringSimilarity.get_cosine_similarity(events[log_pair[0]]['tf-idf'], events[log_pair[1]]['tf-idf'], events[log_pair[0]]['length'], events[log_pair[1]]['length']) return cosines_similarity
Revert "Stricter error message in place of "Name or service not known"" This reverts commit f0258bdd739450104cc196cbea750450f391e763.
<?php namespace Illuminate\Database; use Throwable; use Illuminate\Support\Str; trait DetectsLostConnections { /** * Determine if the given exception was caused by a lost connection. * * @param \Throwable $e * @return bool */ protected function causedByLostConnection(Throwable $e) { $message = $e->getMessage(); return Str::contains($message, [ 'server has gone away', 'no connection to the server', 'Lost connection', 'is dead or not enabled', 'Error while sending', 'decryption failed or bad record mac', 'server closed the connection unexpectedly', 'SSL connection has been closed unexpectedly', 'Error writing data to the connection', 'Resource deadlock avoided', 'Transaction() on null', 'child connection forced to terminate due to client_idle_limit', 'query_wait_timeout', 'reset by peer', 'Physical connection is not usable', 'TCP Provider: Error code 0x68', 'Name or service not known', 'ORA-03114', 'Packets out of order. Expected', 'Adaptive Server connection failed', 'Communication link failure', ]); } }
<?php namespace Illuminate\Database; use Throwable; use Illuminate\Support\Str; trait DetectsLostConnections { /** * Determine if the given exception was caused by a lost connection. * * @param \Throwable $e * @return bool */ protected function causedByLostConnection(Throwable $e) { $message = $e->getMessage(); return Str::contains($message, [ 'server has gone away', 'no connection to the server', 'Lost connection', 'is dead or not enabled', 'Error while sending', 'decryption failed or bad record mac', 'server closed the connection unexpectedly', 'SSL connection has been closed unexpectedly', 'Error writing data to the connection', 'Resource deadlock avoided', 'Transaction() on null', 'child connection forced to terminate due to client_idle_limit', 'query_wait_timeout', 'reset by peer', 'Physical connection is not usable', 'TCP Provider: Error code 0x68', 'getaddrinfo failed: Name or service not known', 'ORA-03114', 'Packets out of order. Expected', 'Adaptive Server connection failed', 'Communication link failure', ]); } }
Make Selector.scope test more rigorous
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def test_unregister(selector): for fp in list(selector): selector.unregister(fp) assert not selector def test_info(selector): for fp in selector: assert selector.info(fp).wants_read assert selector.info(0) is None def test_callbacks(selector): res = selector.select() exp = len(selector) assert sum(m.callback() for m in res) == exp def test_ready(selector): ready = list(selector.ready()) assert ready for event in ready: assert event.ready class TestScoped(object): @fixture def sel(self): return Selector() def test_peaceful(self, sel, handles): with sel.scoped(handles) as monitors: r = set(k.fp for k in sel.ready()) assert r == set(handles) assert not sel def test_exception(self, sel, handles): with raises(NameError): with sel.scoped(handles) as _: raise NameError assert not sel
from contextlib import contextmanager from scell import Selector from pytest import raises, fixture def test_select(selector): res = list(selector.select()) assert res for event in res: assert event.ready def test_select_empty(): sel = Selector() assert list(sel.select()) == [] def test_unregister(selector): for fp in list(selector): selector.unregister(fp) assert not selector def test_info(selector): for fp in selector: assert selector.info(fp).wants_read assert selector.info(0) is None def test_callbacks(selector): res = selector.select() exp = len(selector) assert sum(m.callback() for m in res) == exp def test_ready(selector): ready = list(selector.ready()) assert ready for event in ready: assert event.ready class TestScoped(object): @fixture def sel(self): return Selector() def test_peaceful(self, sel, handles): with sel.scoped(handles) as monitors: r = list(sel.ready()) for ev in r: assert ev.monitored in monitors assert ev.fp in handles assert r assert not sel def test_exception(self, sel, handles): with raises(NameError): with sel.scoped(handles) as _: raise NameError assert not sel
Fix param type in doc block
<?php /** * AmChartsPHP * * @link http://github.com/neeckeloo/AmChartsPHP * @copyright Copyright (c) 2012 Nicolas Eeckeloo */ namespace AmCharts\Chart\Axis; use AmCharts\Chart\Exception; class Category extends AbstractAxis { const POSITION_START = 'start'; const POSITION_MIDDLE = 'middle'; /** * @var string */ protected $gridPosition; /** * Sets grid position * * @param string $position * @return Category */ public function setGridPosition($position) { if ($position != self::POSITION_START && $position != self::POSITION_MIDDLE) { throw new Exception\InvalidArgumentException('The grid position provided is not valid.'); } $this->gridPosition = (string) $position; return $this; } /** * Returns grid position * * @return string */ public function getGridPosition() { return $this->gridPosition; } /** * Returns object properties as array * * @return array */ public function toArray() { $options = parent::toArray(); if ($options) { $keys = array_keys($options); array_walk($keys, function (&$value, $key) { $value = 'categoryAxis.' . $value; }); $options = array_combine($keys, array_values($options)); } return $options; } }
<?php /** * AmChartsPHP * * @link http://github.com/neeckeloo/AmChartsPHP * @copyright Copyright (c) 2012 Nicolas Eeckeloo */ namespace AmCharts\Chart\Axis; use AmCharts\Chart\Exception; class Category extends AbstractAxis { const POSITION_START = 'start'; const POSITION_MIDDLE = 'middle'; /** * @var string */ protected $gridPosition; /** * Sets grid position * * @param type $position * @return Category */ public function setGridPosition($position) { if ($position != self::POSITION_START && $position != self::POSITION_MIDDLE) { throw new Exception\InvalidArgumentException('The grid position provided is not valid.'); } $this->gridPosition = (string) $position; return $this; } /** * Returns grid position * * @return string */ public function getGridPosition() { return $this->gridPosition; } /** * Returns object properties as array * * @return array */ public function toArray() { $options = parent::toArray(); if ($options) { $keys = array_keys($options); array_walk($keys, function (&$value, $key) { $value = 'categoryAxis.' . $value; }); $options = array_combine($keys, array_values($options)); } return $options; } }
Add a missing test description
from django.core.exceptions import ValidationError from django.test import TestCase import djohno from djohno.utils import ( is_pretty_from_address, get_app_versions ) class DjohnoUtilTests(TestCase): def test_is_pretty_from_address_fails_on_bare_address(self): """ Ensure normal email addresses aren't parsed as being "pretty". """ self.assertFalse(is_pretty_from_address('[email protected]')) def test_is_pretty_from_succeeds_on_pretty_address(self): """ Ensure pretty addresses (e.g. Foo <[email protected]>) are parsed as being "pretty". """ self.assertTrue(is_pretty_from_address('Foo <[email protected]>')) def test_is_pretty_from_raises_validation_error_on_bad_input(self): """ Ensure invalid email addresses (e.g. "hello") raise ValidationError if given invalid inputs. """ with self.assertRaises(ValidationError): self.assertTrue(is_pretty_from_address('hello')) def test_get_installed_app_versions(self): """ Ensure we can correctly get the version of a few simple apps (Baz and Moo are bundled in djohno.test, and set up in test_settings.py). """ versions = get_app_versions() self.assertEqual(versions['Djohno']['installed'], djohno.__version__) self.assertEqual(versions['Baz']['installed'], '0.4.2') self.assertEqual(versions['Moo']['installed'], '0.42')
from django.core.exceptions import ValidationError from django.test import TestCase import djohno from djohno.utils import ( is_pretty_from_address, get_app_versions ) class DjohnoUtilTests(TestCase): def test_is_pretty_from_address_fails_on_bare_address(self): """ Ensure normal email addresses aren't parsed as being "pretty". """ self.assertFalse(is_pretty_from_address('[email protected]')) def test_is_pretty_from_succeeds_on_pretty_address(self): """ Ensure pretty addresses (e.g. Foo <[email protected]>) are parsed as being "pretty". """ self.assertTrue(is_pretty_from_address('Foo <[email protected]>')) def test_is_pretty_from_raises_validation_error_on_bad_input(self): """ Ensure invalid email addresses (e.g. "hello") raise ValidationError if given invalid inputs. """ with self.assertRaises(ValidationError): self.assertTrue(is_pretty_from_address('hello')) def test_get_installed_app_versions(self): versions = get_app_versions() self.assertEqual(versions['Djohno']['installed'], djohno.__version__) self.assertEqual(versions['Baz']['installed'], '0.4.2') self.assertEqual(versions['Moo']['installed'], '0.42')
Fix problem loading daily chart on node page
jQuery(function ($) { function generateChart(el) { var url = window.location.origin + "/daily_reports_chart.json"; var certname = $(el).attr('data-certname'); if (typeof certname !== typeof undefined && certname !== false) { url = url + "?certname=" + certname; } d3.json(url, function(data) { var chart = c3.generate({ bindto: '#dailyReportsChart', data: { type: 'bar', json: data['result'], keys: { x: 'day', value: ['failed', 'changed', 'unchanged'], }, groups: [ ['failed', 'changed', 'unchanged'] ], colors: { // Must match CSS colors 'failed':'#AA4643', 'changed':'#4572A7', 'unchanged':'#89A54E', } }, size: { height: 160 }, axis: { x: { type: 'category' } } }); }); } generateChart($("#dailyReportsChart")); });
jQuery(function ($) { function generateChart(el) { var url = "daily_reports_chart.json"; var certname = $(el).attr('data-certname'); if (typeof certname !== typeof undefined && certname !== false) { url = url + "?certname=" + certname; } d3.json(url, function(data) { var chart = c3.generate({ bindto: '#dailyReportsChart', data: { type: 'bar', json: data['result'], keys: { x: 'day', value: ['failed', 'changed', 'unchanged'], }, groups: [ ['failed', 'changed', 'unchanged'] ], colors: { // Must match CSS colors 'failed':'#AA4643', 'changed':'#4572A7', 'unchanged':'#89A54E', } }, size: { height: 160 }, axis: { x: { type: 'category' } } }); }); } generateChart($("#dailyReportsChart")); });
Fix variable in state change
angular.module('billett.admin').controller('AdminPaymentgroupNewController', function ($state, $stateParams, $location, AdminEventgroup, AdminPaymentgroup, Page) { var ctrl = this; console.log("state", $stateParams); var loader = Page.setLoading(); AdminEventgroup.get({id: $stateParams['eventgroup_id']}, function (ret) { loader(); ctrl.eventgroup = ret; ctrl.paymentgroup = new AdminPaymentgroup; ctrl.paymentgroup.eventgroup_id = ret.id; ctrl.save = function () { if (ctrl.paymentgroup.title && ctrl.paymentgroup.title.length > 0) { ctrl.paymentgroup.$save(function (paymentgroup) { if ($stateParams['is_selling']) { $state.go('admin-order-new', {id: ctrl.eventgroup.id, paymentgroup_id: paymentgroup.id}); } else { $location.path('a/paymentgroup/' + paymentgroup.id); } }); } }; ctrl.abort = function () { if ($stateParams['is_selling']) { $state.go('admin-order-new', {id: ctrl.eventgroup.id}); } else { $state.go('admin-paymentgroups', {eventgroup_id: ctrl.eventgroup.id}); } }; }); });
angular.module('billett.admin').controller('AdminPaymentgroupNewController', function ($state, $stateParams, $location, AdminEventgroup, AdminPaymentgroup, Page) { var ctrl = this; console.log("state", $stateParams); var loader = Page.setLoading(); AdminEventgroup.get({id: $stateParams['eventgroup_id']}, function (ret) { loader(); ctrl.eventgroup = ret; ctrl.paymentgroup = new AdminPaymentgroup; ctrl.paymentgroup.eventgroup_id = ret.id; ctrl.save = function () { if (ctrl.paymentgroup.title && ctrl.paymentgroup.title.length > 0) { ctrl.paymentgroup.$save(function (paymentgroup) { if ($stateParams['is_selling']) { $state.go('admin-order-new', {id: ctrl.eventgroup.id, paymentgroup_id: paymentgroup.id}); } else { $location.path('a/paymentgroup/' + paymentgroup.id); } }); } }; ctrl.abort = function () { if ($stateParams['is_selling']) { $state.go('admin-order-new', {id: ctrl.eventgroup.id}); } else { $state.go('admin-paymentgroups', {id: ctrl.eventgroup.id}); } }; }); });
Remove unused imports & Skip if no mock available
# -*- coding: utf-8 -*- ''' :codauthor: :email:`Mike Place <[email protected]>` ''' # Import Salt Testing libs from salttesting.unit import skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock import MagicMock, patch, NO_MOCK, NO_MOCK_REASON ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient @skipIf(NO_MOCK, NO_MOCK_REASON) class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
# -*- coding: utf-8 -*- ''' :codauthor: :email:`Mike Place <[email protected]>` ''' # Import Salt Testing libs from salttesting.helpers import (ensure_in_syspath, destructiveTest) from salttesting.mock import MagicMock, patch ensure_in_syspath('../') # Import salt libs import integration from salt import fileclient # Import Python libs import os class FileClientTest(integration.ModuleCase): def setUp(self): self.file_client = fileclient.Client(self.master_opts) def test_file_list_emptydirs(self): ''' Ensure that the fileclient class won't allow a direct call to file_list_emptydirs() ''' with self.assertRaises(NotImplementedError): self.file_client.file_list_emptydirs() def test_get_file(self): ''' Ensure that the fileclient class won't allow a direct call to get_file() ''' with self.assertRaises(NotImplementedError): self.file_client.get_file(None) def test_get_file_client(self): with patch.dict(self.minion_opts, {'file_client': 'remote'}): with patch('salt.fileclient.RemoteClient', MagicMock(return_value='remote_client')): ret = fileclient.get_file_client(self.minion_opts) self.assertEqual('remote_client', ret) if __name__ == '__main__': from integration import run_tests run_tests(FileClientTest)
Fix package service provider registration
<?php namespace Spekkionu\Assetcachebuster; use Illuminate\Support\ServiceProvider; class AssetcachebusterServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('spekkionu/assetcachebuster'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['assetcachebuster'] = $this->app->share(function ($app) { $options['enable'] = $app['config']->get('assetcachebuster::enable'); $options['hash'] = $app['config']->get('assetcachebuster::hash'); $options['cdn'] = $app['config']->get('assetcachebuster::cdn'); $options['prefix'] = $app['config']->get('assetcachebuster::prefix'); return new Assetcachebuster($options); }); // Register artisan command $this->app['command.assetcachebuster.generate'] = $this->app->share( function ($app) { return new Console\GenerateCommand($app['files']); } ); $this->commands( 'command.assetcachebuster.generate' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('assetcachebuster', 'command.assetcachebuster.generate'); } }
<?php namespace Spekkionu\Assetcachebuster; use Illuminate\Support\ServiceProvider; class AssetcachebusterServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('spekkionu/assetcachebuster'); } /** * Register the service provider. * * @return void */ public function register() { $this->app['assetcachebuster'] = $this->app->share(function ($app) { $options['enable'] = $this->app['config']->get('assetcachebuster::enable'); $options['hash'] = $this->app['config']->get('assetcachebuster::hash'); $options['cdn'] = $this->app['config']->get('assetcachebuster::cdn'); $options['prefix'] = $this->app['config']->get('assetcachebuster::prefix'); return new Assetcachebuster($options); }); // Register artisan command $this->app['command.assetcachebuster.generate'] = $this->app->share( function ($app) { return new Console\GenerateCommand($app['files']); } ); $this->commands( 'command.assetcachebuster.generate' ); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('assetcachebuster', 'command.assetcachebuster.generate'); } }