text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Disable eslint rules ember/no-legacy-test-waiters and ember/no-mixins
'use strict'; module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, plugins: ['ember', 'prettier'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: { 'ember/no-new-mixins': 'off', 'ember/no-mixins': 'off', 'ember/no-legacy-test-waiters': 'off', }, overrides: [ // node files { files: [ '.eslintrc.js', '.template-lintrc.js', '.prettierrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js', ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], rules: Object.assign( {}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here } ), }, ], };
'use strict'; module.exports = { root: true, parser: 'babel-eslint', parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, plugins: ['ember', 'prettier'], extends: [ 'eslint:recommended', 'plugin:ember/recommended', 'plugin:prettier/recommended', ], env: { browser: true, }, rules: { 'ember/no-new-mixins': 'off', }, overrides: [ // node files { files: [ '.eslintrc.js', '.template-lintrc.js', '.prettierrc.js', 'ember-cli-build.js', 'index.js', 'testem.js', 'blueprints/*/index.js', 'config/**/*.js', 'tests/dummy/config/**/*.js', ], excludedFiles: [ 'addon/**', 'addon-test-support/**', 'app/**', 'tests/dummy/app/**', ], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], rules: Object.assign( {}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here } ), }, ], };
Add clasifiers for the Python implementations and versions
#!/usr/bin/env python import sys from setuptools import setup from setuptools.command.test import test as TestCommand import nacl try: import nacl.nacl except ImportError: # installing - there is no cffi yet ext_modules = [] else: # building bdist - cffi is here! ext_modules = [nacl.nacl.ffi.verifier.get_extension()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) setup( name=nacl.__title__, version=nacl.__version__, description=nacl.__summary__, long_description=open("README.rst").read(), url=nacl.__uri__, license=nacl.__license__, author=nacl.__author__, author_email=nacl.__email__, install_requires=[ "cffi", ], extras_require={ "tests": ["pytest"], }, tests_require=["pytest"], packages=[ "nacl", "nacl.invoke", ], ext_package="nacl", ext_modules=ext_modules, zip_safe=False, cmdclass={"test": PyTest}, classifiers=[ "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", ] )
#!/usr/bin/env python import sys from setuptools import setup from setuptools.command.test import test as TestCommand import nacl try: import nacl.nacl except ImportError: # installing - there is no cffi yet ext_modules = [] else: # building bdist - cffi is here! ext_modules = [nacl.nacl.ffi.verifier.get_extension()] class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self.test_args) sys.exit(errno) setup( name=nacl.__title__, version=nacl.__version__, description=nacl.__summary__, long_description=open("README.rst").read(), url=nacl.__uri__, license=nacl.__license__, author=nacl.__author__, author_email=nacl.__email__, install_requires=[ "cffi", ], extras_require={ "tests": ["pytest"], }, tests_require=["pytest"], packages=[ "nacl", "nacl.invoke", ], ext_package="nacl", ext_modules=ext_modules, zip_safe=False, cmdclass={"test": PyTest}, )
Test if method buildViolation exist and fallback to addViolation for symfony < 2.5
<?php /** * @author Marc Pantel <[email protected]> */ namespace Payum\Core\Bridge\Symfony\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; /** * CreditCardDateValidator * * Validate if the Credit Card is not expired */ class CreditCardDateValidator extends ConstraintValidator { /** * {@inheritDoc} */ public function validate($value, Constraint $constraint) { if (null === $value) { return; } if (!($value instanceof \DateTime)) { if (method_exists($this->context, 'buildViolation')) { $this->context->buildViolation($constraint->invalidMessage, array( '{{ value }}' => $value, )) ->addViolation(); return; } $this->context->addViolationAt('expireAt', $constraint->invalidMessage, array( '{{ value }}' => $value, )); } /** * The Credit Card is not expired until last day of the month */ $value->modify('last day of this month'); if (null !== $constraint->min && $value < $constraint->min) { if (method_exists($this->context, 'buildViolation')) { $this->context->buildViolation($constraint->minMessage) ->atPath('expireAt') ->addViolation(); return; } $this->context->addViolationAt('expireAt', $constraint->minMessage); } } }
<?php /** * @author Marc Pantel <[email protected]> */ namespace Payum\Core\Bridge\Symfony\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; /** * CreditCardDateValidator * * Validate if the Credit Card is not expired */ class CreditCardDateValidator extends ConstraintValidator { /** * {@inheritDoc} */ public function validate($value, Constraint $constraint) { if (null === $value) { return; } if (!($value instanceof \DateTime)) { $this->context->buildViolation($constraint->invalidMessage, array( '{{ value }}' => $value, )) ->addViolation(); return; } /** * The Credit Card is not expired until last day of the month */ $value->modify('last day of this month'); if (null !== $constraint->min && $value < $constraint->min) { $this->context->buildViolation($constraint->minMessage) ->atPath('expireAt') ->addViolation(); } } }
Add xlrd dependency for notebook
#! /usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='OpenFisca-Senegal', version='0.5.1', author='OpenFisca Team', author_email='[email protected]', classifiers=[ "Development Status :: 2 - Pre-Alpha", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description=u'Senegalese tax and benefit system for OpenFisca', keywords='benefit microsimulation senegal social tax', license='http://www.fsf.org/licensing/licenses/agpl-3.0.html', url='https://github.com/openfisca/senegal', data_files=[ ('share/openfisca/openfisca-senegal', ['CHANGELOG.md', 'LICENSE', 'README.md']), ], extras_require={ 'notebook': [ 'notebook', 'matplotlib', 'pandas', 'xlrd', ], 'survey': [ 'OpenFisca-Survey-Manager >= 0.8.2', ] }, include_package_data = True, # Will read MANIFEST.in install_requires=[ 'OpenFisca-Core >= 20.0, < 21.0', 'PyYAML >= 3.10', ], packages=find_packages(exclude=['openfisca_senegal.tests*']), test_suite='nose.collector', )
#! /usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup( name='OpenFisca-Senegal', version='0.5.1', author='OpenFisca Team', author_email='[email protected]', classifiers=[ "Development Status :: 2 - Pre-Alpha", "License :: OSI Approved :: GNU Affero General Public License v3", "Operating System :: POSIX", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Information Analysis", ], description=u'Senegalese tax and benefit system for OpenFisca', keywords='benefit microsimulation senegal social tax', license='http://www.fsf.org/licensing/licenses/agpl-3.0.html', url='https://github.com/openfisca/senegal', data_files=[ ('share/openfisca/openfisca-senegal', ['CHANGELOG.md', 'LICENSE', 'README.md']), ], extras_require={ 'notebook': [ 'notebook', 'matplotlib', 'pandas', ], 'survey': [ 'OpenFisca-Survey-Manager >= 0.8.2', ] }, include_package_data = True, # Will read MANIFEST.in install_requires=[ 'OpenFisca-Core >= 20.0, < 21.0', 'PyYAML >= 3.10', ], packages=find_packages(exclude=['openfisca_senegal.tests*']), test_suite='nose.collector', )
Fix missing comma in requirements
from setuptools import setup setup( name='scuevals-api', packages=['scuevals_api'], include_package_data=True, test_suite='tests', entry_points={ 'console_scripts': [ 'app=scuevals_api.cmd:cli' ] }, install_requires=[ 'alembic==0.9.7', 'beautifulsoup4==4.6.0', 'blinker==1.4', 'coveralls==1.2.0', 'Flask-Caching==1.3.3', 'Flask-Cors==3.0.3', 'Flask-JWT-Extended==3.6.0', 'Flask-Migrate==2.1.1', 'Flask-RESTful==0.3.6', 'Flask-Rollbar==1.0.1', 'Flask-SQLAlchemy==2.3.2', 'Flask==0.12.2', 'gunicorn==19.7.1', 'newrelic==2.100.0.84', 'psycopg2==2.7.3.2', 'python-jose==2.0.0', 'PyYAML==3.12', 'requests==2.18.4', 'rollbar==0.13.17', 'vcrpy==1.11.1', 'webargs==1.8.1', ], )
from setuptools import setup setup( name='scuevals-api', packages=['scuevals_api'], include_package_data=True, test_suite='tests', entry_points={ 'console_scripts': [ 'app=scuevals_api.cmd:cli' ] }, install_requires=[ 'alembic==0.9.7' 'beautifulsoup4==4.6.0', 'blinker==1.4', 'coveralls==1.2.0', 'Flask-Caching==1.3.3', 'Flask-Cors==3.0.3', 'Flask-JWT-Extended==3.6.0', 'Flask-Migrate==2.1.1', 'Flask-RESTful==0.3.6', 'Flask-Rollbar==1.0.1', 'Flask-SQLAlchemy==2.3.2', 'Flask==0.12.2', 'gunicorn==19.7.1', 'newrelic==2.100.0.84', 'psycopg2==2.7.3.2', 'python-jose==2.0.0', 'PyYAML==3.12', 'requests==2.18.4', 'rollbar==0.13.17', 'vcrpy==1.11.1', 'webargs==1.8.1', ], )
Add data fixers to reindex for search by re-saving everything
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save() @for_class(Project) def save_all_projects(project): project.save() @for_class(Maker) def save_all_makers(maker): maker.save()
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key in keys: obj = cls.get(key) fn(obj) return do_for_class return do_that @for_class(Maker) def fix_maker_history(maker): for histitem in maker.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addmaker' elif histitem.action == 'edit': histitem.action = 'editmaker' # Make sure the maker is tagged. if histitem.maker is None: histitem.add_link(maker, tag='maker') histitem.save() @for_class(Project) def fix_project_history(project): for histitem in project.history: # Fix the actions. if histitem.action == 'create': histitem.action = 'addproject' elif histitem.action == 'edit': histitem.action = 'editproject' # Make sure the project is tagged. if histitem.project is None: histitem.add_link(project, tag='project') histitem.save()
Set more reasonable SOA defaults
var validators = require('../validators'); function SOA(host, opts) { if (typeof(host) !== 'string') throw new TypeError('host (string) is required'); if (!opts) opts = {}; var defaults = { admin: 'hostmaster.' + host, serial: 0, refresh: 86400, retry: 7200, expire: 1209600, ttl: 10800 }; for (var key in defaults) { if (key in opts) continue; opts[key] = defaults[key]; } this.host = host; this.admin = opts.admin; this.serial = opts.serial; this.refresh = opts.refresh; this.retry = opts.retry; this.expire = opts.expire; this.ttl = opts.ttl; this._type = 'SOA'; } module.exports = SOA; SOA.prototype.valid = function SOA() { var self = this, model = {}; model = { host: validators.nsName, admin: validators.nsName, serial: validators.UInt32BE, refresh: validators.UInt32BE, retry: validators.UInt32BE, expire: validators.UInt32BE, ttl: validators.UInt32BE }; return validators.validate(self, model); };
var validators = require('../validators'); function SOA(host, opts) { if (typeof(host) !== 'string') throw new TypeError('host (string) is required'); if (!opts) opts = {}; var defaults = { admin: 'hostmaster.' + host, serial: 0, refresh: 10, retry: 10, expire: 10, ttl: 10 }; for (key in defaults) { if (key in opts) continue; opts[key] = defaults[key]; } this.host = host; this.admin = opts.admin; this.serial = opts.serial; this.refresh = opts.refresh; this.retry = opts.retry; this.expire = opts.expire; this.ttl = opts.ttl; this._type = 'SOA'; } module.exports = SOA; SOA.prototype.valid = function SOA() { var self = this, model = {}; model = { host: validators.nsName, admin: validators.nsName, serial: validators.UInt32BE, refresh: validators.UInt32BE, retry: validators.UInt32BE, expire: validators.UInt32BE, ttl: validators.UInt32BE }; return validators.validate(self, model); };
Refactor how location is shown
import React, {PureComponent} from 'react'; import classNames from 'classnames'; import {isPast, parse} from 'date-fns'; import {formatDate, generateEventJSONLD} from './utils'; import Heading from '../Heading'; import Link from '../Link'; import styles from './ConferenceItem.scss'; export default class ConferenceItem extends PureComponent { render() { const { name, url, city, country, startDate, endDate, twitter, } = this.props; return ( <div className={classNames( isPast(parse(startDate)) ? styles.past : '', styles.ConferenceItem )} > <script type="application/ld+json" dangerouslySetInnerHTML={{__html: generateEventJSONLD({name, url, city, country, startDate, endDate})}} /> <Heading element="h3" level={3}> <Link url={url} external> {name} </Link> </Heading> <div> {`${Location(city, country)} - `} <span className={styles.Date}> {formatDate(startDate, endDate)} </span> {Twitter(twitter)} </div> </div> ); } } function Twitter(twitter) { if (!twitter) { return null; } return ( <Link url={`https://twitter.com/${twitter}`} external> {twitter} </Link> ); } function Location(city, country) { if (city && country) { return `${city}, ${country}`; } return country || city; }
import React, {PureComponent} from 'react'; import classNames from 'classnames'; import {isPast, parse} from 'date-fns'; import {formatDate, generateEventJSONLD} from './utils'; import Heading from '../Heading'; import Link from '../Link'; import styles from './ConferenceItem.scss'; export default class ConferenceItem extends PureComponent { render() { const { name, url, city, country, startDate, endDate, twitter, } = this.props; return ( <div className={classNames( isPast(parse(startDate)) ? styles.past : '', styles.ConferenceItem )} > <script type="application/ld+json" dangerouslySetInnerHTML={{__html: generateEventJSONLD({name, url, city, country, startDate, endDate})}} /> <Heading element="h3" level={3}> <Link url={url} external> {name} </Link> </Heading> <div> {`${city}, ${country} - `} <span className={styles.Date}> {formatDate(startDate, endDate)} </span> {Twitter(twitter)} </div> </div> ); } } function Twitter(twitter) { if (!twitter) { return null; } return ( <Link url={`https://twitter.com/${twitter}`} external> {twitter} </Link> ); }
Enhance error messaging on exception
<?php namespace Hub\Client\Common; use Hub\Client\Exception\BadRequestException; use Hub\Client\Exception\NotFoundException; use Hub\Client\Exception\NotAuthorizedException; use RuntimeException; class ErrorResponseHandler { public static function handle($response) { if ($response->getStatusCode() == 401) { throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed'); } $xml = $response->getBody(); $rootNode = @simplexml_load_string($xml); if ($rootNode) { if ($rootNode->getName()=='error') { switch ((string)$rootNode->status) { case 400: throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message); break; case 404: throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message); break; case 403: throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message); break; default: throw new RuntimeException( "Unsupported response status code returned: " . (string)$rootNode->code . ': ' . (string)$rootNode->messsage . " (" . (string)$rootNode->details . ")" ); break; } } throw new RuntimeException( "Failed to parse response. It's valid XML, but not the expected error root element" ); } throw new RuntimeException("Failed to parse response: " . $xml); } }
<?php namespace Hub\Client\Common; use Hub\Client\Exception\BadRequestException; use Hub\Client\Exception\NotFoundException; use Hub\Client\Exception\NotAuthorizedException; use RuntimeException; class ErrorResponseHandler { public static function handle($response) { if ($response->getStatusCode() == 401) { throw new NotAuthorizedException('NOT_AUTHORIZED', 'Basic auth failed'); } $xml = $response->getBody(); $rootNode = @simplexml_load_string($xml); if ($rootNode) { if ($rootNode->getName()=='error') { switch ((string)$rootNode->status) { case 400: throw new BadRequestException((string)$rootNode->code, (string)$rootNode->message); break; case 404: throw new NotFoundException((string)$rootNode->code, (string)$rootNode->message); break; case 403: throw new NotAuthorizedException((string)$rootNode->code, (string)$rootNode->message); break; default: throw new RuntimeException( "Unsupported response status code returned: " . (string)$rootNode->status . ' / ' . (string)$rootNode->code ); break; } } throw new RuntimeException( "Failed to parse response. It's valid XML, but not the expected error root element" ); } throw new RuntimeException("Failed to parse response: " . $xml); } }
feat: Add a more button to excerpt in blog list
import React from "react"; import { rhythm } from "../utils/typography"; import Link from "gatsby-link"; export default ({ data }) => { console.log(data); return ( <div> <h4>{data.allMarkdownRemark.totalCount} Posts</h4> {data.allMarkdownRemark.edges.map(({ node }) => ( <div key={node.id}> <h3> <Link to={node.fields.slug}> {node.frontmatter.title} <span>— {node.frontmatter.date}</span> </Link> </h3> <p> {node.excerpt} <Link to={node.fields.slug}>more.</Link> </p> </div> ))} </div> ); }; export const query = graphql` query IndexQuery { allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { published: { eq: true } } } ) { totalCount edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") } fields { slug } excerpt } } } } `;
import React from "react"; import { rhythm } from "../utils/typography"; import Link from "gatsby-link"; export default ({ data }) => { console.log(data); return ( <div> <h4>{data.allMarkdownRemark.totalCount} Posts</h4> {data.allMarkdownRemark.edges.map(({ node }) => ( <div key={node.id}> <h3> <Link to={node.fields.slug}> {node.frontmatter.title} <span>— {node.frontmatter.date}</span> </Link> </h3> <p>{node.excerpt}</p> </div> ))} </div> ); }; export const query = graphql` query IndexQuery { allMarkdownRemark( sort: { fields: [frontmatter___date], order: DESC } filter: { frontmatter: { published: { eq: true } } } ) { totalCount edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") } fields { slug } excerpt } } } } `;
Add name of collection in backbone model
{% include "model.tpl.js" %} /** * File: collection.tpl * User: Martin Martimeo * Date: 29.04.13 * Time: 19:18 */ var {{ collection_name }}Collection = Backbone.Collection.extend({ model: {{ collection_name }}Model, name: '{{ collection_name }}', url: '{{ api_url }}/{{ collection_name }}', _numPages: undefined, _loadedPages: [], // Did we load already all pages? isFullyLoaded: function () { return (this._numPages != undefined) && (this._loadedPages == this._numPages); }, // parse data from server // This is specific overwritten to work with flask-restless / tornado-restless parse: function (response) { if (this._loadedPages.indexOf(response.page) == -1) { this._loadedPages.push(response.page); } this._numPages = response.num_pages; this._numResults = response.num_results; return response.objects; }, // fetches more results to collection fetchMore: function () { if (!this.isFullyLoaded()) { if (this._loadedPages.indexOf('1') == -1) { this.fetch(); } else { this.fetch({page: this._loadedPages.length}); } return true; } return false; } }); {{ collection_name }} = new {{ collection_name }}Collection;
{% include "model.tpl.js" %} /** * File: collection.tpl * User: Martin Martimeo * Date: 29.04.13 * Time: 19:18 */ var {{ collection_name }}Collection = Backbone.Collection.extend({ model: {{ collection_name }}Model, url: '{{ api_url }}/{{ collection_name }}', _numPages: undefined, _loadedPages: [], // Did we load already all pages? isFullyLoaded: function () { return (this._numPages != undefined) && (this._loadedPages == this._numPages); }, // parse data from server // This is specific overwritten to work with flask-restless / tornado-restless parse: function (response) { if (this._loadedPages.indexOf(response.page) == -1) { this._loadedPages.push(response.page); } this._numPages = response.num_pages; this._numResults = response.num_results; return response.objects; }, // fetches more results to collection fetchMore: function () { if (!this.isFullyLoaded()) { if (this._loadedPages.indexOf('1') == -1) { this.fetch(); } else { this.fetch({page: this._loadedPages.length}); } return true; } return false; } }); {{ collection_name }} = new {{ collection_name }}Collection;
Make UUIDField have a fixed max-length
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)): """ We can make use of psycopg2's uuid handling: that means everything at the database end will be a uuid. We also make sure that values assigned to this field on a model will automatically be cast to UUID. """ description = "UUID" default_error_messages = { 'invalid': _("'%(value)s' is not a valid UUID."), } def __init__(self, **kwargs): kwargs['max_length'] = 36 super(UUIDField, self).__init__(**kwargs) def get_internal_type(self): return 'UUIDField' def db_type(self, connection): return 'uuid' def to_python(self, value): if not value: return None if isinstance(value, six.string_types): try: return uuid.UUID(value) except ValueError: raise ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value} ) return value
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(models.SubfieldBase, models.Field)): """ We can make use of psycopg2's uuid handling: that means everything at the database end will be a uuid. We also make sure that values assigned to this field on a model will automatically be cast to UUID. """ description = "UUID" default_error_messages = { 'invalid': _("'%(value)s' is not a valid UUID."), } def get_internal_type(self): return 'UUIDField' def db_type(self, connection): return 'uuid' def to_python(self, value): if isinstance(value, six.string_types): try: return uuid.UUID(value) except ValueError: raise ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value} ) return value
BUG(1900): Allow PropDict.sources in python bindings to be any sequence.
class PropDict(dict): def __init__(self, srcs): dict.__init__(self) self._sources = srcs def set_source_preference(self, sources): """ Change list of source preference This method has been deprecated and should no longer be used. """ raise DeprecationWarning("This method has been deprecated and should no longer be used. Set the sources list using the 'sources' property.") self._set_sources(sources) def has_key(self, item): try: self.__getitem__(item) return True except KeyError: return False def __contains__(self, item): return self.has_key(item) def __getitem__(self, item): if isinstance(item, basestring): for src in self._sources: if src.endswith('*'): for k,v in self.iteritems(): if k[0].startswith(src[:-1]) and k[1] == item: return v try: t = dict.__getitem__(self, (src, item)) return t except KeyError: pass raise KeyError, item return dict.__getitem__(self, item) def get(self, item, default=None): try: return self[item] except KeyError: return default def _get_sources(self): return self._sources def _set_sources(self, val): if isinstance(val, basestring): raise TypeError("Need a sequence of sources") for i in val: if not isinstance(i, basestring): raise TypeError("Sources need to be strings") self._sources = val sources = property(_get_sources, _set_sources)
class PropDict(dict): def __init__(self, srcs): dict.__init__(self) self._sources = srcs def set_source_preference(self, sources): """ Change list of source preference This method has been deprecated and should no longer be used. """ raise DeprecationWarning("This method has been deprecated and should no longer be used. Set the sources list using the 'sources' property.") self._set_sources(sources) def has_key(self, item): try: self.__getitem__(item) return True except KeyError: return False def __contains__(self, item): return self.has_key(item) def __getitem__(self, item): if isinstance(item, basestring): for src in self._sources: if src.endswith('*'): for k,v in self.iteritems(): if k[0].startswith(src[:-1]) and k[1] == item: return v try: t = dict.__getitem__(self, (src, item)) return t except KeyError: pass raise KeyError, item return dict.__getitem__(self, item) def get(self, item, default=None): try: return self[item] except KeyError: return default def _get_sources(self): return self._sources def _set_sources(self, val): if not isinstance(val, list): raise TypeError("Need a list of sources") for i in val: if not isinstance(i, basestring): raise TypeError("Sources need to be strings") self._sources = val sources = property(_get_sources, _set_sources)
Add an EntryDetailCtrl for retreiving the Entry details
var trexControllers = angular.module('trexControllers', []); trexControllers.controller('ProjectListCtrl', ['$scope', 'Project', function($scope, Project) { $scope.projects = Project.query(); $scope.order = "name"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]); trexControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', 'Project', function($scope, $routeParams, Project) { $scope.project = Project.get({projectId: $routeParams.id}); $scope.entries = Project.entries({projectId: $routeParams.id}); // $http.get('/api/1/projects/' + $routeParams.id + "/entries").success( // function(data) { // }); $scope.order = "id"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]); trexControllers.controller('EntryDetailCtrl', ['$scope', '$routeParams', 'Entry', function($scope, $routeParams, Entry) { $scope.entry = Entry.get({entryId: $routeParams.id}); $scope.order = "id"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]);
var trexControllers = angular.module('trexControllers', []); trexControllers.controller('ProjectListCtrl', ['$scope', 'Project', function($scope, Project) { $scope.projects = Project.query(); $scope.order = "name"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]); trexControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', 'Project', function($scope, $routeParams, Project) { $scope.project = Project.get({projectId: $routeParams.id}); $scope.entries = Project.entries({projectId: $routeParams.id}); // $http.get('/api/1/projects/' + $routeParams.id + "/entries").success( // function(data) { // }); $scope.order = "id"; $scope.orderreverse = false; $scope.setOrder = function(name) { if (name == $scope.order) { $scope.orderreverse = !$scope.orderreverse; } $scope.order = name; }; } ]);
Add support for float primitive git-svn-id: 7e8def7d4256e953abb468098d8cb9b4faff0c63@6213 12255794-1b5b-4525-b599-b0510597569d
package com.arondor.common.reflection.reflect.instantiator; import java.util.HashMap; import java.util.Map; public class FastPrimitiveConverter { private interface PrimitiveConverter { Object convert(String value); } private final Map<String, PrimitiveConverter> primitiveConverterMap = new HashMap<String, FastPrimitiveConverter.PrimitiveConverter>(); public FastPrimitiveConverter() { primitiveConverterMap.put("java.lang.String", new PrimitiveConverter() { public Object convert(String value) { return value; } }); primitiveConverterMap.put("long", new PrimitiveConverter() { public Object convert(String value) { return Long.parseLong(value); } }); primitiveConverterMap.put("int", new PrimitiveConverter() { public Object convert(String value) { return Integer.parseInt(value); } }); primitiveConverterMap.put("boolean", new PrimitiveConverter() { public Object convert(String value) { return Boolean.parseBoolean(value); } }); primitiveConverterMap.put("float", new PrimitiveConverter() { public Object convert(String value) { return Float.parseFloat(value); } }); } public Object convert(String value, String primitiveClass) { PrimitiveConverter converter = primitiveConverterMap.get(primitiveClass); if (converter == null) { throw new IllegalArgumentException("Not supported : primitiveClass=" + primitiveClass); } return converter.convert(value); } }
package com.arondor.common.reflection.reflect.instantiator; import java.util.HashMap; import java.util.Map; public class FastPrimitiveConverter { private interface PrimitiveConverter { Object convert(String value); } private final Map<String, PrimitiveConverter> primitiveConverterMap = new HashMap<String, FastPrimitiveConverter.PrimitiveConverter>(); public FastPrimitiveConverter() { primitiveConverterMap.put("java.lang.String", new PrimitiveConverter() { public Object convert(String value) { return value; } }); primitiveConverterMap.put("long", new PrimitiveConverter() { public Object convert(String value) { return Long.parseLong(value); } }); primitiveConverterMap.put("int", new PrimitiveConverter() { public Object convert(String value) { return Integer.parseInt(value); } }); primitiveConverterMap.put("boolean", new PrimitiveConverter() { public Object convert(String value) { return Boolean.parseBoolean(value); } }); } public Object convert(String value, String primitiveClass) { PrimitiveConverter converter = primitiveConverterMap.get(primitiveClass); if (converter == null) { throw new IllegalArgumentException("Not supported : primitiveClass=" + primitiveClass); } return converter.convert(value); } }
Use the correct option name
from mercury.common.configuration import MercuryConfiguration DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml' def parse_options(): configuration = MercuryConfiguration( 'mercury-inventory', DEFAULT_CONFIG_FILE, description='The mercury inventory service' ) configuration.add_option('inventory.bind_address', default='tcp://127.0.0.1:9000', help_string='Mercury Inventory bind address' ) configuration.add_option('asyncio_debug', '--asyncio-debug', 'ASYNCIO_DEBUG', 'logging.debug_asyncio', default=False, special_type=bool, help_string='Enable asyncio debugging' ) configuration.add_option('inventory.database.name', default='test', help_string='The inventory database') configuration.add_option('inventory.database.collection', default='inventory', help_string='The collection for inventory ' 'documents') configuration.add_option('inventory.database.servers', default='localhost:27017', special_type=list, help_string='Server or coma separated list of ' 'servers to connect to') configuration.add_option('inventory.database.replica_name', help_string='An optional replica name') configuration.add_option('inventory.database.username', help_string='The database user') configuration.add_option('inventory.database.password', help_string='The database user\'s password') return configuration.scan_options()
from mercury.common.configuration import MercuryConfiguration DEFAULT_CONFIG_FILE = 'mercury-inventory.yaml' def parse_options(): configuration = MercuryConfiguration( 'mercury-inventory', DEFAULT_CONFIG_FILE, description='The mercury inventory service' ) configuration.add_option('inventory.bind_address', default='tcp://127.0.0.1:9000', help_string='Mercury Inventory bind address' ) configuration.add_option('asyncio_debug', '--asyncio-debug', 'ASYNCIO_DEBUG', 'logging.debug_asyncio', default=False, special_type=bool, help_string='Enable asyncio debugging' ) configuration.add_option('inventory.database.name', default='test', help_string='The inventory database') configuration.add_option('inventory.database.collection', default='inventory', help_string='The collection for inventory ' 'documents') configuration.add_option('inventory.database.servers', default='localhost:27017', special_type=list, help_string='Server or coma separated list of ' 'servers to connect to') configuration.add_option('inventory.database.replica_name', help_string='An optional replica name') configuration.add_option('inventory.database.user', help_string='The database user') configuration.add_option('inventory.database.password', help_string='The database user\'s password') return configuration.scan_options()
Exclude tests package from distribution
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='0.4a0', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(exclude=['tests']), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
#!/usr/bin/env python import sys, os try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup # Hack to prevent "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when setup.py exits # (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) try: import multiprocessing except ImportError: pass setup( name='Willow', version='0.4a0', description='A Python image library that sits on top of Pillow, Wand and OpenCV', author='Karl Hobley', author_email='[email protected]', url='', packages=find_packages(), include_package_data=True, license='BSD', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Topic :: Multimedia :: Graphics', 'Topic :: Multimedia :: Graphics :: Graphics Conversion', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], install_requires=[], zip_safe=False, )
Replace array with ArrayCollection in decks.
<?php namespace Mo\FlashCardsBundle\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; use Doctrine\Common\Collections\ArrayCollection; /** * @MongoDB\Document(collection="decks") */ class Deck { /** * @MongoDB\Id */ protected $id; /** * @MongoDB\String */ protected $name; /** * @MongoDB\String * @MongoDB\UniqueIndex */ protected $slug; /** * @MongoDB\EmbedMany(targetDocument="Card") */ protected $cards; /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getSlug() { return $this->slug; } /** * @param string $slug */ public function setSlug($slug) { $this->slug = $slug; } /** * @return array */ public function getCards() { return $this->cards; } /** * @param Mo\FlashCardsBundle\Document\Card $card */ public function addCard(Card $card) { $this->cards[] = $card; } /** * @param Mo\FlashCardsBundle\Document\Card $card */ public function removeCard(Card $card) { $this->cards->removeElement($card); } /** * Initializes collections. */ public function __construct() { $this->cards = new ArrayCollection(); } }
<?php namespace Mo\FlashCardsBundle\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; /** * @MongoDB\Document(collection="decks") */ class Deck { /** * @MongoDB\Id */ protected $id; /** * @MongoDB\String */ protected $name; /** * @MongoDB\String * @MongoDB\UniqueIndex */ protected $slug; /** * @MongoDB\EmbedMany(targetDocument="Card") */ protected $cards = array(); /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getSlug() { return $this->slug; } /** * @param string $slug */ public function setSlug($slug) { $this->slug = $slug; } /** * @return array */ public function getCards() { return $this->cards; } /** * @param \Mo\FlashCardsBundle\Document\Card $card */ public function addCard(Card $card) { $this->cards[] = $card; } }
CRM-2726: Add process for export job once customer was created or updated
<?php namespace Oro\Bundle\IntegrationBundle\Exception; class SoapConnectionException extends TransportException { /** * @param string $response * @param \Exception $exception * @param string $request * @param string $headers * * @return static */ public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '') { $exceptionMessage = null !== $exception ? $exception->getMessage() : ''; $exceptionCode = null !== $exception ? $exception->getCode() : 0; $code = !empty($headers['code']) ? $headers['code'] : 'unknown'; $message = PHP_EOL; $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL; $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL; $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL; $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL; $message .= PHP_EOL; $newException = new static($message, $exceptionCode, $exception); if ($exception instanceof \SoapFault) { $newException->setFaultCode($exception->faultcode); } return $newException; } }
<?php namespace Oro\Bundle\IntegrationBundle\Exception; class SoapConnectionException extends TransportException { /** * @param string $response * @param \Exception $exception * @param string $request * @param string $headers * * @return static */ public static function createFromResponse($response, \Exception $exception = null, $request = '', $headers = '') { $exceptionMessage = null !== $exception ? $exception->getMessage() : ''; $exceptionCode = null !== $exception ? $exception->getCode() : 0; $code = !empty($headers['code']) ? $headers['code'] : 'unknown'; $message = PHP_EOL; $message .= str_pad('[message]', 20, ' ', STR_PAD_RIGHT) . $exceptionMessage . PHP_EOL; $message .= str_pad('[request]', 20, ' ', STR_PAD_RIGHT) . $request . PHP_EOL; $message .= str_pad('[response]', 20, ' ', STR_PAD_RIGHT) . $response . PHP_EOL; $message .= str_pad('[code]', 20, ' ', STR_PAD_RIGHT) . $code . PHP_EOL; $message .= PHP_EOL; $exception = new static($message, $exceptionCode, $exception); $exception->setFaultCode($code); return $exception; } }
Update vector-im to riot-im on Login Signed-off-by: Andrew (anoa) <[email protected]>
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); import { _t } from 'matrix-react-sdk/lib/languageHandler'; module.exports = React.createClass({ displayName: 'VectorLoginFooter', statics: { replaces: 'LoginFooter', }, render: function() { return ( <div className="mx_Login_links"> <a href="https://medium.com/@RiotChat">blog</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://twitter.com/@RiotChat">twitter</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://github.com/vector-im/riot-web">github</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://matrix.org">{ _t('powered by Matrix') }</a> </div> ); } });
/* Copyright 2015, 2016 OpenMarket Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var React = require('react'); import { _t } from 'matrix-react-sdk/lib/languageHandler'; module.exports = React.createClass({ displayName: 'VectorLoginFooter', statics: { replaces: 'LoginFooter', }, render: function() { return ( <div className="mx_Login_links"> <a href="https://medium.com/@RiotChat">blog</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://twitter.com/@RiotChat">twitter</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://github.com/vector-im/vector-web">github</a>&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="https://matrix.org">{ _t('powered by Matrix') }</a> </div> ); } });
Use the correct path for telegram config
'use strict'; let Telegram = require( 'node-telegram-bot-api' ); let config = require( '../config.js' ); let BotPlug = require( './BotPlug.js' ); class TelegramBotPlug extends BotPlug { constructor( bot ){ super( bot ); if( config.bot.plugins.indexOf( 'Telegram' ) > -1 ){ this.telegramClient = new Telegram( config.telegram.apiKey, { polling: true } ); super.detectMessageToUser( this.onUserMessage ); this.telegramClient.on( 'message', ( msg ) => { var chatId = msg.chat.id; this.telegramClient.sendMessage( chatId, 'Chat id: ' + chatId ); }); } } onUserMessage( users, from, message ){ for( let i = 0; i < users.length; i = i + 1 ){ if( config.telegram.users[ users[ i ] ] ){ this.telegramClient.sendMessage( config.telegram.users[ users[ i ] ], '[' + from + '] ' + message ); console.log( 'Telegram sent to ' + config.telegram.users[ users[ i ] ] ); } } } } module.exports = TelegramBotPlug;
'use strict'; let Telegram = require( 'node-telegram-bot-api' ); let config = require( '../config.js' ); let BotPlug = require( './BotPlug.js' ); class TelegramBotPlug extends BotPlug { constructor( bot ){ super( bot ); if( config.bot.plugins.indexOf( 'Telegram' ) > -1 ){ this.telegramClient = new Telegram( config.telegram.apiKey, { polling: true } ); super.detectMessageToUser( this.onUserMessage ); this.telegramClient.on( 'message', ( msg ) => { var chatId = msg.chat.id; this.telegramClient.sendMessage( chatId, 'Chat id: ' + chatId ); }); } } onUserMessage( users, from, message ){ for( let i = 0; i < users.length; i = i + 1 ){ if( config.users[ users[ i ] ] ){ this.telegramClient.sendMessage( config.users[ users[ i ] ], '[' + from + '] ' + message ); console.log( 'Telegram sent to ' + config.users[ users[ i ] ] ); } } } } module.exports = TelegramBotPlug;
Use install_requires= and bump version It appears that the "requires" keyword argument to setup() doesn't do the right thing. This may be a brain-o on my part. This switches back to using "install_requires" and bumps the version for release.
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='cli_tools', version='0.2.5', author='Kevin L. Mitchell', author_email='[email protected]', url='https://github.com/klmitch/cli_utils', description="Command Line Interface Tools", long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or ' 'later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: User Interfaces', ], py_modules=['cli_tools'], install_requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), )
#!/usr/bin/env python from setuptools import setup def readreq(filename): result = [] with open(filename) as f: for req in f: req = req.partition('#')[0].strip() if not req: continue result.append(req) return result def readfile(filename): with open(filename) as f: return f.read() setup( name='cli_tools', version='0.2.4', author='Kevin L. Mitchell', author_email='[email protected]', url='https://github.com/klmitch/cli_utils', description="Command Line Interface Tools", long_description=readfile('README.rst'), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or ' 'later (GPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: User Interfaces', ], py_modules=['cli_tools'], requires=readreq('requirements.txt'), tests_require=readreq('test-requirements.txt'), )
Create a source map for minified JS code.
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-connect'); // Project configuration. grunt.initConfig({ connect: { server: { options: { port: 8000, base: '.', keepalive: true } } } , pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n', sourceMap: true }, build: { src: 'src/angular-intro.js', dest: 'build/angular-intro.min.js' } }, jshint: { lib: { options: {}, src: ['src/*.js'] }, }, watch: { scripts: { files: 'src/*.js', tasks: ['jshint', 'uglify'], options: { interrupt: true }, }, gruntfile: { files: 'Gruntfile.js' } }, }); // Load all grunt tasks require('load-grunt-tasks')(grunt); // Default task(s). grunt.registerTask('default', ['jshint', 'uglify']); // Test grunt.registerTask('test', ['jshint']); };
module.exports = function(grunt) { grunt.loadNpmTasks('grunt-contrib-connect'); // Project configuration. grunt.initConfig({ connect: { server: { options: { port: 8000, base: '.', keepalive: true } } } , pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'src/angular-intro.js', dest: 'build/angular-intro.min.js' } }, jshint: { lib: { options: {}, src: ['src/*.js'] }, }, watch: { scripts: { files: 'src/*.js', tasks: ['jshint', 'uglify'], options: { interrupt: true }, }, gruntfile: { files: 'Gruntfile.js' } }, }); // Load all grunt tasks require('load-grunt-tasks')(grunt); // Default task(s). grunt.registerTask('default', ['jshint', 'uglify']); // Test grunt.registerTask('test', ['jshint']); };
Update laravel/mvc-basics/step-by-step/23 with theme formatting
<?php // ~/Sites/presentation/mvc-basics/resources/views/event/tickets/create.blade.php // Using your text editor, create the `create.blade.php` file and paste the // following code. <html> <head> <title>Create Event Ticket</title> </head> <body> <form class="form-horizontal" method="post" action="{{ route('event.tickets.store') }}"> {{ csrf_field() }} <div class="form-group"> <label for="ticketholder_name" class="col-sm-3 control-label">Ticketholder Name</label> <div class="col-sm-9"> <input type="text" class="form-control" name="ticketholder_name" /> </div> </div> <div class="form-group"> <label for="ticket_price" class="col-sm-3 control-label">Ticket Price</label> <div class="col-sm-9"> $ <input type="text" class="form-control" name="ticket_price" style="width: 150px; display: inline;" /> </div> </div> <div class="form-group"> <div class="col-sm-9 col-offset-sm-3"> <button type="submit" class="btn btn-primary">Save Ticket</button> <a href="{{ route('event.tickets.index') }}">Cancel</a> </div> </div> </form> </body> </html>
<?php // ~/Sites/presentation/mvc-basics/resources/views/event/tickets/create.blade.php // Using your text editor, create the `create.blade.php` file and paste the // following code. <html> <head> <title>Create Event Ticket</title> </head> <body> <form method="post" action="{{ route('event.tickets.store') }}"> {{ csrf_field() }} <div class="form-group"> <div class="col-sm-3"> Ticketholder Name </div> <div class="col-sm-9"> <input type="text" class="form-control" name="ticketholder_name" /> </div> </div> <div class="form-group"> <div class="col-sm-3"> Ticket Price </div> <div class="col-sm-9"> $ <input type="text" class="form-control" name="ticket_price" style="width: 150px;" /> </div> </div> <div class="form-group"> <div class="col-sm-9 col-offset-sm-3"> <button type="submit" class="btn btn-primary">Save Ticket</button> <a href="{{ route('event.tickets.index') }}">Cancel</a> </div> </div> </form> </body> </html>
Fix missing comma in `install_requires` coincidentally, I [made a video about this today](https://www.youtube.com/watch?v=5Zto6VYsNsI)
import os try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.md') as f: readme = f.read() setup( name="pykwalify", version="1.7.0", description='Python lib/cli for JSON/YAML schema validation', long_description=readme, long_description_content_type='text/markdown', author="Johan Andersson", author_email="[email protected]", maintainer='Johan Andersson', maintainer_email='[email protected]', license='MIT', packages=['pykwalify'], url='http://github.com/grokzen/pykwalify', entry_points={ 'console_scripts': [ 'pykwalify = pykwalify.cli:cli_entrypoint', ], }, install_requires=[ 'docopt>=0.6.2', "ruamel.yaml>=0.16.0", 'python-dateutil>=2.8.0', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
import os try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.md') as f: readme = f.read() setup( name="pykwalify", version="1.7.0", description='Python lib/cli for JSON/YAML schema validation', long_description=readme, long_description_content_type='text/markdown', author="Johan Andersson", author_email="[email protected]", maintainer='Johan Andersson', maintainer_email='[email protected]', license='MIT', packages=['pykwalify'], url='http://github.com/grokzen/pykwalify', entry_points={ 'console_scripts': [ 'pykwalify = pykwalify.cli:cli_entrypoint', ], }, install_requires=[ 'docopt>=0.6.2', "ruamel.yaml>=0.16.0" 'python-dateutil>=2.8.0', ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ], )
Handle no git user configured
from git import Repo, exc import os class GitRepo(object): def __init__(self, root=None, remote="origin", lazy=True): self.remote_name = remote self.root = root self._repo = None if not lazy: self.repo @property def repo(self): if self._repo is None: if self.remote_name is None: self._repo = False else: try: self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True) except exc.InvalidGitRepositoryError: self._repo = False return self._repo @property def enabled(self): return self.repo @property def dirty(self): return self.repo.is_dirty() @property def last_commit(self): if not self.repo: return None return self.repo.head.commit.hexsha @property def remote(self): if not self.repo: return None try: return self.repo.remotes[self.remote_name] except IndexError: return None @property def remote_url(self): if not self.remote: return None return self.remote.url def tag(self, name, message): try: return self.repo.create_tag("wandb/"+name, message=message, force=True) except GitCommandError: print("Failed to tag repository.") return None def push(self, name): if self.remote: return self.remote.push("wandb/"+name, force=True)
from git import Repo, exc import os class GitRepo(object): def __init__(self, root=None, remote="origin", lazy=True): self.remote_name = remote self.root = root self._repo = None if not lazy: self.repo @property def repo(self): if self._repo is None: if self.remote_name is None: self._repo = False else: try: self._repo = Repo(self.root or os.getcwd(), search_parent_directories=True) except exc.InvalidGitRepositoryError: self._repo = False return self._repo @property def enabled(self): return self.repo @property def dirty(self): return self.repo.is_dirty() @property def last_commit(self): if not self.repo: return None return self.repo.head.commit.hexsha @property def remote(self): if not self.repo: return None try: return self.repo.remotes[self.remote_name] except IndexError: return None @property def remote_url(self): if not self.remote: return None return self.remote.url def tag(self, name, message): return self.repo.create_tag("wandb/"+name, message=message, force=True) def push(self, name): if self.remote: return self.remote.push("wandb/"+name, force=True)
Revert "remove NULL check, replace with DummyLayout" This reverts commit ce03278d842a0ff6325f6041e4c95dee0bfd74c6.
<?php namespace Teach\Adapters\Web\Lesplan; final class Fase implements \Teach\Adapters\HTML\LayoutableInterface { private $title; /** * * @var \Teach\Adapters\HTML\LayoutableInterface[] */ private $onderdelen = array(); /** * * @var \Teach\Adapters\HTML\LayoutableInterface */ private $sibling; public function __construct($title) { $this->title = $title; } public function chainTo(\Teach\Adapters\HTML\LayoutableInterface $sibling) { $this->sibling = $sibling; } public function addOnderdeel(\Teach\Adapters\HTML\LayoutableInterface $onderdeel) { $this->onderdelen[] = $onderdeel; } /** * * @return array */ public function generateHTMLLayout() { $onderdelenHTML = []; foreach ($this->onderdelen as $onderdeel) { $onderdelenHTML = array_merge($onderdelenHTML, $onderdeel->generateHTMLLayout()); } if ($this->sibling === null) { $siblingHTML = []; } else { $siblingHTML = $this->sibling->generateHTMLLayout(); } return array_merge([ [ 'section', [], array_merge([ [ 'h2', $this->title ] ], $onderdelenHTML) ] ], $siblingHTML); } }
<?php namespace Teach\Adapters\Web\Lesplan; use Teach\Adapters\HTML\DummyLayout; final class Fase implements \Teach\Adapters\HTML\LayoutableInterface { private $title; /** * * @var \Teach\Adapters\HTML\LayoutableInterface[] */ private $onderdelen = array(); /** * * @var \Teach\Adapters\HTML\LayoutableInterface */ private $sibling; public function __construct($title) { $this->title = $title; $this->sibling = new DummyLayout(); } public function chainTo(\Teach\Adapters\HTML\LayoutableInterface $sibling) { $this->sibling = $sibling; } public function addOnderdeel(\Teach\Adapters\HTML\LayoutableInterface $onderdeel) { $this->onderdelen[] = $onderdeel; } /** * * @return array */ public function generateHTMLLayout() { $onderdelenHTML = []; foreach ($this->onderdelen as $onderdeel) { $onderdelenHTML = array_merge($onderdelenHTML, $onderdeel->generateHTMLLayout()); } return array_merge([ [ 'section', [], array_merge([ [ 'h2', $this->title ] ], $onderdelenHTML) ] ], $this->sibling->generateHTMLLayout()); } }
Add a proper validator for disable_builtins git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@2243 3942dd89-8c5d-46d7-aeed-044bccf3e60c
import logging from flexget import plugin from flexget.plugin import priority, register_plugin, plugins log = logging.getLogger('builtins') def all_builtins(): """Helper function to return an iterator over all builtin plugins.""" return (plugin for plugin in plugins.itervalues() if plugin.builtin) class PluginDisableBuiltins(object): """Disables all (or specific) builtin plugins from a feed.""" def validator(self): from flexget import validator root = validator.factory() root.accept('boolean') root.accept('list').accept('choice').accept_choices(plugin.name for plugin in all_builtins()) return root def debug(self): log.debug('Builtin plugins: %s' % ', '.join(plugin.name for plugin in all_builtins())) @priority(255) def on_feed_start(self, feed, config): self.disabled = [] if not config: return for plugin in all_builtins(): if config is True or plugin.name in config: plugin.builtin = False self.disabled.append(plugin.name) log.debug('Disabled builtin plugin(s): %s' % ', '.join(self.disabled)) @priority(-255) def on_feed_exit(self, feed, config): if not self.disabled: return for name in self.disabled: plugin.plugins[name].builtin = True log.debug('Enabled builtin plugin(s): %s' % ', '.join(self.disabled)) self.disabled = [] on_feed_abort = on_feed_exit register_plugin(PluginDisableBuiltins, 'disable_builtins', api_ver=2)
import logging from flexget import plugin from flexget.plugin import priority, register_plugin log = logging.getLogger('builtins') class PluginDisableBuiltins(object): """ Disables all builtin plugins from a feed. """ def __init__(self): self.disabled = [] def validator(self): from flexget import validator # TODO: accept only list (of texts) or boolean return validator.factory('any') def debug(self): for name, info in plugin.plugins.iteritems(): if not info.builtin: continue log.debug('Builtin plugin: %s' % name) def on_feed_start(self, feed): for name, info in plugin.plugins.iteritems(): if info.builtin: if isinstance(feed.config['disable_builtins'], list): if info.name in feed.config['disable_builtins']: info.builtin = False self.disabled.append(name) else: # disabling all builtins info.builtin = False self.disabled.append(name) log.debug('Disabled builtin plugin %s' % ', '.join(self.disabled)) @priority(-255) def on_feed_exit(self, feed): names = [] for name in self.disabled: names.append(name) plugin.plugins[name].builtin = True self.disabled = [] log.debug('Enabled builtin plugins %s' % ', '.join(names)) on_feed_abort = on_feed_exit register_plugin(PluginDisableBuiltins, 'disable_builtins')
Update mozci version to 0.13.2
from setuptools import setup, find_packages deps = [ 'mozillapulse>=1.1', 'mozci>=0.13.2', 'treeherder-client>=1.5', 'ijson>=2.2', 'requests', ] setup(name='pulse-actions', version='0.1.4', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], author='Alice Scarpa', author_email='[email protected]', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps, url='https://github.com/adusca/pulse_actions', entry_points={ 'console_scripts': [ 'run-pulse-actions = pulse_actions.worker:main' ], })
from setuptools import setup, find_packages deps = [ 'mozillapulse>=1.1', 'mozci>=0.13.1', 'treeherder-client>=1.5', 'ijson>=2.2', 'requests', ] setup(name='pulse-actions', version='0.1.4', description='A pulse listener that acts upon messages with mozci.', classifiers=['Intended Audience :: Developers', 'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules', ], author='Alice Scarpa', author_email='[email protected]', license='MPL 2.0', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=deps, url='https://github.com/adusca/pulse_actions', entry_points={ 'console_scripts': [ 'run-pulse-actions = pulse_actions.worker:main' ], })
:bug: Replace deprecated node type simpleSelector with selector
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'placeholder-in-extend', 'defaults': {}, 'detect': function (ast, parser) { var result = []; ast.traverseByType('atkeyword', function (keyword, i, parent) { keyword.forEach(function (item) { if (item.content === 'extend') { parent.forEach('selector', function (selector) { var placeholder = false; selector.content.forEach(function (selectorPiece) { if (selectorPiece.type === 'placeholder') { placeholder = true; } }); if (!placeholder) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': selector.start.line, 'column': selector.start.column, 'message': '@extend must be used with a %placeholder', 'severity': parser.severity }); } }); } }); }); return result; } };
'use strict'; var helpers = require('../helpers'); module.exports = { 'name': 'placeholder-in-extend', 'defaults': {}, 'detect': function (ast, parser) { var result = []; ast.traverseByType('atkeyword', function (keyword, i, parent) { keyword.forEach(function (item) { if (item.content === 'extend') { parent.forEach('simpleSelector', function (selector) { var placeholder = false; selector.content.forEach(function (selectorPiece) { if (selectorPiece.type === 'placeholder') { placeholder = true; } }); if (!placeholder) { result = helpers.addUnique(result, { 'ruleId': parser.rule.name, 'line': selector.start.line, 'column': selector.start.column, 'message': '@extend must be used with a %placeholder', 'severity': parser.severity }); } }); } }); }); return result; } };
[Discord] Handle bot missing permissions for app commands
from discord import app_commands from discord.ext import commands import logging import sys import traceback import sentry_sdk class CommandTree(app_commands.CommandTree): async def on_error(self, interaction, error): # Command Invoke Error if isinstance(error, app_commands.CommandInvokeError): # Bot missing permissions if isinstance(error.original, commands.BotMissingPermissions): bot = interaction.client ctx = await bot.get_context(interaction) missing_permissions = bot.inflect_engine.join([ f"`{permission}`" for permission in error.original.missing_permissions ]) permission_declension = bot.inflect_engine.plural( 'permission', len(error.original.missing_permissions) ) await ctx.embed_reply( "I don't have permission to do that here\n" f"I need the {missing_permissions} {permission_declension}" ) return if ( isinstance(error, app_commands.TransformerError) and isinstance( error.__cause__, commands.PartialEmojiConversionFailure ) ): ctx = await interaction.client.get_context(interaction) await ctx.embed_reply( f"{ctx.bot.error_emoji} " f"`{error.value}` doesn't seem to be a custom emoji" ) return sentry_sdk.capture_exception(error) print( f"Ignoring exception in slash command {interaction.command.name}", # TODO: Use full name file = sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file = sys.stderr ) logging.getLogger("errors").error( "Uncaught exception\n", exc_info = (type(error), error, error.__traceback__) )
from discord import app_commands from discord.ext import commands import logging import sys import traceback import sentry_sdk class CommandTree(app_commands.CommandTree): async def on_error(self, interaction, error): if ( isinstance(error, app_commands.TransformerError) and isinstance( error.__cause__, commands.PartialEmojiConversionFailure ) ): ctx = await interaction.client.get_context(interaction) await ctx.embed_reply( f"{ctx.bot.error_emoji} " f"`{error.value}` doesn't seem to be a custom emoji" ) return sentry_sdk.capture_exception(error) print( f"Ignoring exception in slash command {interaction.command.name}", # TODO: Use full name file = sys.stderr ) traceback.print_exception( type(error), error, error.__traceback__, file = sys.stderr ) logging.getLogger("errors").error( "Uncaught exception\n", exc_info = (type(error), error, error.__traceback__) )
Use next method of reader object
import csv from datetime import datetime from django.shortcuts import render from django.utils import timezone from django.views.generic import TemplateView from .forms import FeedbackUploadForm from .models import Feedback class FeedbackView(TemplateView): template_name = 'index.html' def get(self, request): feedback = Feedback.objects.all() form = FeedbackUploadForm() return render( request, self.template_name, { 'form': form, 'feedback': feedback } ) def save_feedback(self, data): creation_date = datetime.strptime( data[2], '%m/%d/%Y %H:%M' ).replace(tzinfo=timezone.utc) Feedback.objects.create( fid=data[0], creation_date=creation_date, question_asked=data[4], message=data[5] ) def post(self, request): feedback = Feedback.objects.all() form = FeedbackUploadForm(request.POST, request.FILES) if form.is_valid(): reader = csv.reader(request.FILES['file_upload']) reader.next() map(self.save_feedback, reader) return render( request, self.template_name, { 'form': form, 'feedback': feedback } )
import csv from datetime import datetime from django.shortcuts import render from django.utils import timezone from django.views.generic import TemplateView from .forms import FeedbackUploadForm from .models import Feedback class FeedbackView(TemplateView): template_name = 'index.html' def get(self, request): feedback = Feedback.objects.all() form = FeedbackUploadForm() return render( request, self.template_name, { 'form': form, 'feedback': feedback } ) def save_feedback(self, data): creation_date = datetime.strptime( data[2], '%m/%d/%Y %H:%M' ).replace(tzinfo=timezone.utc) Feedback.objects.create( fid=data[0], creation_date=creation_date, question_asked=data[4], message=data[5] ) def post(self, request): feedback = Feedback.objects.all() form = FeedbackUploadForm(request.POST, request.FILES) if form.is_valid(): reader = csv.reader(request.FILES['file_upload']) next(reader, None) map(self.save_feedback, reader) return render( request, self.template_name, { 'form': form, 'feedback': feedback } )
Add umdNamedDefine to webpack to make it easier to use in a <script> tag.
/* eslint no-var:0 */ var webpack = require('webpack'); var yargs = require('yargs'); var options = yargs .alias('p', 'optimize-minimize') .alias('d', 'debug') .argv; var config = { entry: './src/vizceral.js', output: { path: './dist', filename: options.optimizeMinimize ? 'vizceral.min.js' : 'vizceral.js', library: 'Vizceral', libraryTarget: 'umd', umdNamedDefine: true }, module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/, }, { test: /\.woff2?$/, loader: 'url?limit=10000&mimetype=application/font-woff' }, { test: /\.otf$/, loader: 'file' }, { test: /\.ttf$/, loader: 'file' }, { test: /\.eot$/, loader: 'file' }, { test: /\.svg$/, loader: 'url' }, { test: /\.html$/, loader: 'html' }, { test: /\.css$/, loader: 'style!css' } ] }, plugins: [ new webpack.DefinePlugin({ __DEBUG__: process.env.NODE_ENV !== 'production', __HIDE_DATA__: !!process.env.HIDE_DATA }), ] }; if (!options.optimizeMinimize) { config.devtool = 'source-map'; } module.exports = config;
/* eslint no-var:0 */ var webpack = require('webpack'); var yargs = require('yargs'); var options = yargs .alias('p', 'optimize-minimize') .alias('d', 'debug') .argv; var config = { entry: './src/vizceral.js', output: { path: './dist', filename: options.optimizeMinimize ? 'vizceral.min.js' : 'vizceral.js', library: 'Vizceral', libraryTarget: 'umd' }, module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/, }, { test: /\.woff2?$/, loader: 'url?limit=10000&mimetype=application/font-woff' }, { test: /\.otf$/, loader: 'file' }, { test: /\.ttf$/, loader: 'file' }, { test: /\.eot$/, loader: 'file' }, { test: /\.svg$/, loader: 'url' }, { test: /\.html$/, loader: 'html' }, { test: /\.css$/, loader: 'style!css' } ] }, plugins: [ new webpack.DefinePlugin({ __DEBUG__: process.env.NODE_ENV !== 'production', __HIDE_DATA__: !!process.env.HIDE_DATA }), ] }; if (!options.optimizeMinimize) { config.devtool = 'source-map'; } module.exports = config;
Simplify loop in linear gradient.
<?php namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient; final class Linear implements Gradient { /** @var int */ private $power; /** * @param int $power */ public function __construct($power = 2) { $this->power = $power; } /** * @param array $coefficients * @param array $features * @param float $outcome * @return float */ public function cost(array $coefficients, array $features, $outcome) { return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power); } /** * @param array $coefficients * @param array $features * @return float */ private function predicted(array $coefficients, array $features) { return array_sum(array_map(function ($coefficient, $feature) { return $coefficient * $feature; }, $coefficients, $features)); } /** * @param array $coefficients * @param array $features * @param float $outcome * @return array */ public function gradient(array $coefficients, array $features, $outcome) { $gradient = []; $predicted = $this->predicted($coefficients, $features); foreach ($features as $feature) { $gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $feature; } return $gradient; } }
<?php namespace mcordingley\Regression\Algorithm\GradientDescent\Gradient; final class Linear implements Gradient { /** @var int */ private $power; /** * @param int $power */ public function __construct($power = 2) { $this->power = $power; } /** * @param array $coefficients * @param array $features * @param float $outcome * @return float */ public function cost(array $coefficients, array $features, $outcome) { return pow(abs($this->predicted($coefficients, $features) - $outcome), $this->power); } /** * @param array $coefficients * @param array $features * @return float */ private function predicted(array $coefficients, array $features) { return array_sum(array_map(function ($coefficient, $feature) { return $coefficient * $feature; }, $coefficients, $features)); } /** * @param array $coefficients * @param array $features * @param float $outcome * @return array */ public function gradient(array $coefficients, array $features, $outcome) { $gradient = []; $predicted = $this->predicted($coefficients, $features); for ($i = 0; $i < count($features); $i++) { $gradient[] = $this->power * pow(abs($predicted - $outcome), $this->power - 1) * $features[$i]; } return $gradient; } }
Update ID of device in load script
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put(('https://ubervest.firebaseio.com/devices/%d/hr/' % device) + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
import argparse import requests import time DEFAULT_DEVICE = 0 DEFAULT_FILE = '../data/ECG_data.csv' def main(device=0, filename=DEFAULT_FILE): print("Loading firebase for device #%d" % device) with open(filename) as f: index = 0 count = 0 timestamp = int(time.time() * 1000) for line in f: line = line.strip() ts, value = line.split(',', 1) count += float(value) index += 1 if index == 10: # Dump timestamp += 1 print("Sending %s: %s" % (str(timestamp), str(count / 10))) requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) count = 0 index = 0 timestamp += 1 requests.put('https://ubervest.firebaseio.com/devices/0/hr/' + str(timestamp) + '.json', data=str(count / 10)) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Load sample data for a given device') parser.add_argument('--d', type=int, default=DEFAULT_DEVICE, help="The ID of the device to load with data.") parser.add_argument('--f', type=str, default=DEFAULT_FILE, help="The ID of the device to load with data.") args = parser.parse_args() main(device=args.d, filename=args.f)
Use lib/ instead of src/lib.
#/usr/bin/env python2.6 # # $Id: setup.py 87 2010-07-01 18:01:03Z ver $ from distutils.core import setup description = """ The Jersey core libraries provide common abstractions used by Jersey software. """ def getVersion(): import os packageSeedFile = os.path.join("lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = "jersey", version = version.short(), description = "Jersey Core Libraries", long_description = description, author = "Oliver Gould", author_email = "[email protected]", maintainer = "Jersey-Devel", maintainer_email = "[email protected]", package_dir = { "jersey": "lib", }, packages = [ "jersey", "jersey.cases", ], py_modules = [ "jersey._version", "jersey.cli", "jersey.cases.test_cli", "jersey.inet", "jersey.cases.test_inet", "jersey.log", "jersey.cases.test_log", ], provides = [ "jersey", "jersey.cli", "jersey.log", ], requires = [ "twisted (>=9.0.0)", ], )
#/usr/bin/env python2.6 # # $Id: setup.py 87 2010-07-01 18:01:03Z ver $ from distutils.core import setup description = """ The Jersey core libraries provide common abstractions used by Jersey software. """ def getVersion(): import os packageSeedFile = os.path.join("src", "lib", "_version.py") ns = {"__name__": __name__, } execfile(packageSeedFile, ns) return ns["version"] version = getVersion() setup( name = "jersey", version = version.short(), description = "Jersey Core Libraries", long_description = description, author = "Oliver Gould", author_email = "[email protected]", maintainer = "Jersey-Devel", maintainer_email = "[email protected]", package_dir = { "jersey": "src/lib", }, packages = [ "jersey", "jersey.cases", ], py_modules = [ "jersey._version", "jersey.cli", "jersey.cases.test_cli", "jersey.inet", "jersey.cases.test_inet", "jersey.log", "jersey.cases.test_log", ], provides = [ "jersey", "jersey.cli", "jersey.log", ], requires = [ "twisted (>=9.0.0)", ], )
Fix for Chrome filepath C:\fakepath\
/** */ (function($) { $.fn.inputFileText = function(userOptions) { var MARKER_ATTRIBUTE = 'data-inputFileText'; if(this.attr(MARKER_ATTRIBUTE) === 'true') { // Plugin has already been applied to input file element return this; } var options = $.extend({ // Defaults text: 'Choose File', remove: false }, userOptions); // Hide input file element this.css({ display: 'none' //width: 0 }); // Insert button after input file element var button = $( '<input type="button" value="' + options.text + '" />' ).insertAfter(this); // Insert text after button element var text = $( '<input type="text" style="readonly:true; border:none; margin-left: 5px" />' ).insertAfter(button); // Open input file dialog when button clicked var self = this; button.click(function() { self.click(); }); // Update text when input file chosen this.change(function() { // Chrome puts C:\fakepath\... for file path text.val(self.val().replace('C:\\fakepath\\', '')); }); // Mark that this plugin has been applied to the input file element return this.attr(MARKER_ATTRIBUTE, 'true'); }; }(jQuery));
/** */ (function($) { $.fn.inputFileText = function(userOptions) { var MARKER_ATTRIBUTE = 'data-inputFileText'; if(this.attr(MARKER_ATTRIBUTE) === 'true') { // Plugin has already been applied to input file element return this; } var options = $.extend({ // Defaults text: 'Choose File', remove: false }, userOptions); // Hide input file element this.css({ display: 'none' //width: 0 }); // Insert button after input file element var button = $( '<input type="button" value="' + options.text + '" />' ).insertAfter(this); // Insert text after button element var text = $( '<input type="text" style="readonly:true; border:none; margin-left: 5px" />' ).insertAfter(button); // Open input file dialog when button clicked var self = this; button.click(function() { self.click(); }); // Update text when input file chosen this.change(function() { text.val(self.val()); }); // Mark that this plugin has been applied to the input file element return this.attr(MARKER_ATTRIBUTE, 'true'); }; }(jQuery));
Fix regex as the `:` after the column is optional Fixes SublimeLinter/SublimeLinter#1847 Closes #17 Output from pyflakes can be ``` <stdin>:1044:12 undefined name 'settingss' <stdin>:34:45: invalid syntax ``` t.i. the `:` after the column is optional. In the latter case `filename` overmatched ("not lazy") to "<stdin>:34".
from SublimeLinter.lint import PythonLinter import re class Pyflakes(PythonLinter): cmd = 'pyflakes' regex = r'''(?x) ^(?P<filename>.+?):(?P<line>\d+):((?P<col>\d+):?)?\s # The rest of the line is the error message. # Within that, capture anything within single quotes as `near`. (?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*) ''' multiline = True # stderr has all syntax errors, parse it via our regex on_stderr = None defaults = { 'selector': 'source.python' } def reposition_match(self, line, col, match, vv): if 'imported but unused' in match.message: # Consider: # from foo import bar # import foo.bar # In both cases `pyflakes` reports `'foo.bar' ... unused`. import_id = re.escape(match.near[1:-1]) # unquote last_part = import_id.split('.')[-1] # So we match either `bar` or `foo.bar` against the line content text = vv.select_line(line) pattern = r"\s({}|{})".format(last_part, import_id) re_match = re.search(pattern, text) if re_match: return line, re_match.start(1), re_match.end(1) return super().reposition_match(line, col, match, vv)
from SublimeLinter.lint import PythonLinter import re class Pyflakes(PythonLinter): cmd = 'pyflakes' regex = r'''(?x) ^(?P<filename>.+):(?P<line>\d+):((?P<col>\d+):?)?\s # The rest of the line is the error message. # Within that, capture anything within single quotes as `near`. (?P<message>[^\'\n\r]*(?P<near>\'.+?\')?.*) ''' multiline = True # stderr has all syntax errors, parse it via our regex on_stderr = None defaults = { 'selector': 'source.python' } def reposition_match(self, line, col, match, vv): if 'imported but unused' in match.message: # Consider: # from foo import bar # import foo.bar # In both cases `pyflakes` reports `'foo.bar' ... unused`. import_id = re.escape(match.near[1:-1]) # unquote last_part = import_id.split('.')[-1] # So we match either `bar` or `foo.bar` against the line content text = vv.select_line(line) pattern = r"\s({}|{})".format(last_part, import_id) re_match = re.search(pattern, text) if re_match: return line, re_match.start(1), re_match.end(1) return super().reposition_match(line, col, match, vv)
Add __repr__ for User model
import os import hashlib import datetime import peewee database = peewee.Proxy() class BaseModel(peewee.Model): class Meta: database = database class User(BaseModel): id = peewee.IntegerField(primary_key=True) name = peewee.CharField(unique=True) password = peewee.CharField() salt = peewee.CharField(default=os.urandom(10).decode('cp1251', errors='replace')) join_date = peewee.DateTimeField(default=datetime.datetime.now) class AuthError(Exception): pass class RegisterError(Exception): pass @classmethod def auth(cls, name, password): user = User.get(name=name) pass_with_salt = password + user.salt pass_hash = hashlib.sha224(pass_with_salt.encode()).hexdigest() if not pass_hash == user.password: raise cls.AuthError('Wrong password!') return user @classmethod def register(cls, name, password): try: User.get(name=name) raise cls.RegisterError('User with that name does exist') except User.DoesNotExist: pass user = User(name=name) pass_with_salt = password + user.salt user.password = hashlib.sha224(pass_with_salt.encode()).hexdigest() user.save() def __repr__(self): return '<User %r>' % self.username
import os import hashlib import datetime import peewee database = peewee.Proxy() class BaseModel(peewee.Model): class Meta: database = database class User(BaseModel): id = peewee.IntegerField(primary_key=True) name = peewee.CharField(unique=True) password = peewee.CharField() salt = peewee.CharField(default=os.urandom(10).decode('cp1251', errors='replace')) join_date = peewee.DateTimeField(default=datetime.datetime.now) class AuthError(Exception): pass class RegisterError(Exception): pass @classmethod def auth(cls, name, password): user = User.get(name=name) pass_with_salt = password + user.salt pass_hash = hashlib.sha224(pass_with_salt.encode()).hexdigest() if not pass_hash == user.password: raise cls.AuthError('Wrong password!') return user @classmethod def register(cls, name, password): try: User.get(name=name) raise cls.RegisterError('User with that name does exist') except User.DoesNotExist: pass user = User(name=name) pass_with_salt = password + user.salt user.password = hashlib.sha224(pass_with_salt.encode()).hexdigest() user.save()
Remove the missing script tag resource
<?php return array( /* |-------------------------------------------------------------------------- | Service Name |-------------------------------------------------------------------------- | | Name of the API service these description configs are for. | */ "name" => "Shopify", /* |-------------------------------------------------------------------------- | Service Description |-------------------------------------------------------------------------- | | Description of the API service. | */ "description" => "A Shopify API Wrapper built using Guzzle - ShopifyExtras.com", /* |-------------------------------------------------------------------------- | Service Configurations |-------------------------------------------------------------------------- | | Configuration files of specfic service descriptions to load. | */ "services" => array( "auth", "application-charge", "article", "asset", "blog", "carrier-service", "checkout", "collect", "comment", "country", "custom-collection", "customer", "customer-address", "customer-group", "customer-saved-search", "event", "fulfillment", "fulfillment-service", "location", "metafield", "order", "order-risk", "page", "product", "product-image", "product-variant", "province", "recurring-application-charge", "redirect", "refund", "shop", "smart-collection", "theme", "transaction", "user", "webhook" ), /* |-------------------------------------------------------------------------- | Default models |-------------------------------------------------------------------------- | | Default response models for typical usage of responses | */ "models" => array( "defaultJsonResponse" => array( "type" => "object", "additionalProperties" => array( "location" => "json", ) ) ) );
<?php return array( /* |-------------------------------------------------------------------------- | Service Name |-------------------------------------------------------------------------- | | Name of the API service these description configs are for. | */ "name" => "Shopify", /* |-------------------------------------------------------------------------- | Service Description |-------------------------------------------------------------------------- | | Description of the API service. | */ "description" => "A Shopify API Wrapper built using Guzzle - ShopifyExtras.com", /* |-------------------------------------------------------------------------- | Service Configurations |-------------------------------------------------------------------------- | | Configuration files of specfic service descriptions to load. | */ "services" => array( "auth", "application-charge", "article", "asset", "blog", "carrier-service", "checkout", "collect", "comment", "country", "custom-collection", "customer", "customer-address", "customer-group", "customer-saved-search", "event", "fulfillment", "fulfillment-service", "location", "metafield", "order", "order-risk", "page", "product", "product-image", "product-variant", "province", "recurring-application-charge", "redirect", "refund", "script-tag", "shop", "smart-collection", "theme", "transaction", "user", "webhook" ), /* |-------------------------------------------------------------------------- | Default models |-------------------------------------------------------------------------- | | Default response models for typical usage of responses | */ "models" => array( "defaultJsonResponse" => array( "type" => "object", "additionalProperties" => array( "location" => "json", ) ) ) );
Fix vertical layout visibility update
// @flow import { helpers } from 'utils'; import LayoutBehavior from './behaviors/LayoutBehavior'; const classes = { CLASS_NAME: 'layout__vertical-layout', ITEM: 'layout__vertical-layout-item', HIDDEN: 'layout__hidden' }; export default Marionette.View.extend({ initialize(options) { helpers.ensureOption(options, 'rows'); this.rows = options.rows; }, tagName: 'div', template: false, className() { return `${classes.CLASS_NAME} ${this.options.class || ''}`; }, behaviors: { LayoutBehavior: { behaviorClass: LayoutBehavior } }, templateContext() { return { title: this.options.title }; }, onRender() { this.__rowsCtx = []; this.rows.forEach(view => { view.on('change:visible', (activeView, visible) => this.__handleChangeVisibility(activeView, visible)); this.$el.append(view.render().$el); this.__rowsCtx.push({ view }); }); this.__updateState(); }, onAttach() { this.rows.forEach(view => { view._isAttached = true; view.triggerMethod('attach'); }); }, update() { this.rows.forEach(view => { if (view.update) { view.update(); } }); this.__updateState(); }, __handleChangeVisibility(view, visible) { view.$el.toggleClass(classes.HIDDEN, !visible); }, onDestroy() { this.rows.forEach(view => view.destroy()); } });
// @flow import { helpers } from 'utils'; import LayoutBehavior from './behaviors/LayoutBehavior'; const classes = { CLASS_NAME: 'layout__vertical-layout', ITEM: 'layout__vertical-layout-item', HIDDEN: 'layout__hidden' }; export default Marionette.View.extend({ initialize(options) { helpers.ensureOption(options, 'rows'); this.rows = options.rows; }, tagName: 'div', template: false, className() { return `${classes.CLASS_NAME} ${this.options.class || ''}`; }, behaviors: { LayoutBehavior: { behaviorClass: LayoutBehavior } }, templateContext() { return { title: this.options.title }; }, onRender() { this.__rowsCtx = []; this.rows.forEach(view => { view.on('change:visible', (activeView, visible) => this.__handleChangeVisibility(activeView, visible)); this.$el.append(view.render().$el); this.__rowsCtx.push({ view }); }); }, onAttach() { this.rows.forEach(view => { view._isAttached = true; view.triggerMethod('attach'); }); }, update() { this.rows.forEach(view => { if (view.update) { view.update(); } }); this.__updateState(); }, __handleChangeVisibility(view, visible) { view.$el.toggleClass(classes.HIDDEN, !visible); }, onDestroy() { this.rows.forEach(view => view.destroy()); } });
Move CancellablePromiseInterface typehint to class property
<?php namespace React\Promise; class CancellationQueue { private $started = false; /** * @var CancellablePromiseInterface[] */ private $queue = []; public function __invoke() { if ($this->started) { return; } $this->started = true; $this->drain(); } public function enqueue($promise) { if (!$promise instanceof CancellablePromiseInterface) { return; } $length = array_push($this->queue, $promise); if ($this->started && 1 === $length) { $this->drain(); } } private function drain() { for ($i = key($this->queue); isset($this->queue[$i]); $i++) { $promise = $this->queue[$i]; $exception = null; try { $promise->cancel(); } catch (\Exception $exception) { } unset($this->queue[$i]); if ($exception) { throw $exception; } } $this->queue = []; } }
<?php namespace React\Promise; class CancellationQueue { private $started = false; private $queue = []; public function __invoke() { if ($this->started) { return; } $this->started = true; $this->drain(); } public function enqueue($promise) { if (!$promise instanceof CancellablePromiseInterface) { return; } $length = array_push($this->queue, $promise); if ($this->started && 1 === $length) { $this->drain(); } } private function drain() { for ($i = key($this->queue); isset($this->queue[$i]); $i++) { /** @var CancellablePromiseInterface $promise */ $promise = $this->queue[$i]; $exception = null; try { $promise->cancel(); } catch (\Exception $exception) { } unset($this->queue[$i]); if ($exception) { throw $exception; } } $this->queue = []; } }
Fix the corporation migration to not have any unique indexes
<?php use Phinx\Db\Adapter\MysqlAdapter; use Phinx\Migration\AbstractMigration; class Corporations extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class */ public function change() { $corporations = $this->table('corporations', array("engine" => "TokuDB")); $corporations ->addColumn("corporationID", "integer", array("limit" => 16)) ->addColumn("allianceID", "integer", array("limit" => 16)) ->addColumn("corporationName", "string", array("limit" => 128)) ->addColumn("ceoID", "integer", array("limit" => 16)) ->addColumn("corpTicker", "string", array("limit" => 6)) ->addColumn("memberCount", "integer", array("limit" => 5)) ->addColumn('information', 'text', array("limit" => MysqlAdapter::TEXT_MEDIUM)) ->addColumn('dateAdded', 'datetime', array('default' => 'CURRENT_TIMESTAMP')) ->addColumn('lastUpdated', 'datetime', array('default' => '0000-00-00 00:00:00')) ->addIndex(array("corporationID")) ->addIndex(array("allianceID")) ->addIndex(array("corporationName")) ->addIndex(array("lastUpdated")) ->save(); } }
<?php use Phinx\Db\Adapter\MysqlAdapter; use Phinx\Migration\AbstractMigration; class Corporations extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class */ public function change() { $corporations = $this->table('corporations', array("engine" => "TokuDB")); $corporations ->addColumn("corporationID", "integer", array("limit" => 16)) ->addColumn("allianceID", "integer", array("limit" => 16)) ->addColumn("corporationName", "string", array("limit" => 128)) ->addColumn("ceoID", "integer", array("limit" => 16)) ->addColumn("corpTicker", "string", array("limit" => 6)) ->addColumn("memberCount", "integer", array("limit" => 5)) ->addColumn('information', 'text', array("limit" => MysqlAdapter::TEXT_MEDIUM)) ->addColumn('dateAdded', 'datetime', array('default' => 'CURRENT_TIMESTAMP')) ->addColumn('lastUpdated', 'datetime', array('default' => '0000-00-00 00:00:00')) ->addIndex(array("corporationID", "corporationName"), array("unique" => true)) ->addIndex(array("allianceID")) ->addIndex(array("corporationName")) ->addIndex(array("lastUpdated")) ->save(); } }
Make sure to parse OBO documents in order
import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle, ordered=True) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
import os import fastobo from .base import BaseParser from ._fastobo import FastoboParser class OboParser(FastoboParser, BaseParser): @classmethod def can_parse(cls, path, buffer): return buffer.lstrip().startswith((b"format-version:", b"[Term", b"[Typedef")) def parse_from(self, handle): # Load the OBO document through an iterator using fastobo doc = fastobo.iter(handle) # Extract metadata from the OBO header and resolve imports self.ont.metadata = self.extract_metadata(doc.header()) self.ont.imports.update( self.process_imports( self.ont.metadata.imports, self.ont.import_depth, os.path.dirname(self.ont.path or str()), self.ont.timeout, ) ) # Extract frames from the current document. try: for frame in doc: if isinstance(frame, fastobo.term.TermFrame): self.enrich_term(frame) elif isinstance(frame, fastobo.typedef.TypedefFrame): self.enrich_relationship(frame) except SyntaxError as s: location = self.ont.path, s.lineno, s.offset, s.text raise SyntaxError(s.args[0], location) from None
Store merkle roots for 10 minutes
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice [email protected] import gevent, time, logging class Getwork_Store: """ Class that stores getworks so we can figure out the server again """ def __init__(self): self.data = {} gevent.spawn(self.prune) def add(self, merkle_root, data): """ Adds a merkle_root and a data value """ self.data[merkle_root] = (data, time.time()) def get(self, merkle_root): "" if self.data.has_key(merkle_root): return self.data[merkle_root][0] logging.debug('Merkle Root Not Found %s', merkle_root) return None def drop_roots(self): """ Resets the merkle_root database Very crude. Should probably have an invalidate block function instead """ self.data = {} def prune(self): """ Running greenlet that prunes old merkle_roots """ while True: for key, work in self.data.items(): if work[1] < (time.time() - (60*20)): del self.data[key] gevent.sleep(60)
#Copyright (C) 2011,2012 Colin Rice #This software is licensed under an included MIT license. #See the file entitled LICENSE #If you were not provided with a copy of the license please contact: # Colin Rice [email protected] import gevent, time, logging class Getwork_Store: """ Class that stores getworks so we can figure out the server again """ def __init__(self): self.data = {} gevent.spawn(self.prune) def add(self, merkle_root, data): """ Adds a merkle_root and a data value """ self.data[merkle_root] = (data, time.time()) def get(self, merkle_root): "" if self.data.has_key(merkle_root): return self.data[merkle_root][0] logging.debug('Merkle Root Not Found %s', merkle_root) return None def drop_roots(self): """ Resets the merkle_root database Very crude. Should probably have an invalidate block function instead """ self.data = {} def prune(self): """ Running greenlet that prunes old merkle_roots """ while True: for key, work in self.data.items(): if work[1] < (time.time() - (60*3)): del self.data[key] gevent.sleep(60)
Add bumpversion, sync package version
""" trafficserver_exporter ---------------------- An Apache Traffic Server metrics exporter for Prometheus. Uses the stats_over_http plugin to translate JSON data into Prometheus format. """ from setuptools import setup setup( name='trafficserver_exporter', version='0.0.3', author='Greg Dallavalle', description='Traffic Server metrics exporter for Prometheus', long_description=__doc__, license='Apache Software License 2.0', keywords='prometheus monitoring trafficserver', test_suite='tests', packages=['trafficserver_exporter'], entry_points={ 'console_scripts': [ 'trafficserver_exporter=trafficserver_exporter.__main__:main' ], }, install_requires=[ 'prometheus_client>=0.0.11', 'requests>=2.0.0' ], classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'License :: OSI Approved :: Apache Software License', ], )
""" trafficserver_exporter ---------------------- An Apache Traffic Server metrics exporter for Prometheus. Uses the stats_over_http plugin to translate JSON data into Prometheus format. """ from setuptools import setup setup( name='trafficserver_exporter', version='0.0.2', author='Greg Dallavalle', description='Traffic Server metrics exporter for Prometheus', long_description=__doc__, license='Apache Software License 2.0', keywords='prometheus monitoring trafficserver', test_suite='tests', packages=['trafficserver_exporter'], entry_points={ 'console_scripts': [ 'trafficserver_exporter=trafficserver_exporter.__main__:main' ], }, install_requires=[ 'prometheus_client>=0.0.11', 'requests>=2.0.0' ], classifiers=[ 'Development Status :: 3 - Alpha', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Intended Audience :: Information Technology', 'Intended Audience :: System Administrators', 'Topic :: System :: Monitoring', 'Topic :: System :: Networking :: Monitoring', 'License :: OSI Approved :: Apache Software License', ], )
Tag for Python 3 support.
#!/usr/bin/env python from distribute_setup import use_setuptools use_setuptools() from setuptools import setup from pudb import VERSION try: readme = open("README.rst") long_description = str(readme.read()) finally: readme.close() setup(name='pudb', version=VERSION, description='A full-screen, console-based Python debugger', long_description=long_description, author='Andreas Kloeckner', author_email='[email protected]', install_requires=[ "urwid>=0.9.9.2", "pygments>=1.0", ], url='http://pypi.python.org/pypi/pudb', classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Environment :: Console :: Curses", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development", "Topic :: Software Development :: Debuggers", "Topic :: Software Development :: Quality Assurance", "Topic :: System :: Recovery Tools", "Topic :: System :: Software Distribution", "Topic :: Terminals", "Topic :: Utilities", ], packages=["pudb"])
#!/usr/bin/env python from distribute_setup import use_setuptools use_setuptools() from setuptools import setup from pudb import VERSION try: readme = open("README.rst") long_description = str(readme.read()) finally: readme.close() setup(name='pudb', version=VERSION, description='A full-screen, console-based Python debugger', long_description=long_description, author='Andreas Kloeckner', author_email='[email protected]', install_requires=[ "urwid>=0.9.9.2", "pygments>=1.0", ], url='http://pypi.python.org/pypi/pudb', classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Environment :: Console :: Curses", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 2", "Topic :: Software Development", "Topic :: Software Development :: Debuggers", "Topic :: Software Development :: Quality Assurance", "Topic :: System :: Recovery Tools", "Topic :: System :: Software Distribution", "Topic :: Terminals", "Topic :: Utilities", ], packages=["pudb"])
Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): def executable(self, tool_locator): return tool_locator.find_executable("deagle") def name(self): return "Deagle" def version(self, executable): return self._version_from_tool(executable) def get_data_model(self, task): if isinstance(task.options, dict) and task.options.get("language") == "C": data_model = task.options.get("data_model") if data_model == "LP64": return ["--64"] return ["--32"] # default def cmdline(self, executable, options, task, rlimits): return [executable] + options + self.get_data_model(task) + list(task.input_files_or_identifier) def determine_result(self, run): status = result.RESULT_UNKNOWN output = run.output stroutput = str(output) if "SUCCESSFUL" in stroutput: status = result.RESULT_TRUE_PROP elif "FAILED" in stroutput: status = result.RESULT_FALSE_REACH else: status = result.RESULT_UNKNOWN return status
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool): def executable(self): return util.find_executable("deagle") def name(self): return "Deagle" def version(self, executable): return self._version_from_tool(executable) def cmdline(self, executable, options, tasks, propertyfile, rlimits): options = options + ["--32", "--no-unwinding-assertions", "--closure"] return [executable] + options + tasks def determine_result(self, returncode, returnsignal, output, isTimeout): status = result.RESULT_UNKNOWN stroutput = str(output) if isTimeout: status = "TIMEOUT" elif "SUCCESSFUL" in stroutput: status = result.RESULT_TRUE_PROP elif "FAILED" in stroutput: status = result.RESULT_FALSE_REACH elif "UNKNOWN" in stroutput: status = result.RESULT_UNKNOWN else: status = result.RESULT_UNKNOWN return status
Change endpoint to match spec
package uk.gov.dvla.services.enquiry; import uk.gov.dvla.domain.Driver; import uk.gov.dvla.domain.Person; import uk.gov.dvla.services.ManagedService; public interface DriverEnquiry extends ManagedService { public static final String EXTERNAL_DRIVER_URI = "/iiadd/api/v1/driver"; public static final String DRIVER_URI = "/driver/"; public static final String DLN_SEARCH = "dlnSearch"; public static final String PERSONAL_DETAILS_SEARCH = "personalDetailsSearch"; public static final String CUSTOMER_PORTAL = "customer.portal"; public static final String MIB = "mib"; public static final String DLN_PARAM = "dln"; public static final String ENQUIRY_ID_PARAM = "guid"; public static final String FORENAME_PARAM = "fn"; public static final String SURNAME_PARAM = "sn"; public static final String DOB_PARAM = "d"; public static final String GENDER_PARAM = "g"; public static final String POSTCODE_PARAM = "pc"; public static final String VEHICLE_REGISTRATION_MARK_PARAM = "vrm"; public static final String SERVICE_TYPE_PARAM = "type"; public static final String CONTACT_CHANNEL_PARAM = "cc"; public static final String ENQUIRY_REASON_PARAM = "er"; public Driver get(String dln); public Driver get(Person person); public Driver get(String forename, String surname, String dob, String gender, String postCode); }
package uk.gov.dvla.services.enquiry; import uk.gov.dvla.domain.Driver; import uk.gov.dvla.domain.Person; import uk.gov.dvla.services.ManagedService; public interface DriverEnquiry extends ManagedService { public static final String EXTERNAL_DRIVER_URI = "/mib/driver"; public static final String DRIVER_URI = "/driver/"; public static final String DLN_SEARCH = "dlnSearch"; public static final String PERSONAL_DETAILS_SEARCH = "personalDetailsSearch"; public static final String CUSTOMER_PORTAL = "customer.portal"; public static final String MIB = "mib"; public static final String DLN_PARAM = "dln"; public static final String ENQUIRY_ID_PARAM = "guid"; public static final String FORENAME_PARAM = "fn"; public static final String SURNAME_PARAM = "sn"; public static final String DOB_PARAM = "d"; public static final String GENDER_PARAM = "g"; public static final String POSTCODE_PARAM = "pc"; public static final String VEHICLE_REGISTRATION_MARK_PARAM = "vrm"; public static final String SERVICE_TYPE_PARAM = "type"; public static final String CONTACT_CHANNEL_PARAM = "cc"; public static final String ENQUIRY_REASON_PARAM = "er"; public Driver get(String dln); public Driver get(Person person); public Driver get(String forename, String surname, String dob, String gender, String postCode); }
Refactor encoders to have base class
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoderMixin(object): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) return super(JSONEncoderMixin, self).default(obj) class JSONEncoder(JSONEncoderMixin, _JSONEncoder): def default(self, obj): if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(JSONEncoderMixin, elasticsearch.serializer.JSONSerializer): def default(self, obj): try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
import logging import datetime import decimal import elasticsearch from bson import ObjectId, DBRef from nefertari.renderers import _JSONEncoder log = logging.getLogger(__name__) class JSONEncoder(_JSONEncoder): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, decimal.Decimal): return float(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if hasattr(obj, 'to_dict'): # If it got to this point, it means its a nested object. # outter objects would have been handled with DataProxy. return obj.to_dict(__nested=True) return super(JSONEncoder, self).default(obj) class ESJSONSerializer(elasticsearch.serializer.JSONSerializer): def default(self, obj): if isinstance(obj, (ObjectId, DBRef)): return str(obj) if isinstance(obj, (datetime.datetime, datetime.date)): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") # iso if isinstance(obj, datetime.time): return obj.strftime('%H:%M:%S') if isinstance(obj, datetime.timedelta): return obj.seconds if isinstance(obj, decimal.Decimal): return float(obj) try: return super(ESJSONSerializer, self).default(obj) except: import traceback log.error(traceback.format_exc())
Handle Django 1.4 nuance for the empty ModelMultipleChoiceField values
from django import forms from .models import ObjectSet def objectset_form_factory(Model, queryset=None): """Takes an ObjectSet subclass and defines a base form class. In addition, an optional queryset can be supplied to limit the choices for the objects. This uses the generic `objects` field rather being named after a specific type. """ # A few checks to keep things sane.. if not issubclass(Model, ObjectSet): raise TypeError('{0} must subclass ObjectSet'.format(Model.__name__)) instance = Model() if queryset is None: queryset = instance._object_class._default_manager.all() elif queryset.model is not instance._object_class: raise TypeError('ObjectSet of type {0}, not {1}' .format(instance._object_class.__name__, queryset.model.__name__)) label = getattr(Model, instance._set_object_rel).field.verbose_name class form_class(forms.ModelForm): objects = forms.ModelMultipleChoiceField(queryset, label=label, required=False) def save(self, *args, **kwargs): objects = self.cleaned_data.get('objects') # Django 1.4 nuance when working with an empty list. It is not # properly defined an empty query set if isinstance(objects, list) and not objects: objects = self.instance.__class__.objects.none() self.instance._pending = objects return super(form_class, self).save(*args, **kwargs) class Meta(object): model = Model exclude = (instance._set_object_rel,) form_class.__name__ = '{0}Form'.format(Model.__name__) return form_class
from django import forms from .models import ObjectSet def objectset_form_factory(Model, queryset=None): """Takes an ObjectSet subclass and defines a base form class. In addition, an optional queryset can be supplied to limit the choices for the objects. This uses the generic `objects` field rather being named after a specific type. """ # A few checks to keep things sane.. if not issubclass(Model, ObjectSet): raise TypeError('{0} must subclass ObjectSet'.format(Model.__name__)) instance = Model() if queryset is None: queryset = instance._object_class._default_manager.all() elif queryset.model is not instance._object_class: raise TypeError('ObjectSet of type {0}, not {1}' .format(instance._object_class.__name__, queryset.model.__name__)) label = getattr(Model, instance._set_object_rel).field.verbose_name class form_class(forms.ModelForm): objects = forms.ModelMultipleChoiceField(queryset, label=label, required=False) def save(self, *args, **kwargs): self.instance._pending = self.cleaned_data.get('objects') return super(form_class, self).save(*args, **kwargs) class Meta(object): model = Model exclude = (instance._set_object_rel,) form_class.__name__ = '{0}Form'.format(Model.__name__) return form_class
Use more precise grep expression Otherwise we match wrong lines when memory stats contain PID. Change-Id: I924c1b151ddaad8209445a514bf02a7af5d2e0e0 Reviewed-on: http://review.couchbase.org/79848 Reviewed-by: Pavel Paulau <[email protected]> Tested-by: Pavel Paulau <[email protected]>
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class PSStats(RemoteStats): METRICS = ( ("rss", 1024), # kB -> B ("vsize", 1024), ) PS_CMD = "ps -eo pid,rss,vsize,comm | " \ "grep {} | grep -v grep | sort -n -k 2 | tail -n 1" TOP_CMD = "top -b n2 -d1 -p {0} | grep ^{0}" @parallel_task(server_side=True) def get_server_samples(self, process): return self.get_samples(process) @parallel_task(server_side=False) def get_client_samples(self, process): return self.get_samples(process) def get_samples(self, process): samples = {} stdout = self.run(self.PS_CMD.format(process)) if stdout: for i, value in enumerate(stdout.split()[1:1 + len(self.METRICS)]): metric, multiplier = self.METRICS[i] title = "{}_{}".format(process, metric) samples[title] = float(value) * multiplier pid = stdout.split()[0] else: return samples stdout = self.run(self.TOP_CMD.format(pid)) if stdout: title = "{}_cpu".format(process) samples[title] = float(stdout.split()[8]) return samples
from cbagent.collectors.libstats.remotestats import RemoteStats, parallel_task class PSStats(RemoteStats): METRICS = ( ("rss", 1024), # kB -> B ("vsize", 1024), ) PS_CMD = "ps -eo pid,rss,vsize,comm | " \ "grep {} | grep -v grep | sort -n -k 2 | tail -n 1" TOP_CMD = "top -b n2 -d1 -p {0} | grep {0}" @parallel_task(server_side=True) def get_server_samples(self, process): return self.get_samples(process) @parallel_task(server_side=False) def get_client_samples(self, process): return self.get_samples(process) def get_samples(self, process): samples = {} stdout = self.run(self.PS_CMD.format(process)) if stdout: for i, value in enumerate(stdout.split()[1:1 + len(self.METRICS)]): metric, multiplier = self.METRICS[i] title = "{}_{}".format(process, metric) samples[title] = float(value) * multiplier pid = stdout.split()[0] else: return samples stdout = self.run(self.TOP_CMD.format(pid)) if stdout: title = "{}_cpu".format(process) samples[title] = float(stdout.split()[8]) return samples
Add support for configured tagName to HTMLMessage
/* global React */ /* jslint esnext:true */ import escape from '../escape'; import IntlMixin from '../mixin'; function escapeProps(props) { return Object.keys(props).reduce(function (escapedProps, name) { var value = props[name]; // TODO: Can we force string coersion here? Or would that not be needed // and possible mess with IntlMessageFormat? if (typeof value === 'string') { value = escape(value); } escapedProps[name] = value; return escapedProps; }, {}); } var IntlHTMLMessage = React.createClass({ displayName: 'IntlHTMLMessage', mixins : [IntlMixin], getDefaultProps: function () { return {__tagName: 'span'}; }, render: function () { var props = this.props; var tagName = props.__tagName; var message = props.children; var escapedProps = escapeProps(props); // Since the message presumably has HTML in it, we need to set // `innerHTML` in order for it to be rendered and not escaped by React. // To be safe, we are escaping all string prop values before formatting // the message. It is assumed that the message is not UGC, and came from // the developer making it more like a template. return React.DOM[tagName]({ dangerouslySetInnerHTML: { __html: this.formatMessage(message, escapedProps) } }); } }); export default IntlHTMLMessage;
/* global React */ /* jslint esnext:true */ import escape from '../escape'; import IntlMixin from '../mixin'; function escapeProps(props) { return Object.keys(props).reduce(function (escapedProps, name) { var value = props[name]; // TODO: Can we force string coersion here? Or would that not be needed // and possible mess with IntlMessageFormat? if (typeof value === 'string') { value = escape(value); } escapedProps[name] = value; return escapedProps; }, {}); } var IntlHTMLMessage = React.createClass({ displayName: 'HTMLMessage', mixins : [IntlMixin], render: function () { var message = React.Children.only(this.props.children); var escapedProps = escapeProps(this.props); // Since the message presumably has HTML in it, we need to set // `innerHTML` in order for it to be rendered and not escaped by React. // To be safe, we are escaping all string prop values before formatting // the message. It is assumed that the message is not UGC, and came from // the developer making it more like a template. return React.DOM.span({ dangerouslySetInnerHTML: { __html: this.formatMessage(message, escapedProps) } }); } }); export default IntlHTMLMessage;
Fix typo bug in sap b1 http POST to sap
import _ from 'underscore'; import { HTTP } from 'meteor/http' /** * SAP B1 Integration Methods */ Meteor.methods({ 'sapB1integration/testConnectionToWindowsService': (sapServerIpAddress) => { if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock() let connectionStatusResponse = Meteor.http.call("GET", `${sapServerIpAddress}:9080/api/payrun`); return connectionStatusResponse }, 'sapB1integration/postPayrunResults': (payRunResult, periodMonth, periodYear, sapServerIpAddress) => { if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock() // if(sapServerIpAddress.startsWith("http://")) { // // } //-- let postData = JSON.stringify(payRunResult) postData = "=" + postData; // A quirk of the C# REST API on the windows service HTTP.call('POST', `${sapServerIpAddress}:9080/api/payrun`, {data: postData}, (error, result) => { if (!error) { console.log(`Payrun batch result: \n${JSON.stringify(result)}`) } }); } });
import _ from 'underscore'; import { HTTP } from 'meteor/http' /** * SAP B1 Integration Methods */ Meteor.methods({ 'sapB1integration/testConnectionToWindowsService': (sapServerIpAddress) => { if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock() let connectionStatusResponse = Meteor.http.call("GET", `${sapServerIpAddress}:9080/api/payrun`); return connectionStatusResponse }, 'sapB1integration/postPayrunResults': (payRunResult, periodMonth, periodYear, sapServerIpAddress) => { if (!this.userId && Core.hasPayrollAccess(this.userId)) { throw new Meteor.Error(401, "Unauthorized"); } let userId = Meteor.userId(); this.unblock() // if(sapServerIpAddress.startsWith("http://")) { // // } //-- let postData = JSON.stringify(payRunResult) postData = "=" + postData; // A quirk of the C# REST API on the windows service // HTTP.call('POST', `${sapServerIpAddress}:9080/api/payrun`, {data: postData}, () => (error, result) { // if (!error) { // console.log(`Payrun batch result: \n${JSON.stringify(result)}`) // // } // }); } });
Fix TPS warning messages being sent too many times
package ee.ellytr.autoclick.tps; import ee.ellytr.autoclick.EllyCheat; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class TPSRunnable implements Runnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { double tps = Math.round(TPSTracker.getTPS() * 100.0) / 100.0; if (tps <= EllyCheat.getInstance().getConfig().getInt("tps-warning")) { if (player.hasPermission("ellycheat.cps.warning")) { player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!"); } if (EllyCheat.getInstance().getConfig().getBoolean("log-warnings")) { Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!"); } } } Bukkit.getScheduler().runTaskLaterAsynchronously(EllyCheat.getInstance(), this, 20); } }
package ee.ellytr.autoclick.tps; import ee.ellytr.autoclick.EllyCheat; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class TPSRunnable implements Runnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { double tps = Math.round(TPSTracker.getTPS() * 100.0) / 100.0; if (tps <= EllyCheat.getInstance().getConfig().getInt("tps-warning")) { for (Player player2 : Bukkit.getOnlinePlayers()) { if (player2.hasPermission("ellycheat.cps.warning")) { player2.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!"); } } if (EllyCheat.getInstance().getConfig().getBoolean("log-warnings")) { Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!"); } } } Bukkit.getScheduler().runTaskLaterAsynchronously(EllyCheat.getInstance(), this, 20); } }
Replace removed middleware with equivalent current middleware
<?php namespace LaravelAcl\Authentication\Tests\Unit; use Illuminate\Support\Facades\Route; use Mockery as m; class ClientLoggedFilterTest extends TestCase { protected $custom_url = '/custom'; public function setUp() { parent::setUp(); Route::get('check', ['middleware' => 'admin_logged', 'uses' => function(){return '';}]); Route::get('check_custom', ['middleware' => "admin_logged:{$this->custom_url}", 'uses' => function(){return '';}]); } public function tearDown() { m::close(); } /** * @test **/ public function permitAccessToLoggedUsers() { $this->authCheck(true); $this->call('GET', 'check'); } /** * @test **/ public function redirectToLoginAnonymousUsers() { $this->authCheck(true); $this->call('GET', 'check'); $this->assertRedirectedTo('/login'); } /** * @test **/ public function redirectToCustomUrlAnonymousUsers() { $this->authCheck(true); $this->call('GET', 'check_custom'); $this->assertRedirectedTo($this->custom_url); } /** * @param $true */ private function authCheck($true) { $auth_success = m::mock('StdClass'); $auth_success->shouldReceive('check')->andReturn($true); } }
<?php namespace LaravelAcl\Authentication\Tests\Unit; use Illuminate\Support\Facades\Route; use Mockery as m; class ClientLoggedFilterTest extends TestCase { protected $custom_url = '/custom'; public function setUp() { parent::setUp(); Route::get('check', ['middleware' => 'logged', 'uses' => function(){return '';}]); Route::get('check_custom', ['middleware' => "logged:{$this->custom_url}", 'uses' => function(){return '';}]); } public function tearDown() { m::close(); } /** * @test **/ public function permitAccessToLoggedUsers() { $this->authCheck(true); $this->call('GET', 'check'); } /** * @test **/ public function redirectToLoginAnonymousUsers() { $this->authCheck(true); $this->call('GET', 'check'); $this->assertRedirectedTo('/login'); } /** * @test **/ public function redirectToCustomUrlAnonymousUsers() { $this->authCheck(true); $this->call('GET', 'check_custom'); $this->assertRedirectedTo($this->custom_url); } /** * @param $true */ private function authCheck($true) { $auth_success = m::mock('StdClass'); $auth_success->shouldReceive('check')->andReturn($true); } }
Remove import of non-existent module
import { observable, action, runInAction } from 'mobx' import axios from 'axios' class AppState { @observable authenticated = false; @observable authenticating = false; @observable items = []; @observable item = {}; // constructor() { // this.authenticated = false; // this.authenticating = false; // this.items = []; // this.item = {}; // } @action async fetchData(next = () => {}) { const APIURL = 'http://localhost:3000/?limit=1000'; try { let {data} = await axios.get(APIURL) // this.setOrders(data); runInAction(() => this.items.replace(data)) } catch (e) { // this.setOrders([]); runInAction(() => this.items.replace([])) } next(); } @action setOrders(data) { // this.items = data.map(item => new OrderModel(item)); this.items.replace(data); } @action setData(data) { this.items = data } @action setSingle(data) { this.item = data } @action clearItems() { this.items = [] this.item = {} } @action authenticate() { return new Promise((resolve,reject) => { this.authenticating = true setTimeout(() => { this.authenticated = !this.authenticated this.authenticating = false resolve(this.authenticated) }, 0) }) } } export default AppState;
import { observable, action, runInAction } from 'mobx' import axios from 'axios' import OrderModel from '../models/OrderModel'; class AppState { @observable authenticated = false; @observable authenticating = false; @observable items = []; @observable item = {}; // constructor() { // this.authenticated = false; // this.authenticating = false; // this.items = []; // this.item = {}; // } @action async fetchData(next = () => {}) { const APIURL = 'http://localhost:3000/?limit=1000'; try { let {data} = await axios.get(APIURL) // this.setOrders(data); runInAction(() => this.items.replace(data)) } catch (e) { // this.setOrders([]); runInAction(() => this.items.replace([])) } next(); } @action setOrders(data) { // this.items = data.map(item => new OrderModel(item)); this.items.replace(data); } @action setData(data) { this.items = data } @action setSingle(data) { this.item = data } @action clearItems() { this.items = [] this.item = {} } @action authenticate() { return new Promise((resolve,reject) => { this.authenticating = true setTimeout(() => { this.authenticated = !this.authenticated this.authenticating = false resolve(this.authenticated) }, 0) }) } } export default AppState;
Fix tests for legacy phpunit versions
<?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\Validator; /** * A list of constraint violations. * * @author Bernhard Schussek <[email protected]> */ interface ConstraintViolationListInterface extends \Traversable, \Countable, \ArrayAccess { /** * Adds a constraint violation to this list. */ public function add(ConstraintViolationInterface $violation); /** * Merges an existing violation list into this list. */ public function addAll(ConstraintViolationListInterface $otherList); /** * Returns the violation at a given offset. * * @param int $offset The offset of the violation * * @return ConstraintViolationInterface The violation * * @throws \OutOfBoundsException if the offset does not exist */ public function get($offset); /** * Returns whether the given offset exists. * * @param int $offset The violation offset * * @return bool Whether the offset exists */ public function has($offset); /** * Sets a violation at a given offset. * * @param int $offset The violation offset * @param ConstraintViolationInterface $violation The violation */ public function set($offset, ConstraintViolationInterface $violation); /** * Removes a violation at a given offset. * * @param int $offset The offset to remove */ public function remove($offset); }
<?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\Validator; /** * A list of constraint violations. * * @author Bernhard Schussek <[email protected]> */ interface ConstraintViolationListInterface extends \Traversable, \Countable, \ArrayAccess { /** * Adds a constraint violation to this list. */ public function add(ConstraintViolationInterface $violation); /** * Merges an existing violation list into this list. */ public function addAll(self $otherList); /** * Returns the violation at a given offset. * * @param int $offset The offset of the violation * * @return ConstraintViolationInterface The violation * * @throws \OutOfBoundsException if the offset does not exist */ public function get($offset); /** * Returns whether the given offset exists. * * @param int $offset The violation offset * * @return bool Whether the offset exists */ public function has($offset); /** * Sets a violation at a given offset. * * @param int $offset The violation offset * @param ConstraintViolationInterface $violation The violation */ public function set($offset, ConstraintViolationInterface $violation); /** * Removes a violation at a given offset. * * @param int $offset The offset to remove */ public function remove($offset); }
Correct module name (ord.ode4j -> org.ode4j)
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ module org.ode4j.cpp { requires transitive org.ode4j; exports org.ode4j.cpp.internal; exports org.ode4j.cpp; }
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ module ord.ode4j.cpp { requires transitive org.ode4j; exports org.ode4j.cpp.internal; exports org.ode4j.cpp; }
Enable the consul secret engine
"""Vault secrets engines endpoints""" from hvac.api.secrets_engines.aws import Aws from hvac.api.secrets_engines.azure import Azure from hvac.api.secrets_engines.gcp import Gcp from hvac.api.secrets_engines.identity import Identity from hvac.api.secrets_engines.kv import Kv from hvac.api.secrets_engines.pki import Pki from hvac.api.secrets_engines.kv_v1 import KvV1 from hvac.api.secrets_engines.kv_v2 import KvV2 from hvac.api.secrets_engines.transit import Transit from hvac.api.secrets_engines.database import Database from hvac.api.secrets_engines.consul import Consul from hvac.api.vault_api_category import VaultApiCategory __all__ = ( 'Aws', 'Azure', 'Gcp', 'Identity', 'Kv', 'KvV1', 'KvV2', 'Pki', 'Transit', 'SecretsEngines', 'Database' ) class SecretsEngines(VaultApiCategory): """Secrets Engines.""" implemented_classes = [ Aws, Azure, Gcp, Identity, Kv, Pki, Transit, Database, Consul, ] unimplemented_classes = [ 'Ad', 'AliCloud', 'Azure', 'GcpKms', 'Nomad', 'RabbitMq', 'Ssh', 'TOTP', 'Cassandra', 'MongoDb', 'Mssql', 'MySql', 'PostgreSql', ]
"""Vault secrets engines endpoints""" from hvac.api.secrets_engines.aws import Aws from hvac.api.secrets_engines.azure import Azure from hvac.api.secrets_engines.gcp import Gcp from hvac.api.secrets_engines.identity import Identity from hvac.api.secrets_engines.kv import Kv from hvac.api.secrets_engines.pki import Pki from hvac.api.secrets_engines.kv_v1 import KvV1 from hvac.api.secrets_engines.kv_v2 import KvV2 from hvac.api.secrets_engines.transit import Transit from hvac.api.secrets_engines.database import Database from hvac.api.vault_api_category import VaultApiCategory __all__ = ( 'Aws', 'Azure', 'Gcp', 'Identity', 'Kv', 'KvV1', 'KvV2', 'Pki', 'Transit', 'SecretsEngines', 'Database' ) class SecretsEngines(VaultApiCategory): """Secrets Engines.""" implemented_classes = [ Aws, Azure, Gcp, Identity, Kv, Pki, Transit, Database, ] unimplemented_classes = [ 'Ad', 'AliCloud', 'Azure', 'Consul', 'GcpKms', 'Nomad', 'RabbitMq', 'Ssh', 'TOTP', 'Cassandra', 'MongoDb', 'Mssql', 'MySql', 'PostgreSql', ]
Drop wrap content starting with text/html New versions of Django give HTML responses with the content type 'text/html; charset: utf-8'. We don't want to wrap that, so only check for a start of text/html.
from django.http import HttpResponse import json class NonHtmlDebugToolbarMiddleware(object): """ The Django Debug Toolbar usually only works for views that return HTML. This middleware wraps any non-HTML response in HTML if the request has a 'debug' query parameter (e.g. http://localhost/foo?debug) Special handling for json (pretty printing) and binary data (only show data length). Based on http://stackoverflow.com/a/19249559/10817 """ @staticmethod def process_response(request, response): if request.GET.get('debug') == '': if response['Content-Type'] == 'application/octet-stream': new_content = '<html><body>Binary Data, ' \ 'Length: {}</body></html>'.format(len(response.content)) response = HttpResponse(new_content) elif not response['Content-Type'].startswith('text/html'): content = response.content try: json_ = json.loads(content) content = json.dumps(json_, sort_keys=True, indent=2) except ValueError: pass response = HttpResponse('<html><body><pre>{}' '</pre></body></html>'.format(content)) return response # Middleware classes for debug toolbar. middleware = ('debug_toolbar.middleware.DebugToolbarMiddleware', 'server.debug.NonHtmlDebugToolbarMiddleware')
from django.http import HttpResponse import json class NonHtmlDebugToolbarMiddleware(object): """ The Django Debug Toolbar usually only works for views that return HTML. This middleware wraps any non-HTML response in HTML if the request has a 'debug' query parameter (e.g. http://localhost/foo?debug) Special handling for json (pretty printing) and binary data (only show data length). Based on http://stackoverflow.com/a/19249559/10817 """ @staticmethod def process_response(request, response): if request.GET.get('debug') == '': if response['Content-Type'] == 'application/octet-stream': new_content = '<html><body>Binary Data, ' \ 'Length: {}</body></html>'.format(len(response.content)) response = HttpResponse(new_content) elif response['Content-Type'] != 'text/html': content = response.content try: json_ = json.loads(content) content = json.dumps(json_, sort_keys=True, indent=2) except ValueError: pass response = HttpResponse('<html><body><pre>{}' '</pre></body></html>'.format(content)) return response # Middleware classes for debug toolbar. middleware = ('debug_toolbar.middleware.DebugToolbarMiddleware', 'server.debug.NonHtmlDebugToolbarMiddleware')
Remove unused import, make sure balance is reflected correctly
import { roundBalance } from '../../common/tools'; import { info } from '../broadcast'; let balanceStr = ''; export default Engine => class Balance extends Engine { observeBalance() { this.listen('balance', r => { const { balance: { balance: b, currency }, } = r; this.balance = roundBalance({ currency, balance: b }); balanceStr = `${this.balance} ${currency}`; info({ accountID: this.accountInfo.loginid, balance: balanceStr }); }); } // eslint-disable-next-line class-methods-use-this getBalance(type) { const { scope } = this.store.getState(); let { balance } = this; // Deduct trade `amount` in this scope for correct value in `balance`-block if (scope === 'BEFORE_PURCHASE') { balance = roundBalance({ currency: this.tradeOptions.currency, balance : Number(balance) - this.tradeOptions.amount, }); balanceStr = `${balance} ${this.tradeOptions.currency}`; } return type === 'STR' ? balanceStr : Number(balance); } };
import { roundBalance } from '../../common/tools'; import { info } from '../broadcast'; import { doUntilDone } from '../tools'; let balanceStr = ''; export default Engine => class Balance extends Engine { observeBalance() { this.listen('balance', r => { const { balance: { balance: b, currency }, } = r; this.balance = roundBalance({ currency, balance: b }); balanceStr = `${this.balance} ${currency}`; info({ accountID: this.accountInfo.loginid, balance: balanceStr }); }); } // eslint-disable-next-line class-methods-use-this getBalance(type) { const { scope } = this.store.getState(); // Deduct trade `amount` in this scope for correct value in `balance`-block if (scope === 'BEFORE_PURCHASE') { this.balance = roundBalance({ currency: this.tradeOptions.currency, balance : Number(this.balance) - this.tradeOptions.amount, }); balanceStr = `${this.balance} ${this.tradeOptions.currency}`; } return type === 'STR' ? balanceStr : Number(this.balance); } };
Rename generated specimen component to make eslint happy
// Higher-order Specimen which provides theme import React, {PropTypes} from 'react'; import Span from './Span'; import parseSpecimenOptions from '../../utils/parseSpecimenOptions'; import parseSpecimenBody from '../../utils/parseSpecimenBody'; const identity = (v) => v; export default function Specimen(mapBodyToProps = identity, mapOptionsToProps = []) { const parseOptions = parseSpecimenOptions(mapOptionsToProps); const parseBody = parseSpecimenBody(mapBodyToProps); return (WrappedSpecimen) => { const SpecimenContainer = (props, {theme}) => { const {rawOptions, rawBody} = props; const optionProps = parseOptions(rawOptions); const bodyProps = parseBody(rawBody); const span = props.span || optionProps.span; if (Array.isArray(bodyProps)) { return ( <Span span={span}> {bodyProps.map((specimenProps, i) => ( <Span key={i} span={specimenProps.span}> <WrappedSpecimen {...optionProps} {...specimenProps} {...props} theme={theme} /> </Span> ))} </Span> ); } return ( <Span span={span}> <WrappedSpecimen {...optionProps} {...bodyProps} {...props} theme={theme} /> </Span> ); }; SpecimenContainer.propTypes = { span: PropTypes.number, rawBody: PropTypes.string, rawOptions: PropTypes.string }; SpecimenContainer.contextTypes = { theme: PropTypes.object.isRequired }; return SpecimenContainer; }; }
// Higher-order Specimen which provides theme import React, {PropTypes} from 'react'; import Span from './Span'; import parseSpecimenOptions from '../../utils/parseSpecimenOptions'; import parseSpecimenBody from '../../utils/parseSpecimenBody'; const identity = (v) => v; export default function Specimen(mapBodyToProps = identity, mapOptionsToProps = []) { const parseOptions = parseSpecimenOptions(mapOptionsToProps); const parseBody = parseSpecimenBody(mapBodyToProps); return (WrappedSpecimen) => { const Specimen = (props, {theme}) => { const {rawOptions, rawBody} = props; const optionProps = parseOptions(rawOptions); const bodyProps = parseBody(rawBody); const span = props.span || optionProps.span; if (Array.isArray(bodyProps)) { return ( <Span span={span}> {bodyProps.map((specimenProps, i) => ( <Span key={i} span={specimenProps.span}> <WrappedSpecimen {...optionProps} {...specimenProps} {...props} theme={theme} /> </Span> ))} </Span> ); } return ( <Span span={span}> <WrappedSpecimen {...optionProps} {...bodyProps} {...props} theme={theme} /> </Span> ); }; Specimen.propTypes = { span: PropTypes.number, rawBody: PropTypes.string, rawOptions: PropTypes.string }; Specimen.contextTypes = { theme: PropTypes.object.isRequired }; return Specimen; }; }
FIX Format String Error in Conector Driver Comando
# -*- coding: iso-8859-1 -*- from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): # logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) logging.getLogger().info("inicializando ConectorDriverComando driver de '${0}'".format(driver)) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): # logging.getLogger().info("Enviando comando %s" % args) logging.getLogger().info("Enviando comando '${0}'".format(args)) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None
# -*- coding: iso-8859-1 -*- from serial import SerialException import importlib import threading import logging class ConectorError(Exception): pass class ConectorDriverComando: driver = None def __init__(self, comando, driver, *args, **kwargs): logging.getLogger().info("inicializando ConectorDriverComando driver de %s" % driver) self._comando = comando self.driver_name = driver # instanciar el driver dinamicamente segun el driver pasado como parametro libraryName = "Drivers." + driver + "Driver" driverModule = importlib.import_module(libraryName) driverClass = getattr(driverModule, driver + "Driver") self.driver = driverClass(**kwargs) def sendCommand(self, *args): logging.getLogger().info("Enviando comando %s" % args) return self.driver.sendCommand(*args) def close(self): # Si el driver es Receipt, se cierra desde la misma clase del driver, sino, tira error de Bad File Descriptor por querer cerrarlo dos veces. if self.driver_name == "ReceiptDirectJet": if self.driver.connected is False: return None self.driver.close() self.driver = None
Change directory to test uninitialized project
from tests.test_actions import * from ltk import actions, exceptions import unittest class TestInitAction(unittest.TestCase): def test_uninitialized(self): # todo create dir outside so folder not initialized os.chdir('/') self.assertRaises(exceptions.UninitializedError, actions.Action, os.getcwd()) def test_init_host(self): create_config() action = actions.Action(os.getcwd()) assert action.host cleanup() def test_init_access_token(self): create_config() action = actions.Action(os.getcwd()) assert action.access_token cleanup() def test_init_project_id(self): create_config() action = actions.Action(os.getcwd()) assert action.project_id cleanup() def test_init_path(self): create_config() action = actions.Action(os.getcwd()) assert action.path cleanup() def test_init_community_id(self): create_config() action = actions.Action(os.getcwd()) assert action.community_id cleanup() def test_init_api(self): create_config() action = actions.Action(os.getcwd()) assert action.api cleanup() def test_init_doc_manager(self): create_config() action = actions.Action(os.getcwd()) assert action.doc_manager cleanup() if __name__ == '__main__': unittest.main()
from tests.test_actions import * from ltk import actions, exceptions import unittest class TestInitAction(unittest.TestCase): def test_uninitialized(self): # todo create dir outside so folder not initialized self.assertRaises(exceptions.UninitializedError, actions.Action, os.getcwd()) def test_init_host(self): create_config() action = actions.Action(os.getcwd()) assert action.host cleanup() def test_init_access_token(self): create_config() action = actions.Action(os.getcwd()) assert action.access_token cleanup() def test_init_project_id(self): create_config() action = actions.Action(os.getcwd()) assert action.project_id cleanup() def test_init_path(self): create_config() action = actions.Action(os.getcwd()) assert action.path cleanup() def test_init_community_id(self): create_config() action = actions.Action(os.getcwd()) assert action.community_id cleanup() def test_init_api(self): create_config() action = actions.Action(os.getcwd()) assert action.api cleanup() def test_init_doc_manager(self): create_config() action = actions.Action(os.getcwd()) assert action.doc_manager cleanup() # if __name__ == '__main__': # unittest.main()
Fix namespace in autoload list.
<?php namespace Studio\Parts\Composer; use League\Flysystem\Filesystem; use Studio\Parts\AbstractPart; class Part extends AbstractPart { public function setupPackage($composer, Filesystem $target) { // Ask for package name $composer->name = $this->input->ask( 'Please name this package', '/[[:alnum:]]+\/[[:alnum:]]+/' ); // Ask for the root namespace $namespace = $this->input->ask( 'Please provide a default namespace (PSR-4)', '/([[:alnum:]]+\\\\?)+/', $this->makeDefaultNamespace($composer->name) ); // Normalize and store the namespace $namespace = rtrim($namespace, '\\'); @$composer->autoload->{'psr-4'}->{"$namespace\\"} = 'src/'; // Create an example file $this->copyTo( __DIR__ . '/stubs/src/Example.php', $target, 'src/Example.php', function ($content) use ($namespace) { return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content); } ); } protected function makeDefaultNamespace($package) { list($vendor, $name) = explode('/', $package); return ucfirst($vendor) . '\\' . ucfirst($name); } }
<?php namespace Studio\Parts\Composer; use League\Flysystem\Filesystem; use Studio\Parts\AbstractPart; class Part extends AbstractPart { public function setupPackage($composer, Filesystem $target) { // Ask for package name $composer->name = $this->input->ask( 'Please name this package', '/[[:alnum:]]+\/[[:alnum:]]+/' ); // Ask for the root namespace $namespace = $this->input->ask( 'Please provide a default namespace (PSR-4)', '/([[:alnum:]]+\\\\?)+/', $this->makeDefaultNamespace($composer->name) ); // Normalize and store the namespace $namespace = rtrim($namespace, '\\'); @$composer->autoload->{'psr-4'}->{$namespace} = 'src/'; // Create an example file $this->copyTo( __DIR__ . '/stubs/src/Example.php', $target, 'src/Example.php', function ($content) use ($namespace) { return preg_replace('/namespace[^;]+;/', "namespace $namespace;", $content); } ); } protected function makeDefaultNamespace($package) { list($vendor, $name) = explode('/', $package); return ucfirst($vendor) . '\\' . ucfirst($name); } }
Allow to search for project tags
// -*- coding: utf-8 -*- // // (c) 2014 Bjoern Ricks <[email protected]> // // See LICENSE comming with the source of 'trex' for details. // 'use strict'; var trexServices = angular.module('trex.services', ['ngResource']); trexServices.factory('Conf', function($location) { function getRootUrl() { var rootUrl = $location.protocol() + '://' + $location.host(); if ($location.port()) rootUrl += ':' + $location.port(); return rootUrl; }; return { 'apiBase': '/api/1', 'rootUrl': getRootUrl() }; }); trexServices.factory('Project', ['$resource', 'Conf', function($resource, Conf) { return $resource(Conf.apiBase + '/projects/:projectId', {projectId: '@id'}, {entries: {method: 'GET', isArray: true, url: Conf.apiBase + '/projects/:projectId/entries', params: {projectId: '@id'} }, tags: {method: 'GET', isArray: true, url: Conf.apiBase + '/projects/:projectId/tags', params: {projectId: '@id'} } } ); } ]); trexServices.factory('Entry', ['$resource', 'Conf', function($resource, Conf) { return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, { }); } ]);
// -*- coding: utf-8 -*- // // (c) 2014 Bjoern Ricks <[email protected]> // // See LICENSE comming with the source of 'trex' for details. // 'use strict'; var trexServices = angular.module('trex.services', ['ngResource']); trexServices.factory('Conf', function($location) { function getRootUrl() { var rootUrl = $location.protocol() + '://' + $location.host(); if ($location.port()) rootUrl += ':' + $location.port(); return rootUrl; }; return { 'apiBase': '/api/1', 'rootUrl': getRootUrl() }; }); trexServices.factory('Project', ['$resource', 'Conf', function($resource, Conf) { return $resource(Conf.apiBase + '/projects/:projectId', {projectId: '@id'}, {entries: {method: 'GET', isArray: true, url: Conf.apiBase + '/projects/:projectId/entries', params: {projectId: '@id'} } } ); } ]); trexServices.factory('Entry', ['$resource', 'Conf', function($resource, Conf) { return $resource(Conf.apiBase + '/entries/:entryId', {entryId: '@id'}, { }); } ]);
Fix versioning from git after `setup.py install` When following the `README`, __init__.py raised an "IOError: [Errno 2] No such file or directory:" about `setup.py`.
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = None else: __version__ = _dist.version if not __version__: try: # try to parse from setup.py for l in open(os.path.join(__path__[0], '..', 'setup.py')): if l.startswith("version = '"): __version__ = l.split("'")[1] break except: pass finally: if not __version__: __version__ = 'undefined' # add git revision and commit status try: rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' except: pass # ########### endversion ##################
# -*- coding: utf-8 -*- # ############# version ################## from pkg_resources import get_distribution, DistributionNotFound import os.path import subprocess try: _dist = get_distribution('pyethapp') # Normalize case for Windows systems dist_loc = os.path.normcase(_dist.location) here = os.path.normcase(__file__) if not here.startswith(os.path.join(dist_loc, 'pyethapp')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = None else: __version__ = _dist.version if not __version__: try: # try to parse from setup.py for l in open(os.path.join(__path__[0], '..', 'setup.py')): if l.startswith("version = '"): __version__ = l.split("'")[1] break finally: if not __version__: __version__ = 'undefined' # add git revision and commit status try: rev = subprocess.check_output(['git', 'rev-parse', 'HEAD']) is_dirty = len(subprocess.check_output(['git', 'diff', '--shortstat']).strip()) __version__ += '-' + rev[:4] + '-dirty' if is_dirty else '' except: pass # ########### endversion ##################
Add test for too short isin
package name.abuchen.portfolio.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class IsinTest { @Test public void testValidIsin() { String ubsIsin = "CH0244767585"; assertTrue(Isin.isValid(ubsIsin)); String adidasIsin = "DE000A1EWWW0"; assertTrue(Isin.isValid(adidasIsin)); String toyotaIsin = "JP3633400001"; assertTrue(Isin.isValid(toyotaIsin)); } @Test public void testInvalidIsin() { String invalidUbsIsin = "CH0244767586"; // Wrong Checksum assertFalse(Isin.isValid(invalidUbsIsin)); } @Test public void testIsinInvalidLength() { String isinTooLong = "CH0244767585222222"; assertFalse(Isin.isValid(isinTooLong)); String isinTooShort = "CH02381"; assertFalse(Isin.isValid(isinTooShort)); } @Test public void testIsinNull() { String nullIsin = null; assertFalse(Isin.isValid(nullIsin)); } @Test public void testInvalidChar() { String invalidCharIsin = "ÜE0244767585"; assertFalse(Isin.isValid(invalidCharIsin)); } }
package name.abuchen.portfolio.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class IsinTest { @Test public void testValidIsin() { String ubsIsin = "CH0244767585"; assertTrue(Isin.isValid(ubsIsin)); String adidasIsin = "DE000A1EWWW0"; assertTrue(Isin.isValid(adidasIsin)); String toyotaIsin = "JP3633400001"; assertTrue(Isin.isValid(toyotaIsin)); } @Test public void testInvalidIsin() { String invalidUbsIsin = "CH0244767586"; // Wrong Checksum assertFalse(Isin.isValid(invalidUbsIsin)); } @Test public void testIsinTooLong() { String isinTooLong = "CH0244767585222222"; assertFalse(Isin.isValid(isinTooLong)); } @Test public void testIsinNull() { String nullIsin = null; assertFalse(Isin.isValid(nullIsin)); } @Test public void testInvalidChar() { String invalidCharIsin = "ÜE0244767585"; assertFalse(Isin.isValid(invalidCharIsin)); } }
Fix styled-components API for ProjectDescription
import React from 'react'; import styled from 'styled-components'; import Linkify from 'linkifyjs/react'; import { generateTimeRange } from '../../utils/date.utils'; import { Section, SectionBody, SectionTitle } from '../Section'; import { CompanyName as ProjectName, Job as ProjectContainer, JobDescription, JobInfos as ProjectInfoContainer, WorkedTime as ProjectTime, } from '../Jobs'; import projects from '../../globals/data/projects'; const ProjectsSection = styled(Section)` page-break-inside: auto; `; const ProjectDescription = styled(JobDescription)``.withComponent(Linkify); export default () => { return ( <ProjectsSection> <SectionTitle title="Projects" /> <SectionBody> {projects.map(project => { return ( <ProjectContainer key={project.id}> <ProjectInfoContainer> <ProjectName>{project.name}</ProjectName> <ProjectTime>{generateTimeRange(project.timeInit, project.timeEnd)}</ProjectTime> </ProjectInfoContainer> {project.description.map((desc, index) => { return ( <ProjectDescription key={index + desc.substr(0, 10)}>{desc}</ProjectDescription> ); })} </ProjectContainer> ); })} </SectionBody> </ProjectsSection> ); };
import React from 'react'; import styled from 'styled-components'; import Linkify from 'linkifyjs/react'; import { generateTimeRange } from '../../utils/date.utils'; import { Section, SectionBody, SectionTitle } from '../Section'; import { CompanyName as ProjectName, Job as ProjectContainer, JobDescription, JobInfos as ProjectInfoContainer, WorkedTime as ProjectTime, } from '../Jobs'; import projects from '../../globals/data/projects'; const ProjectsSection = styled(Section)` page-break-inside: auto; `; /* TODO: Fix it */ // const ProjectDescription = styled(Linkify)``.extend(JobDescription); const ProjectDescription = styled(Linkify)`` export default () => { return ( <ProjectsSection> <SectionTitle title="Projects" /> <SectionBody> {projects.map(project => { return ( <ProjectContainer key={project.id}> <ProjectInfoContainer> <ProjectName>{project.name}</ProjectName> <ProjectTime>{generateTimeRange(project.timeInit, project.timeEnd)}</ProjectTime> </ProjectInfoContainer> {project.description.map((desc, index) => { return ( <ProjectDescription key={index + desc.substr(0, 10)}>{desc}</ProjectDescription> ); })} </ProjectContainer> ); })} </SectionBody> </ProjectsSection> ); };
Remove invalid keyword from parameters dictionary
import os from threading import Thread from werkzeug._reloader import ReloaderLoop class Watcher(Thread, ReloaderLoop): def __init__(self, paths, static, tasks, interval=1, *args, **kwargs): self.paths = paths self.static = static self.tasks = tasks self.debug = kwargs.get('debug') del kwargs['debug'] super(Watcher, self).__init__(*args, **kwargs) ReloaderLoop.__init__(self, interval=interval) def run(self): times = {} while not self._Thread__stopped: for filename in self.static.findFiles(self.path): try: currtime = os.stat(filename).st_mtime except OSError: continue oldtime = times.get(filename) if oldtime and currtime > oldtime: if self.debug: print('[*] detected changes on %s' % filename) self.static.run(*self.tasks) times[filename] = currtime break times[filename] = currtime self._sleep(self.interval)
import os from threading import Thread from werkzeug._reloader import ReloaderLoop class Watcher(Thread, ReloaderLoop): def __init__(self, paths, static, tasks, interval=1, *args, **kwargs): self.paths = paths self.static = static self.tasks = tasks self.debug = kwargs.get('debug') super(Watcher, self).__init__(*args, **kwargs) ReloaderLoop.__init__(self, interval=interval) def run(self): times = {} while not self._Thread__stopped: for filename in self.static.findFiles(self.path): try: currtime = os.stat(filename).st_mtime except OSError: continue oldtime = times.get(filename) if oldtime and currtime > oldtime: if self.debug: print('[*] detected changes on %s' % filename) self.static.run(*self.tasks) times[filename] = currtime break times[filename] = currtime self._sleep(self.interval)
Update user model interface name
<?php namespace ZfcUserDoctrineORM; use Zend\Module\Manager, Zend\Module\Consumer\AutoloaderProvider, ZfcUserDoctrineORM\Event\ResolveTargetEntityListener, ZfcUser\Module as ZfcUser, Doctrine\ORM\Events, Zend\EventManager\StaticEventManager; class Module implements AutoloaderProvider { public function init(Manager $moduleManager) { $events = StaticEventManager::getInstance(); $events->attach('bootstrap', 'bootstrap', array($this, 'attachDoctrineEvents'), 100); } public function getAutoloaderConfig() { return array( 'Zend\Loader\ClassMapAutoloader' => array( __DIR__ . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function attachDoctrineEvents($e) { $app = $e->getParam('application'); $locator = $app->getLocator(); $em = $locator->get('zfcuser_doctrine_em'); $evm = $em->getEventManager(); $listener = new ResolveTargetEntityListener; $listener->addResolveTargetEntity( 'ZfcUser\Model\UserInterface', ZfcUser::getOption('user_model_class'), array() ); $evm->addEventListener(Events::loadClassMetadata, $listener); } }
<?php namespace ZfcUserDoctrineORM; use Zend\Module\Manager, Zend\Module\Consumer\AutoloaderProvider, ZfcUserDoctrineORM\Event\ResolveTargetEntityListener, ZfcUser\Module as ZfcUser, Doctrine\ORM\Events, Zend\EventManager\StaticEventManager; class Module implements AutoloaderProvider { public function init(Manager $moduleManager) { $events = StaticEventManager::getInstance(); $events->attach('bootstrap', 'bootstrap', array($this, 'attachDoctrineEvents'), 100); } public function getAutoloaderConfig() { return array( 'Zend\Loader\ClassMapAutoloader' => array( __DIR__ . '/autoload_classmap.php', ), 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function attachDoctrineEvents($e) { $app = $e->getParam('application'); $locator = $app->getLocator(); $em = $locator->get('zfcuser_doctrine_em'); $evm = $em->getEventManager(); $listener = new ResolveTargetEntityListener; $listener->addResolveTargetEntity( 'ZfcUser\Model\User', ZfcUser::getOption('user_model_class'), array() ); $evm->addEventListener(Events::loadClassMetadata, $listener); } }
Use UTC time (we want to standardise on this)
from flask import jsonify from sqlalchemy.types import String from sqlalchemy import func import datetime from .. import main from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent @main.route('/frameworks', methods=['GET']) def list_frameworks(): frameworks = Framework.query.all() return jsonify( frameworks=[f.serialize() for f in frameworks] ) @main.route('/frameworks/g-cloud-7/stats', methods=['GET']) def get_framework_stats(): seven_days_ago = datetime.datetime.utcnow() + datetime.timedelta(-7) lot_column = DraftService.data['lot'].cast(String).label('lot') return str({ 'services_drafts': DraftService.query.filter( DraftService.status == "not-submitted" ).count(), 'services_complete': DraftService.query.filter( DraftService.status == "submitted" ).count(), 'services_by_lot': dict(db.session.query( lot_column, func.count(lot_column) ).group_by(lot_column).all()), 'users': User.query.count(), 'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(), 'suppliers': Supplier.query.count(), 'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(), 'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count() })
from flask import jsonify from sqlalchemy.types import String from sqlalchemy import func import datetime from .. import main from ...models import db, Framework, DraftService, Service, User, Supplier, SelectionAnswers, AuditEvent @main.route('/frameworks', methods=['GET']) def list_frameworks(): frameworks = Framework.query.all() return jsonify( frameworks=[f.serialize() for f in frameworks] ) @main.route('/frameworks/g-cloud-7/stats', methods=['GET']) def get_framework_stats(): seven_days_ago = datetime.datetime.now() + datetime.timedelta(-7) lot_column = DraftService.data['lot'].cast(String).label('lot') return str({ 'services_drafts': DraftService.query.filter( DraftService.status == "not-submitted" ).count(), 'services_complete': DraftService.query.filter( DraftService.status == "submitted" ).count(), 'services_by_lot': dict(db.session.query( lot_column, func.count(lot_column) ).group_by(lot_column).all()), 'users': User.query.count(), 'active_users': User.query.filter(User.logged_in_at > seven_days_ago).count(), 'suppliers': Supplier.query.count(), 'suppliers_interested': AuditEvent.query.filter(AuditEvent.type == 'register_framework_interest').count(), 'suppliers_with_complete_declaration': SelectionAnswers.find_by_framework('g-cloud-7').count() })
Make unittests easier to deal with. - Test everything ./test_spec.py - Test suite ./test_spec.py inverted - Test unit ./test_spec.py inverted.test_7
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): json_path = '%s.json' % json_path class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for i, test in enumerate(yaml['tests']): vars()['test_%s' % i] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': spec = spec.split('.')[0] globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
#!/usr/bin/python import unittest import os import json from entei import render SPECS_PATH = os.path.join('spec', 'specs') SPECS = [path for path in os.listdir(SPECS_PATH) if path.endswith('.json')] STACHE = render def _test_case_from_path(json_path): class MustacheTestCase(unittest.TestCase): """A simple yaml based test case""" def _test_from_object(obj): """Generate a unit test from a test object""" def test_case(self): result = STACHE(obj['template'], obj['data'], partials_dict=obj.get('partials', {})) self.assertEqual(result, obj['expected']) test_case.__doc__ = 'suite: {} desc: {}'.format(spec, obj['desc']) return test_case with open(json_path, 'r') as f: yaml = json.load(f) # Generates a unit test for each test object for test in yaml['tests']: vars()['test_'+test['name']] = _test_from_object(test) # Return the built class return MustacheTestCase # Create TestCase for each json file for spec in SPECS: # Ignore optional tests if spec[0] is not '~': globals()[spec] = _test_case_from_path(os.path.join(SPECS_PATH, spec)) # Run unit tests from command line if __name__ == "__main__": unittest.main()
Fix template in edit test suite
define([ 'jquery', 'underscore', 'backbone', 'models/testsuite/TestSuiteModel', 'text!templates/testsuites/testSuiteTemplate.html' ], function($, _, Backbone, TestSuiteModel, testSuiteTemplate) { var TestSuiteView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render', 'save'); }, render: function(options) { this.model = options.model; $('.menu a').removeClass('active'); $('.menu a[href="#/projects"]').addClass('active'); var data = { testsuite: this.model, projectId: options.project_id, _: _ } var compiledTemplate = _.template(testSuiteTemplate, data); this.$el.html(compiledTemplate); }, save: function(e) { e.preventDefault(); var arr = this.$('form').serializeArray(); var data = _(arr).reduce(function(acc, field) { acc[field.name] = field.value; return acc; }, {}); Backbone.history.navigate('#projects', true); // this.model.save(); return false; } }); return TestSuiteView; });
define([ 'jquery', 'underscore', 'backbone', 'models/testsuite/TestSuiteModel', 'text!templates/testsuites/testSuiteTemplate.html' ], function($, _, Backbone, TestSuiteModel, testSuiteTemplate) { var TestSuiteView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render', 'save'); }, render: function(options) { this.model = options.model; $('.menu a').removeClass('active'); $('.menu a[href="#/projects"]').addClass('active'); var data = { testsuite: this.model, projectId: options.project_id, _: _ } var compiledTemplate = _.template(testSuiteTemplate, data); $("#content-area").html(compiledTemplate); }, save: function(e) { e.preventDefault(); var arr = this.$('form').serializeArray(); var data = _(arr).reduce(function(acc, field) { acc[field.name] = field.value; return acc; }, {}); Backbone.history.navigate('#projects', true); // this.model.save(); return false; } }); return TestSuiteView; });
Make vote count visible after upvoting
$(document).ready(function() { MageHero_App.bindUpvote(); $('table.listing').tablesorter({ headers: { 1: { sorter: false }, 2: { sorter: false }, 4: { sorter: false }, 8: { sorter: false } }, textExtraction: function(cell) { var votes = $(cell).find('.vote-count'); if (votes.length) { return votes.text(); } return $(cell).text(); } }); }); document.addEventListener('DOMContentLoaded', function() { // Nothing yet }); MageHero_App = { bindUpvote: function() { var self = this; $('.upvote a').click(function() { var userId = $(this).closest('tr').attr('data-user-id'); var upvoteCount = $(this).closest('.upvote').find('.vote-count') $.ajax({ url: '/user/' + userId + '/upvote', method: 'GET', success: function(data) { console.log(data); if (! data.success) { alert(data.message); return; } upvoteCount.text(data.vote_count).show(); } }); }); return this; } };
$(document).ready(function() { MageHero_App.bindUpvote(); $('table.listing').tablesorter({ headers: { 1: { sorter: false }, 2: { sorter: false }, 4: { sorter: false }, 8: { sorter: false } }, textExtraction: function(cell) { var votes = $(cell).find('.vote-count'); if (votes.length) { return votes.text(); } return $(cell).text(); } }); }); document.addEventListener('DOMContentLoaded', function() { // Nothing yet }); MageHero_App = { bindUpvote: function() { var self = this; $('.upvote a').click(function() { var userId = $(this).closest('tr').attr('data-user-id'); var upvoteCount = $(this).closest('.upvote').find('.vote-count') $.ajax({ url: '/user/' + userId + '/upvote', method: 'GET', success: function(data) { console.log(data); if (! data.success) { alert(data.message); return; } upvoteCount.text(data.vote_count); } }); }); return this; } };
Clean up tweets hset too
<?php namespace PHPSW\Spec\Suite; describe("Task", function () { describe("meetup:import:all", function () { it("expects that the task runs", function () { $stdout = task('meetup:import:all'); expect($stdout)->toMatch(trimlns('#Group: \. Events: \.+ Photos: \.+ Posts: \.+ Reviews: \.+ Members: \.+ Speakers: \.+ Talks: \.+ #')); }); }); describe("redis:restore-fixtures", function () { it("expects that the task runs", function () { $stdout = task('redis:restore-fixtures'); expect($stdout)->toMatch(trimlns('#events: \.+ group: \. members: \.+ photos: \.+ posts: \.+ reviews: \.+ slides: \.+ speakers: \.+ talks: \.+ #')); }); }); describe("twitter:import:all", function () { it("expects that the task runs", function () { $stdout = task('twitter:import:all'); expect($stdout)->toMatch('#Tweets: \.+\n#'); }); }); afterEach(function () { global $redis; $redis->del('events'); $redis->del('group'); $redis->del('members'); $redis->del('photos'); $redis->del('posts'); $redis->del('reviews'); $redis->del('slides'); $redis->del('speakers'); $redis->del('talks'); $redis->del('tweets'); }); });
<?php namespace PHPSW\Spec\Suite; describe("Task", function () { describe("meetup:import:all", function () { it("expects that the task runs", function () { $stdout = task('meetup:import:all'); expect($stdout)->toMatch(trimlns('#Group: \. Events: \.+ Photos: \.+ Posts: \.+ Reviews: \.+ Members: \.+ Speakers: \.+ Talks: \.+ #')); }); }); describe("redis:restore-fixtures", function () { it("expects that the task runs", function () { $stdout = task('redis:restore-fixtures'); expect($stdout)->toMatch(trimlns('#events: \.+ group: \. members: \.+ photos: \.+ posts: \.+ reviews: \.+ slides: \.+ speakers: \.+ talks: \.+ #')); }); }); describe("twitter:import:all", function () { it("expects that the task runs", function () { $stdout = task('twitter:import:all'); expect($stdout)->toMatch('#Tweets: \.+\n#'); }); }); afterEach(function () { global $redis; $redis->del('events'); $redis->del('group'); $redis->del('members'); $redis->del('photos'); $redis->del('posts'); $redis->del('reviews'); $redis->del('slides'); $redis->del('speakers'); $redis->del('talks'); }); });
Add 'comment' field to list of non-numeric fields.
<?php class JsonView extends ApiView { public function render($content) { header('Content-Type: application/json; charset=utf8'); echo $this->buildOutput($content); return true; } /** * Function to build output, can be used by JSON and JSONP */ public function buildOutput ($content) { $content = $this->addCount($content); // need to work out which fields should have been numbers // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs) // Specify a list of fields to NOT convert to numbers $this->string_fields = array("stub", "track_name", "comment"); $output = $this->numeric_check($content); $retval = json_encode($output); return $retval; } protected function numeric_check($data) { if (!is_array($data)) { return $this->scalarNumericCheck('', $data); } $output = array(); foreach($data as $key => $value) { // recurse as needed if(is_array($value)) { $output[$key] = $this->numeric_check($value); } else { $output[$key] = $this->scalarNumericCheck($key, $value); } } return $output; } protected function scalarNumericCheck($key, $value) { if (is_numeric($value) && !in_array($key, $this->string_fields)) { return (float)$value; } return $value; } }
<?php class JsonView extends ApiView { public function render($content) { header('Content-Type: application/json; charset=utf8'); echo $this->buildOutput($content); return true; } /** * Function to build output, can be used by JSON and JSONP */ public function buildOutput ($content) { $content = $this->addCount($content); // need to work out which fields should have been numbers // Don't use JSON_NUMERIC_CHECK because it eats things (e.g. talk stubs) // Specify a list of fields to NOT convert to numbers $this->string_fields = array("stub", "track_name"); $output = $this->numeric_check($content); $retval = json_encode($output); return $retval; } protected function numeric_check($data) { if (!is_array($data)) { return $this->scalarNumericCheck('', $data); } $output = array(); foreach($data as $key => $value) { // recurse as needed if(is_array($value)) { $output[$key] = $this->numeric_check($value); } else { $output[$key] = $this->scalarNumericCheck($key, $value); } } return $output; } protected function scalarNumericCheck($key, $value) { if (is_numeric($value) && !in_array($key, $this->string_fields)) { return (float)$value; } return $value; } }
Remove a couple useless imports
import logging import socket import traceback from threading import Thread from splunklib import client _client = None class SplunkFilter(logging.Filter): """ A logging filter for Splunk's debug logs on the root logger to avoid recursion """ def filter(self, record): return not (record.module == 'binding' and record.levelno == logging.DEBUG) class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _init_client(self): return client.connect( host=self.host, port=self.port, username=self.username, password=self.password) def _async_emit(self, record): global _client if not _client: _client = self._init_client() try: _client.indexes[self.index].submit( self.format(record), host=socket.gethostname(), source=record.pathname, sourcetype='json') except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
import datetime import json import logging import socket import traceback from threading import Thread from splunklib import client _client = None class SplunkFilter(logging.Filter): """ A logging filter for Splunk's debug logs on the root logger to avoid recursion """ def filter(self, record): return not (record.module == 'binding' and record.levelno == logging.DEBUG) class SplunkHandler(logging.Handler): """ A logging handler to send events to a Splunk Enterprise instance """ def __init__(self, host, port, username, password, index): logging.Handler.__init__(self) self.host = host self.port = port self.username = username self.password = password self.index = index def emit(self, record): thread = Thread(target=self._async_emit, args=(record, )) thread.start() def _init_client(self): return client.connect( host=self.host, port=self.port, username=self.username, password=self.password) def _async_emit(self, record): global _client if not _client: _client = self._init_client() try: _client.indexes[self.index].submit( self.format(record), host=socket.gethostname(), source=record.pathname, sourcetype='json') except Exception, e: print "Traceback:\n" + traceback.format_exc() print "Exception in Splunk logging handler: %s" % str(e)
Change ring buffer default length to 3 3 is the Micrometer default, 1024 is way to big and results in excessive memory usage.
package io.quarkus.micrometer.runtime.config; import java.time.Duration; import java.util.Optional; import io.quarkus.runtime.annotations.ConfigGroup; import io.quarkus.runtime.annotations.ConfigItem; @ConfigGroup public class JsonConfigGroup implements MicrometerConfig.CapabilityEnabled { /** * Support for export to JSON format. Off by default. */ @ConfigItem(defaultValue = "false") public Optional<Boolean> enabled; /** * The path for the JSON metrics endpoint. * The default value is {@code metrics}. */ @ConfigItem(defaultValue = "metrics") public String path; /** * Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent * samples. Samples are accumulated to such statistics in ring buffers which rotate after * the expiry, with this buffer length. */ @ConfigItem(defaultValue = "3") public Integer bufferLength; /** * Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent * samples. Samples are accumulated to such statistics in ring buffers which rotate after * this expiry, with a particular buffer length. */ @ConfigItem(defaultValue = "P3D") public Duration expiry; @Override public Optional<Boolean> getEnabled() { return enabled; } @Override public String toString() { return this.getClass().getSimpleName() + "{path='" + path + ",enabled=" + enabled + '}'; } }
package io.quarkus.micrometer.runtime.config; import java.time.Duration; import java.util.Optional; import io.quarkus.runtime.annotations.ConfigGroup; import io.quarkus.runtime.annotations.ConfigItem; @ConfigGroup public class JsonConfigGroup implements MicrometerConfig.CapabilityEnabled { /** * Support for export to JSON format. Off by default. */ @ConfigItem(defaultValue = "false") public Optional<Boolean> enabled; /** * The path for the JSON metrics endpoint. * The default value is {@code metrics}. */ @ConfigItem(defaultValue = "metrics") public String path; /** * Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent * samples. Samples are accumulated to such statistics in ring buffers which rotate after * the expiry, with this buffer length. */ @ConfigItem(defaultValue = "1024") public Integer bufferLength; /** * Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent * samples. Samples are accumulated to such statistics in ring buffers which rotate after * this expiry, with a particular buffer length. */ @ConfigItem(defaultValue = "P3D") public Duration expiry; @Override public Optional<Boolean> getEnabled() { return enabled; } @Override public String toString() { return this.getClass().getSimpleName() + "{path='" + path + ",enabled=" + enabled + '}'; } }
Add the ability to retrieve the sha of the content.
package org.kohsuke.github; /** * A Content of a repository. * * @author Alexandre COLLIGNON */ public final class GHContent { private GHRepository owner; private String type; private String encoding; private long size; private String sha; private String name; private String path; private String content; private String url; // this is the API url private String git_url; // this is the Blob url private String html_url; // this is the UI public GHRepository getOwner() { return owner; } public String getType() { return type; } public String getEncoding() { return encoding; } public long getSize() { return size; } public String getSha() { return sha; } public String getName() { return name; } public String getPath() { return path; } public String getContent() { return new String(javax.xml.bind.DatatypeConverter.parseBase64Binary(getEncodedContent())); } public String getEncodedContent() { return content; } public String getUrl() { return url; } public String getGitUrl() { return git_url; } public String getHtmlUrl() { return html_url; } public boolean isFile() { return "file".equals(type); } public boolean isDirectory() { return "dir".equals(type); } }
package org.kohsuke.github; /** * A Content of a repository. * * @author Alexandre COLLIGNON */ public final class GHContent { private GHRepository owner; private String type; private String encoding; private long size; private String name; private String path; private String content; private String url; // this is the API url private String git_url; // this is the Blob url private String html_url; // this is the UI public GHRepository getOwner() { return owner; } public String getType() { return type; } public String getEncoding() { return encoding; } public long getSize() { return size; } public String getName() { return name; } public String getPath() { return path; } public String getContent() { return new String(javax.xml.bind.DatatypeConverter.parseBase64Binary(getEncodedContent())); } public String getEncodedContent() { return content; } public String getUrl() { return url; } public String getGitUrl() { return git_url; } public String getHtmlUrl() { return html_url; } public boolean isFile() { return "file".equals(type); } public boolean isDirectory() { return "dir".equals(type); } }
Move OpenID stuff under /accounts/openid/
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^accounts/openid/', include('django_authopenid.urls')), ) urlpatterns += patterns('', (r'^accounts/', include('registration.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls.defaults import * from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views.generic.simple import direct_to_template import settings admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^idp/', include('authentic.idp.urls')), (r'^accounts/', include('registration.urls')), (r'^$', login_required(direct_to_template), { 'template': 'index.html' }, 'index'), ) if settings.AUTH_OPENID: urlpatterns += patterns('', (r'^openid/', include('django_authopenid.urls')), ) if settings.AUTH_SSL: urlpatterns += patterns('', url(r'^sslauth/$', 'authentic.sslauth.login_ssl.process_request', name='user_signin_ssl'), url(r'^error_ssl/$', direct_to_template, {'template': 'error_ssl.html'}, 'error_ssl'), ) if settings.STATIC_SERVE: urlpatterns += patterns('', url( regex = r'^media/(?P<path>.*)$', view = 'django.views.static.serve', kwargs = {'document_root': settings.MEDIA_ROOT}), )
Change webpack dev server port
var webpack = require('webpack') var path = require('path') var autoprefixer = require('autoprefixer') module.exports = { entry: './index.js', output: { path: './', filename: 'bundle.js', publicPath: '' }, module: { preLoaders: [ { test: /\.html$/, loader: 'riotjs' } ], loaders: [ { test: /\.(jpe?g|png|gif|svg|mp4)$/i, loader:'file-loader' }, { test: /\.less$/, loader: 'style!css!postcss!less' }, { test: /\.js$|\.html$/, loader: 'babel', query: { presets: 'es2015-riot' } } ] }, plugins: [ new webpack.ProvidePlugin({ riot: 'riot' }), //new webpack.optimize.UglifyJsPlugin({warnings: false}), ], postcss: function () { return [autoprefixer({browsers: 'last 2 versions'})]; }, devServer: { port: 8080, outputPath: __dirname, inline: false, progress: true, }, }
var webpack = require('webpack') var path = require('path') var autoprefixer = require('autoprefixer') module.exports = { entry: './index.js', output: { path: './', filename: 'bundle.js', publicPath: '' }, module: { preLoaders: [ { test: /\.html$/, loader: 'riotjs' } ], loaders: [ { test: /\.(jpe?g|png|gif|svg|mp4)$/i, loader:'file-loader' }, { test: /\.less$/, loader: 'style!css!postcss!less' }, { test: /\.js$|\.html$/, loader: 'babel', query: { presets: 'es2015-riot' } } ] }, plugins: [ new webpack.ProvidePlugin({ riot: 'riot' }), new webpack.optimize.UglifyJsPlugin({warnings: false}) ], postcss: function () { return [autoprefixer({browsers: 'last 2 versions'})]; }, devServer: { port: 7070, outputPath: __dirname, inline: false, progress: true, }, }
Use updated containers in main
'use strict' import 'normalize.css' import React, { Component } from 'react' import ReactCSS from 'reactcss' import '../fonts/work-sans/WorkSans.css!' import '../styles/felony.css!' import colors from '../styles/variables/colors' import Header from './header/Header' import FloatingButtonContainer from '../containers/FloatingButtonContainer' import ComposerContainer from '../containers/ComposerContainer' import BuddiesContainer from '../containers/BuddiesContainer' export class Felony extends Component { state = { selected: [], // replaced with redux } classes() { return { 'default': { app: { // NOTE: Set here and not in felony.css in order to use color variable background: colors.bgLight, position: 'absolute', width: '100%', height: '100%', color: 'white', }, header: { position: 'fixed', top: 0, left: 0, right: 0, }, }, } } // this will be replaced with Redux handleAddToSelected = (selected) => { this.setState({ selected: this.state.selected.concat([selected]), }) } render() { return ( <div is="app"> <div is="header" onClick={ this.handleAddToSelected }> <Header /> </div> <BuddiesContainer /> <FloatingButtonContainer /> <ComposerContainer /> </div> ) } } export default ReactCSS(Felony)
'use strict' import 'normalize.css' import React, { Component } from 'react' import ReactCSS from 'reactcss' import '../fonts/work-sans/WorkSans.css!' import '../styles/felony.css!' import colors from '../styles/variables/colors' import Header from './header/Header' import FloatingButtonContainer from '../containers/FloatingButtonContainer' import ComposeContainer from '../containers/ComposeContainer' import Encrypt from './encrypt/Encrypt' export class Felony extends Component { state = { selected: [], // replaced with redux } classes() { return { 'default': { app: { // NOTE: Set here and not in felony.css in order to use color variable background: colors.bgLight, position: 'absolute', width: '100%', height: '100%', color: 'white', }, header: { position: 'fixed', top: 0, left: 0, right: 0, }, }, } } // this will be replaced with Redux handleAddToSelected = (selected) => { this.setState({ selected: this.state.selected.concat([selected]), }) } render() { return ( <div is="app"> <div is="header" onClick={ this.handleAddToSelected }> <Header /> </div> <Encrypt /> <FloatingButtonContainer /> <ComposeContainer /> </div> ) } } export default ReactCSS(Felony)
Add preprints to the sidebar [#OSF-7198]
from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^preprints/', include('admin.preprints.urls', namespace='preprints')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
from django.conf.urls import include, url from django.contrib import admin from settings import ADMIN_BASE from . import views base_pattern = '^{}'.format(ADMIN_BASE) urlpatterns = [ ### ADMIN ### url( base_pattern, include([ url(r'^$', views.home, name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^spam/', include('admin.spam.urls', namespace='spam')), url(r'^account/', include('admin.common_auth.urls', namespace='auth')), url(r'^password/', include('password_reset.urls')), url(r'^nodes/', include('admin.nodes.urls', namespace='nodes')), url(r'^users/', include('admin.users.urls', namespace='users')), url(r'^meetings/', include('admin.meetings.urls', namespace='meetings')), url(r'^project/', include('admin.pre_reg.urls', namespace='pre_reg')), url(r'^metrics/', include('admin.metrics.urls', namespace='metrics')), url(r'^desk/', include('admin.desk.urls', namespace='desk')), ]), ), ] admin.site.site_header = 'OSF-Admin administration'
Clear all notifications when sign out.
'use strict'; angular.module('copay.header').controller('HeaderController', function($scope, $rootScope, $location, walletFactory, controllerUtils) { $scope.menu = [{ 'title': 'Copayers', 'icon': 'fi-torsos-all', 'link': '#/peer' }, { 'title': 'Addresses', 'icon': 'fi-address-book', 'link': '#/addresses' }, { 'title': 'Transactions', 'icon': 'fi-loop', 'link': '#/transactions' }, { 'title': 'Send', 'icon': 'fi-arrow-right', 'link': '#/send' }, { 'title': 'Backup', 'icon': 'fi-archive', 'link': '#/backup' }]; $rootScope.$watch('wallet', function(wallet) { if (wallet) { controllerUtils.setSocketHandlers(); } }); $scope.isActive = function(item) { if (item.link && item.link.replace('#','') == $location.path()) { return true; } return false; }; $scope.signout = function() { var w = $rootScope.wallet; if (w) { w.disconnect(); controllerUtils.logout(); } $rootScope.flashMessage = {}; }; $scope.clearFlashMessage = function() { $rootScope.flashMessage = {}; }; $rootScope.isCollapsed = true; });
'use strict'; angular.module('copay.header').controller('HeaderController', function($scope, $rootScope, $location, walletFactory, controllerUtils) { $scope.menu = [{ 'title': 'Copayers', 'icon': 'fi-torsos-all', 'link': '#/peer' }, { 'title': 'Addresses', 'icon': 'fi-address-book', 'link': '#/addresses' }, { 'title': 'Transactions', 'icon': 'fi-loop', 'link': '#/transactions' }, { 'title': 'Send', 'icon': 'fi-arrow-right', 'link': '#/send' }, { 'title': 'Backup', 'icon': 'fi-archive', 'link': '#/backup' }]; $rootScope.$watch('wallet', function(wallet) { if (wallet) { controllerUtils.setSocketHandlers(); } }); $scope.isActive = function(item) { if (item.link && item.link.replace('#','') == $location.path()) { return true; } return false; }; $scope.signout = function() { var w = $rootScope.wallet; if (w) { w.disconnect(); controllerUtils.logout(); } }; $scope.clearFlashMessage = function() { $rootScope.flashMessage = {}; }; $rootScope.isCollapsed = true; });
Create index mappings independently of index, just update settings?
from django.core.management.base import NoArgsCommand from elasticutils import get_es from pyelasticsearch.exceptions import IndexAlreadyExistsError, ElasticHttpError from bulbs.indexable.conf import settings from bulbs.indexable.models import polymorphic_indexable_registry class Command(NoArgsCommand): help = 'Creates indexes and mappings for for Indexable objects.' def handle(self, *args, **options): indexes = {} for name, model in polymorphic_indexable_registry.all_models.items(): index = model.get_index_name() if index not in indexes: indexes[index] = {} indexes[index].update(model.get_mapping()) es = get_es(urls=settings.ES_URLS) for index, mappings in indexes.items(): try: es.create_index(index, settings={ "settings": settings.ES_SETTINGS }) except IndexAlreadyExistsError: es.update_settings(index, settings.ES_SETTINGS) except ElasticHttpError as e: self.stderr.write("ES Error: %s" % e.error) for doctype, mapping in mappings.items(): try: es.put_mapping(index, doctype, dict(doctype=mapping)) except ElasticHttpError as e: self.stderr.write("ES Error: %s" % e.error)
from django.core.management.base import NoArgsCommand from elasticutils import get_es from pyelasticsearch.exceptions import IndexAlreadyExistsError, ElasticHttpError from bulbs.indexable.conf import settings from bulbs.indexable.models import polymorphic_indexable_registry class Command(NoArgsCommand): help = 'Creates indexes and mappings for for Indexable objects.' def handle(self, *args, **options): indexes = {} for name, model in polymorphic_indexable_registry.all_models.items(): index = model.get_index_name() if index not in indexes: indexes[index] = {} indexes[index].update(model.get_mapping()) es = get_es(urls=settings.ES_URLS) for index, mappings in indexes.items(): try: es.create_index(index, settings={ "mappings": mappings, "settings": settings.ES_SETTINGS }) except IndexAlreadyExistsError: pass except ElasticHttpError as e: self.stderr.write("ES Error: %s" % e.error) for doctype, mapping in mappings.items(): try: es.put_mapping(index, doctype, dict(doctype=mapping)) except ElasticHttpError as e: self.stderr.write("ES Error: %s" % e.error)
Remove code which blanks patch files
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Look for a patch file from our collection (which is # in the pyscraper/patches folder in Public Whip CVS) patchfile = os.path.join("patches", fileshort + ".patch") if not os.path.isfile(patchfile): return False while True: # Apply the patch shutil.copyfile(filein, fileout) # delete temporary file that might have been created by a previous patch failure filoutorg = fileout + ".orig" if os.path.isfile(filoutorg): os.remove(filoutorg) status = os.system("patch --quiet %s <%s" % (fileout, patchfile)) if status == 0: return True raise Exception, "Error running 'patch' on file %s" % fileshort #print "blanking out %s" % fileshort #os.rename(patchfile, patchfile + ".old~") #blankfile = open(patchfile, "w") #blankfile.close()
#! /usr/bin/python2.3 # vim:sw=8:ts=8:et:nowrap import os import shutil def ApplyPatches(filein, fileout): # Generate short name such as wrans/answers2003-03-31.html (rest, name) = os.path.split(filein) (rest, dir) = os.path.split(rest) fileshort = os.path.join(dir, name) # Look for a patch file from our collection (which is # in the pyscraper/patches folder in Public Whip CVS) patchfile = os.path.join("patches", fileshort + ".patch") if not os.path.isfile(patchfile): return False while True: # Apply the patch shutil.copyfile(filein, fileout) # delete temporary file that might have been created by a previous patch failure filoutorg = fileout + ".orig" if os.path.isfile(filoutorg): os.remove(filoutorg) status = os.system("patch --quiet %s <%s" % (fileout, patchfile)) if status == 0: return True print "Error running 'patch' on file %s, blanking it out" % fileshort os.rename(patchfile, patchfile + ".old~") blankfile = open(patchfile, "w") blankfile.close()
Add failing test for dynamic imports
const matchSourceExpression = require('../lib/matchSourceExpression'); const expect = require('./unexpected-with-plugins'); const parse = require('../lib/parseJavascript'); describe('parseJavascript', () => { it('should parse jsx', () => { expect(parse('<main>Hello world</main>'), 'to satisfy', { type: 'Program', tokens: [ { type: { label: 'jsxTagStart' } }, { type: { label: 'jsxName' }, value: 'main' }, { type: { label: 'jsxTagEnd' } }, { type: { label: 'jsxText' }, value: 'Hello world' }, { type: { label: 'jsxTagStart' } }, { type: { label: '/' } }, { type: { label: 'jsxName' }, value: 'main' }, { type: { label: 'jsxTagEnd' } } ] }); }); it('should parse dynamic imports', () => { expect(parse('const foo = import("./foo.js")', { sourceType: 'module' }), 'to satisfy', { type: 'Program' }); }) });
const matchSourceExpression = require('../lib/matchSourceExpression'); const expect = require('./unexpected-with-plugins'); const parse = require('../lib/parseJavascript'); describe('parseJavascript', () => { it('should parse jsx', () => { expect(parse('<main>Hello world</main>'), 'to satisfy', { type: 'Program', tokens: [ { type: { label: 'jsxTagStart' } }, { type: { label: 'jsxName' }, value: 'main' }, { type: { label: 'jsxTagEnd' } }, { type: { label: 'jsxText' }, value: 'Hello world' }, { type: { label: 'jsxTagStart' } }, { type: { label: '/' } }, { type: { label: 'jsxName' }, value: 'main' }, { type: { label: 'jsxTagEnd' } } ] }); }); });
Change about link to home
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Header.module.css'; class Header extends Component { render() { return ( <div className={ styles.container }> <header className={ styles.header }> <Link to='/'> <h1> Evan Simpson </h1> </Link> <p> Designer, Developer, Lifelong Learner </p> </header> <nav className={ styles.nav }> <ul> <li> <Link to={'/'}> About </Link> </li> <li> <Link to={'/work/'}> Work </Link> </li> <li> <Link to={'/contact/'}> Contact </Link> </li> </ul> </nav> </div> ); } } export default Header;
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './Header.module.css'; class Header extends Component { render() { return ( <div className={ styles.container }> <header className={ styles.header }> <Link to='/'> <h1> Evan Simpson </h1> </Link> <p> Designer, Developer, Lifelong Learner </p> </header> <nav className={ styles.nav }> <ul> <li> <Link to={'/'}> About </Link> </li> <li> <Link to={'/about/'}> About </Link> </li> <li> <Link to={'/contact/'}> Contact </Link> </li> </ul> </nav> </div> ); } } export default Header;
Throw error returned from DAGNode.create in access controller
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { if (err) { throw err } resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
'use strict' const AccessController = require('./access-controller') const { DAGNode } = require('ipld-dag-pb') class IPFSAccessController extends AccessController { constructor (ipfs) { super() this._ipfs = ipfs } async load (address) { // Transform '/ipfs/QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' // to 'QmPFtHi3cmfZerxtH9ySLdzpg1yFhocYDZgEZywdUXHxFU' if (address.indexOf('/ipfs') === 0) address = address.split('/')[2] try { const dag = await this._ipfs.object.get(address) const obj = JSON.parse(dag.toJSON().data) this._access = obj } catch (e) { console.log("ACCESS ERROR:", e) } } async save (onlyHash) { let hash try { const access = JSON.stringify(this._access, null, 2) let dag if (onlyHash) { dag = await new Promise(resolve => { DAGNode.create(Buffer.from(access), (err, n) => { resolve(n) }) }) } else { dag = await this._ipfs.object.put(new Buffer(access)) } hash = dag.toJSON().multihash.toString() } catch (e) { console.log("ACCESS ERROR:", e) } return hash } } module.exports = IPFSAccessController
Fix 'undefined index `code`' error
<?php namespace Omnipay\Square\Message; use Omnipay\Common\Message\AbstractResponse; use Omnipay\Common\Message\RedirectResponseInterface; /** * Square Purchase Response */ class ChargeResponse extends AbstractResponse implements RedirectResponseInterface { public function isSuccessful() { if ($this->data['status'] == 'success') { return true; } else { return false; } } public function isRedirect() { return false; } public function getRedirectUrl() { return ""; } public function getRedirectMethod() { return ""; } public function getRedirectData() { return array(); } public function getTransactionId() { return $this->data['transactionId']; } public function getTenders() { return $this->data['tenders']; } public function getOrderId() { return $this->data['orderId']; } public function getCreatedAt() { return $this->data['created_at']; } public function getReferenceId() { return $this->data['referenceId']; } public function getMessage() { $message = ''; if (isset($this->data['code'])) { $message .= $this->data['code'] . ': '; } return $message . ($this->data['error'] ?? ''); } }
<?php namespace Omnipay\Square\Message; use Omnipay\Common\Message\AbstractResponse; use Omnipay\Common\Message\RedirectResponseInterface; /** * Square Purchase Response */ class ChargeResponse extends AbstractResponse implements RedirectResponseInterface { public function isSuccessful() { if ($this->data['status'] == 'success') { return true; } else { return false; } } public function isRedirect() { return false; } public function getRedirectUrl() { return ""; } public function getRedirectMethod() { return ""; } public function getRedirectData() { return array(); } public function getTransactionId() { return $this->data['transactionId']; } public function getTenders() { return $this->data['tenders']; } public function getOrderId() { return $this->data['orderId']; } public function getCreatedAt() { return $this->data['created_at']; } public function getReferenceId() { return $this->data['referenceId']; } public function getMessage() { $message = ''; if (strlen($this->data['code'])) { $message .= $this->data['code'] . ': '; } return $message . $this->data['error']; } }
Use arguments instead of the spread operator
"use strict"; const P = require('bluebird'); const redis = require('redis'); const HyperSwitch = require('hyperswitch'); const Redis = superclass => class extends superclass { constructor(options) { super(options); if (!options.redis) { throw new Error('Redis options not provided to the rate_limiter'); } if (!(options.redis.host && options.redis.port) && !options.redis.path) { throw new Error('Redis host:port or unix socket path must be specified'); } options.redis = Object.assign(options.redis, { no_ready_check: true // Prevents sending unsupported info command to nutcracker }); this._redis = P.promisifyAll(redis.createClient(options.redis)); this._redis.on('error', (e) => { // If we can't connect to redis - don't worry and don't fail, // just log it and ignore. options.log('error/redis', e); }); HyperSwitch.lifecycle.on('close', () => this._redis.quit()); } }; class MixinBuilder { constructor(superclass) { this.superclass = superclass; } with() { return Array.prototype.slice.call(arguments) .reduce((c, mixin) => mixin(c), this.superclass); } } module.exports = { mix: superclass => new MixinBuilder(superclass), Redis };
"use strict"; const P = require('bluebird'); const redis = require('redis'); const HyperSwitch = require('hyperswitch'); const Redis = superclass => class extends superclass { constructor(options) { super(options); if (!options.redis) { throw new Error('Redis options not provided to the rate_limiter'); } if (!(options.redis.host && options.redis.port) && !options.redis.path) { throw new Error('Redis host:port or unix socket path must be specified'); } options.redis = Object.assign(options.redis, { no_ready_check: true // Prevents sending unsupported info command to nutcracker }); this._redis = P.promisifyAll(redis.createClient(options.redis)); this._redis.on('error', (e) => { // If we can't connect to redis - don't worry and don't fail, // just log it and ignore. options.log('error/redis', e); }); HyperSwitch.lifecycle.on('close', () => this._redis.quit()); } }; class MixinBuilder { constructor(superclass) { this.superclass = superclass; } with(...mixins) { return mixins.reduce((c, mixin) => mixin(c), this.superclass); } } module.exports = { mix: superclass => new MixinBuilder(superclass), Redis };
Set resource to public in LogicboxesComodo.
<?php namespace LaravelLb; use LaravelLb\LogicBoxes; class LogicBoxesActions extends LogicBoxes { public $resource; public function __construct() { parent::__construct(); $this->resource = "actions"; } /** * Gets the Current Actions based on the criteria specified. * http://manage.logicboxes.com/kb/answer/908 * @return LogicboxesCommon */ public function searchCurrentActions($variables = [], $pageNo = 1, $noOfRecords = 500) { $method = 'search-current'; $variables = array_merge($variables, [ 'page-no' => $pageNo, 'no-of-records' => $noOfRecords, ]); $response = $this->get($this->resource, $method, $variables); return $this; } /** * Searches the Archived Actions based on the criteria specified. * http://manage.logicboxes.com/kb/answer/909 * @return LogicboxesCommon */ public function searchArchivedActions($variables = [], $pageNo = 1, $noOfRecords = 500) { $method = 'search-archived'; $variables = array_merge($variables, [ 'page-no' => $pageNo, 'no-of-records' => $noOfRecords, ]); $response = $this->get($this->resource, $method, $variables); return $this; } }
<?php namespace LaravelLb; use LaravelLb\LogicBoxes; class LogicBoxesActions extends LogicBoxes { public function __construct() { parent::__construct(); $this->resource = "actions"; } /** * Gets the Current Actions based on the criteria specified. * http://manage.logicboxes.com/kb/answer/908 * @return LogicboxesCommon */ public function searchCurrentActions($variables = [], $pageNo = 1, $noOfRecords = 500) { $method = 'search-current'; $variables = array_merge($variables, [ 'page-no' => $pageNo, 'no-of-records' => $noOfRecords, ]); $response = $this->get($this->resource, $method, $variables); return $this; } /** * Searches the Archived Actions based on the criteria specified. * http://manage.logicboxes.com/kb/answer/909 * @return LogicboxesCommon */ public function searchArchivedActions($variables = [], $pageNo = 1, $noOfRecords = 500) { $method = 'search-archived'; $variables = array_merge($variables, [ 'page-no' => $pageNo, 'no-of-records' => $noOfRecords, ]); $response = $this->get($this->resource, $method, $variables); return $this; } }
Fix for /whoami with a user who doesn't have a profile picture
<?php /* * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Entities; use Longman\TelegramBot\Exception\TelegramException; class UserProfilePhotos extends Entity { protected $total_count; protected $photos; public function __construct(array $data) { $this->total_count = isset($data['total_count']) ? $data['total_count'] : null; if ($this->total_count === null && !is_numeric($this->total_count) ) { throw new TelegramException('total_count is empty!'); } $this->photos = isset($data['photos']) ? $data['photos'] : null; if ($this->photos === null || !is_array($data['photos']) ) { throw new TelegramException('photos is empty!'); } $photos = []; foreach ($this->photos as $key => $photo) { if (is_array($photo)) { foreach ($photo as $photo_size) { $photos[$key][] = new PhotoSize($photo_size); } } else { throw new TelegramException('photo is not an array!'); } } $this->photos = $photos; } public function getTotalCount() { return $this->total_count; } public function getPhotos() { return $this->photos; } }
<?php /* * This file is part of the TelegramBot package. * * (c) Avtandil Kikabidze aka LONGMAN <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Longman\TelegramBot\Entities; use Longman\TelegramBot\Exception\TelegramException; class UserProfilePhotos extends Entity { protected $total_count; protected $photos; public function __construct(array $data) { $this->total_count = isset($data['total_count']) ? $data['total_count'] : null; if (empty($this->total_count)) { throw new TelegramException('total_count is empty!'); } $this->photos = isset($data['photos']) ? $data['photos'] : null; if (empty($this->photos)) { throw new TelegramException('photos is empty!'); } $photos = []; foreach ($this->photos as $key => $photo) { if (is_array($photo)) { foreach ($photo as $photo_size) { $photos[$key][] = new PhotoSize($photo_size); } } else { throw new TelegramException('photo is not an array!'); } } $this->photos = $photos; } public function getTotalCount() { return $this->total_count; } public function getPhotos() { return $this->photos; } }
Fix missing parentheses initialization error
#!/usr/bin/env python # -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2016 execuc * # * * # * This file is part of LCInterlocking module. * # * LCInterlocking module is free software; you can redistribute it and/or* # * modify it under the terms of the GNU Lesser General Public * # * License as published by the Free Software Foundation; either * # * version 2.1 of the License, or (at your option) any later version. * # * * # * This module is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * # * Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Lesser General Public * # * License along with this library; if not, write to the Free Software * # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * # * MA 02110-1301 USA * # * * # *************************************************************************** print("Interlocking laser cut workbench loaded")
#!/usr/bin/env python # -*- coding: utf-8 -*- # *************************************************************************** # * * # * Copyright (c) 2016 execuc * # * * # * This file is part of LCInterlocking module. * # * LCInterlocking module is free software; you can redistribute it and/or* # * modify it under the terms of the GNU Lesser General Public * # * License as published by the Free Software Foundation; either * # * version 2.1 of the License, or (at your option) any later version. * # * * # * This module is distributed in the hope that it will be useful, * # * but WITHOUT ANY WARRANTY; without even the implied warranty of * # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * # * Lesser General Public License for more details. * # * * # * You should have received a copy of the GNU Lesser General Public * # * License along with this library; if not, write to the Free Software * # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * # * MA 02110-1301 USA * # * * # *************************************************************************** print "Interlocking laser cut workbench loaded"
Add window.angular to make it pass the basic tests
(function (angular) { 'use strict'; angular.module('angular-reverse-url', ['ngRoute']) .filter('reverseUrl', ['$route', function ($route) { var regexp = /:([A-Za-z0-9]*)\\*?\\??/g; return _.memoize(function (name, params) { var targetRoute; angular.forEach($route.routes, function (route) { if (route.controller === name || route.name === name) { // we need to check we are passing the parameters in var success = true; var matches = regexp.exec(route.originalPath); // we can't allow empty params if this route is expecting params if ((matches !== null) && (matches.length > 0) && (angular.isUndefined(params) === true)) { success = false; } // TODO: check params exist for each match if (success === true) { targetRoute = route.originalPath; return; } } }); targetRoute = targetRoute.replace(regexp, function (match, pattern) { return params[pattern]; }); return '#' + targetRoute; }, function (name, params) { return name + JSON.stringify(params); }); }]); }(window.angular));
(function () { 'use strict'; angular.module('angular-reverse-url', ['ngRoute']) .filter('reverseUrl', ['$route', function ($route) { var regexp = /:([A-Za-z0-9]*)\\*?\\??/g; return _.memoize(function (name, params) { var targetRoute; angular.forEach($route.routes, function (route) { if (route.controller === name || route.name === name) { // we need to check we are passing the parameters in var success = true; var matches = regexp.exec(route.originalPath); // we can't allow empty params if this route is expecting params if ((matches !== null) && (matches.length > 0) && (angular.isUndefined(params) === true)) { success = false; } // TODO: check params exist for each match if (success === true) { targetRoute = route.originalPath; return; } } }); targetRoute = targetRoute.replace(regexp, function (match, pattern) { return params[pattern]; }); return '#' + targetRoute; }, function (name, params) { return name + JSON.stringify(params); }); }]); }());
Call go build with default grunt invocation
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // the package file to use qunit: { // internal task or name of a plugin (like "qunit") all: ['tests/*.html'] }, watch: { files: ['tests/*.js', 'tests/*.html', 'tmpl/*.html', 'js/*.js', 'src/*.go'], tasks: ['qunit', 'shell:buildGo', 'shell:testGo'] }, shell: { buildGo: { command: 'go build -o rtfblog src/*.go', options: { stdout: true, stderr: true } }, testGo: { command: 'go test ./...', options: { stdout: true, stderr: true } } } }); // load up your plugins grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-shell'); // register one or more task lists (you should ALWAYS have a "default" task list) grunt.registerTask('default', ['qunit', 'shell:buildGo', 'shell:testGo']); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // the package file to use qunit: { // internal task or name of a plugin (like "qunit") all: ['tests/*.html'] }, watch: { files: ['tests/*.js', 'tests/*.html', 'tmpl/*.html', 'js/*.js', 'src/*.go'], tasks: ['qunit', 'shell:buildGo', 'shell:testGo'] }, shell: { buildGo: { command: 'go build -o rtfblog src/*.go', options: { stdout: true, stderr: true } }, testGo: { command: 'go test ./...', options: { stdout: true, stderr: true } } } }); // load up your plugins grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-shell'); // register one or more task lists (you should ALWAYS have a "default" task list) grunt.registerTask('default', ['qunit', 'shell:testGo']); //grunt.registerTask('taskName', ['taskToRun', 'anotherTask']); };
Stop mail transport after sending
<?php class CM_Mail_Mailer extends Swift_Mailer implements CM_Service_ManagerAwareInterface { use CM_Service_ManagerAwareTrait; public function __construct(Swift_Transport $transport) { CM_Mail_Message::register(); parent::__construct($transport); } public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; $to = $message->getTo(); if (empty($to)) { throw new CM_Exception_Invalid('No recipient specified'); } $numSent = 0; $failedRecipients = null; $context = new CM_Log_Context(); try { $numSent = parent::send($message, $failedRecipients); } catch (Exception $e) { $context->setException($e); throw $e; } $this->getTransport()->stop(); $succeeded = 0 !== $numSent && null !== $failedRecipients && 0 === count($failedRecipients); if (!$succeeded) { $context->setExtra([ 'message' => [ 'subject' => $message->getSubject(), 'from' => $message->getFrom(), 'to' => $message->getTo(), 'cc' => $message->getCc(), 'bcc' => $message->getBcc(), ], 'failedRecipients' => $failedRecipients, ]); $this->getServiceManager()->getLogger()->error('Failed to send email', $context); } return $numSent; } public function createMessage($service = null) { $service = null === $service ? 'cm-message' : $service; return parent::createMessage($service); } }
<?php class CM_Mail_Mailer extends Swift_Mailer implements CM_Service_ManagerAwareInterface { use CM_Service_ManagerAwareTrait; public function __construct(Swift_Transport $transport) { CM_Mail_Message::register(); parent::__construct($transport); } public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $failedRecipients = (array) $failedRecipients; $to = $message->getTo(); if (empty($to)) { throw new CM_Exception_Invalid('No recipient specified'); } $numSent = parent::send($message, $failedRecipients); if (0 === $numSent || 0 !== count($failedRecipients)) { $context = new CM_Log_Context(); $context->setExtra([ 'message' => [ 'subject' => $message->getSubject(), 'from' => $message->getSender(), 'to' => $message->getTo(), 'cc' => $message->getCc(), 'bcc' => $message->getBcc(), ], 'failedRecipients' => $failedRecipients, ]); $this->getServiceManager()->getLogger()->error('Failed to send email to all recipients', $context); } return $numSent; } public function createMessage($service = null) { $service = null === $service ? 'cm-message' : $service; return parent::createMessage($service); } }
Update regex to cope with the request paths used in portlets
/* @VaadinApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.server; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import com.vaadin.Application; import com.vaadin.terminal.ApplicationResource; import com.vaadin.terminal.DownloadStream; import com.vaadin.terminal.RequestHandler; import com.vaadin.terminal.WrappedRequest; import com.vaadin.terminal.WrappedResponse; public class ApplicationResourceHandler implements RequestHandler { private static final Pattern APP_RESOURCE_PATTERN = Pattern .compile("^/?APP/(\\d+)/.*"); public boolean handleRequest(Application application, WrappedRequest request, WrappedResponse response) throws IOException { // Check for application resources String requestPath = request.getRequestPathInfo(); if (requestPath == null) { return false; } Matcher resourceMatcher = APP_RESOURCE_PATTERN.matcher(requestPath); if (resourceMatcher.matches()) { ApplicationResource resource = application .getResource(resourceMatcher.group(1)); if (resource != null) { DownloadStream stream = resource.getStream(); if (stream != null) { stream.setCacheTime(resource.getCacheTime()); stream.writeTo(response); return true; } } // We get here if the url looks like an application resource but no // resource can be served response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestPathInfo() + " can not be found"); return true; } return false; } }
/* @VaadinApache2LicenseForJavaFiles@ */ package com.vaadin.terminal.gwt.server; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import com.vaadin.Application; import com.vaadin.terminal.ApplicationResource; import com.vaadin.terminal.DownloadStream; import com.vaadin.terminal.RequestHandler; import com.vaadin.terminal.WrappedRequest; import com.vaadin.terminal.WrappedResponse; public class ApplicationResourceHandler implements RequestHandler { private static final Pattern APP_RESOURCE_PATTERN = Pattern .compile("/APP/(\\d+)/.*"); public boolean handleRequest(Application application, WrappedRequest request, WrappedResponse response) throws IOException { // Check for application resources String requestPath = request.getRequestPathInfo(); if (requestPath == null) { return false; } Matcher resourceMatcher = APP_RESOURCE_PATTERN.matcher(requestPath); if (resourceMatcher.matches()) { ApplicationResource resource = application .getResource(resourceMatcher.group(1)); if (resource != null) { DownloadStream stream = resource.getStream(); if (stream != null) { stream.setCacheTime(resource.getCacheTime()); stream.writeTo(response); return true; } } // We get here if the url looks like an application resource but no // resource can be served response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestPathInfo() + " can not be found"); return true; } return false; } }