text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Test string parsing with a more interesting value.
'use strict'; var vcap = require('../main/vcap-parser'), reappt = require('../main/reappt'); describe('VCAP service parser', function() { it('can find Reappt service', function() { var parser = new vcap.Parser([new reappt.Parser()]); var services = parser.parse({ 'push-reappt' : [{}] }); expect(services.reappt).toBe(null); }); it('can handle a string with the Reappt service', function() { var parser = new vcap.Parser([new reappt.Parser()]); var services = parser.parse('{"push-reappt":[{"credentials":{"host":"host","principal":"principal","credentials":"credentials"}}]}'); expect(services.reappt.host).toBe("host"); expect(services.reappt.principal).toBe("principal"); expect(services.reappt.credentials).toBe("credentials"); }); });
'use strict'; var vcap = require('../main/vcap-parser'), reappt = require('../main/reappt'); describe('VCAP service parser', function() { it('can find Reappt service', function() { var parser = new vcap.Parser([new reappt.Parser()]); var services = parser.parse({ 'push-reappt' : [{}] }); expect(services.reappt).toBe(null); }); it('can handle a string with the Reappt service', function() { var parser = new vcap.Parser([new reappt.Parser()]); var services = parser.parse('{"push-reappt" : [{}]}'); expect(services.reappt).toBe(null); }); });
Fix test loading config.yaml with wrong locations
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris package main import ( "os" "testing" "time" "github.com/vlifesystems/rulehunter/internal/testhelpers" ) func TestSubMain_interrupt(t *testing.T) { cfgDir := testhelpers.BuildConfigDirs(t, false) flags := &cmdFlags{install: false, serve: true, configDir: cfgDir} defer os.RemoveAll(cfgDir) mustWriteConfig(t, cfgDir, 100) l := testhelpers.NewLogger() hasQuitC := make(chan bool) go func() { wantExitCode := 0 exitCode, err := subMain(flags, l) if exitCode != wantExitCode { t.Errorf("subMain(%v) exitCode: %d, want: %d", flags, exitCode, wantExitCode) } if err != nil { t.Errorf("subMain(%v): %s", flags, err) } hasQuitC <- true }() interruptC := time.NewTimer(time.Second).C timeoutC := time.NewTimer(6 * time.Second).C for { select { case <-interruptC: interruptProcess(t) case <-timeoutC: t.Fatal("subMain() hasn't stopped") case <-hasQuitC: return } } }
// +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris package main import ( "os" "path/filepath" "testing" "time" "github.com/vlifesystems/rulehunter/internal/testhelpers" ) func TestSubMain_interrupt(t *testing.T) { configDir := testhelpers.BuildConfigDirs(t, false) flags := &cmdFlags{install: false, serve: true, configDir: configDir} defer os.RemoveAll(configDir) testhelpers.CopyFile(t, filepath.Join("fixtures", "config.yaml"), configDir) l := testhelpers.NewLogger() hasQuitC := make(chan bool) go func() { wantExitCode := 0 exitCode, err := subMain(flags, l) if exitCode != wantExitCode { t.Errorf("subMain(%v) exitCode: %d, want: %d", flags, exitCode, wantExitCode) } if err != nil { t.Errorf("subMain(%v): %s", flags, err) } hasQuitC <- true }() interruptC := time.NewTimer(time.Second).C timeoutC := time.NewTimer(6 * time.Second).C for { select { case <-interruptC: interruptProcess(t) case <-timeoutC: t.Fatal("subMain() hasn't stopped") case <-hasQuitC: return } } }
Use headings on admin index instead of descriptions.
<div class="content"> <h1>Site Admin</h1> <div class="content-body"> <?php if (!empty($AdminMethods)) { ?> <h2>Tools</h2> <ul> <?php foreach ($AdminMethods as $name => $url) { ?> <li><a href="<?= $url ?>" title="Access this admin tool"><?= $name ?></a></li> <?php } ?> </ul> <?php } if (!empty($ModelAdminURLs)) { ?> <h2>Data Types</h2> <ul> <?php foreach ($ModelAdminURLs as $modelName => $url) { ?> <li><a href="<?= $url ?>" title="Access this admin tool"><?= $modelName ?></a></li> <?php } ?> </ul> <?php } ?> </div> </div>
<div class="content"> <h1>Site Admin</h1> <div class="content-body"> <?php if (!empty($AdminMethods)) { ?> <p>The following tools are available to administer this site:</p> <ul> <?php foreach ($AdminMethods as $name => $url) { ?> <li><a href="<?= $url ?>" title="Access this admin tool"><?= $name ?></a></li> <?php } ?> </ul> <?php } if (!empty($ModelAdminURLs)) { ?> <!-- p>Select an object type to administer:</p --> <!-- p>These controllers provide an admin method:</p --> <p>You may administer the following types of objects in the database:</p> <ul> <?php foreach ($ModelAdminURLs as $modelName => $url) { ?> <li><a href="<?= $url ?>" title="Access this admin tool"><?= $modelName ?></a></li> <?php } ?> </ul> <?php } ?> </div> </div>
Set required alt attr instead of title for <img>s
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" alt="' + match + '" src="' + path + '"/>'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Emoji = {}; Emoji.baseImagePath = '/packages/davidfrancisco_twemoji/img/'; Emoji.convert = function (str) { if (typeof str !== 'string') { return ''; } return str.replace(/:[\+\-a-z0-9_]+:/gi, function(match) { var imgName = match.slice(1, -1), path = Emoji.baseImagePath + imgName + '.png'; return '<img class="emoji" title="' + match + '" src="' + path + '"/>'; }); }; // borrowed code from https://github.com/meteor/meteor/blob/devel/packages/showdown/template-integration.js if (Package.templating) { var Template = Package.templating.Template; var Blaze = Package.blaze.Blaze; // implied by `templating` var HTML = Package.htmljs.HTML; // implied by `blaze` Blaze.Template.registerHelper('emoji', new Template('emoji', function () { var view = this, content = ''; if (view.templateContentBlock) { // this is for the block usage eg: {{#emoji}}:smile:{{/emoji}} content = Blaze._toText(view.templateContentBlock, HTML.TEXTMODE.STRING); } else { // this is for the direct usage eg: {{> emoji ':blush:'}} content = view.parentView.dataVar.get(); } return HTML.Raw(Emoji.convert(content)); })); }
Fix _select_attributes from project api
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. """ PYBOSSA api module for exposing domain object ProjectStats via an API. """ import copy from flask import request from pybossa.model.project_stats import ProjectStats from api_base import APIBase class ProjectStatsAPI(APIBase): """Class for domain object ProjectStats.""" __class__ = ProjectStats def _select_attributes(self, stats_data): if not request.args.get('full'): tmp = copy.deepcopy(stats_data) tmp['info'].pop('hours_stats', None) tmp['info'].pop('dates_stats', None) tmp['info'].pop('users_stats', None) return tmp return stats_data
# -*- coding: utf8 -*- # This file is part of PYBOSSA. # # Copyright (C) 2015 Scifabric LTD. # # PYBOSSA is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PYBOSSA is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with PYBOSSA. If not, see <http://www.gnu.org/licenses/>. """ PYBOSSA api module for exposing domain object ProjectStats via an API. """ from flask import request from pybossa.model.project_stats import ProjectStats from api_base import APIBase class ProjectStatsAPI(APIBase): """Class for domain object ProjectStats.""" __class__ = ProjectStats def _select_attributes(self, stats_data): if request.args.get('full'): return stats_data stats_data['info'].pop('hours_stats', None) stats_data['info'].pop('dates_stats', None) stats_data['info'].pop('users_stats', None) return stats_data
Revert "Re-activate code coverage test." This reverts commit 9a5d5122139aedddbbcea169525e924269f6c20a.
# coding=utf-8 # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. """Test the run_ccoverage.py file.""" from __future__ import absolute_import, division, print_function, unicode_literals # isort:skip import logging import unittest import pytest import funfuzz FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test") logging.basicConfig(level=logging.DEBUG) logging.getLogger("flake8").setLevel(logging.WARNING) class RunCcoverageTests(unittest.TestCase): """"TestCase class for functions in run_ccoverage.py""" @pytest.mark.skip(reason="disable for now until actual use") def test_main(self): """Run run_ccoverage with test parameters.""" build_url = "https://build.fuzzing.mozilla.org/builds/jsshell-mc-64-opt-gcov.zip" # run_ccoverage's main method does not actually return anything. self.assertTrue(not funfuzz.run_ccoverage.main(argparse_args=["--url", build_url]))
# coding=utf-8 # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. """Test the run_ccoverage.py file.""" from __future__ import absolute_import, division, print_function, unicode_literals # isort:skip import logging import unittest import funfuzz FUNFUZZ_TEST_LOG = logging.getLogger("run_ccoverage_test") logging.basicConfig(level=logging.DEBUG) logging.getLogger("flake8").setLevel(logging.WARNING) class RunCcoverageTests(unittest.TestCase): """"TestCase class for functions in run_ccoverage.py""" def test_main(self): """Run run_ccoverage with test parameters.""" build_url = "https://build.fuzzing.mozilla.org/builds/jsshell-mc-64-opt-gcov.zip" # run_ccoverage's main method does not actually return anything. self.assertTrue(not funfuzz.run_ccoverage.main(argparse_args=["--url", build_url]))
Set DEBUG flag false again.
package com.jakewharton.trakt; import junit.framework.TestCase; public abstract class BaseTestCase extends TestCase { protected static final String API_KEY = "5abdaea0246b840cb7c709f8e1788fed"; public static final String USERNAME = "sgtest"; public static final String PASSWORD_SHA_1 = "2a4d398c09ec9c6915d1f46710ceed9673fa4e3d"; private static final boolean DEBUG = false; private final Trakt manager = new Trakt(); @Override public void setUp() { manager.setApiKey(API_KEY); manager.setAuthentication(USERNAME, PASSWORD_SHA_1); manager.setIsDebug(DEBUG); } protected final Trakt getManager() { return manager; } }
package com.jakewharton.trakt; import junit.framework.TestCase; public abstract class BaseTestCase extends TestCase { protected static final String API_KEY = "5abdaea0246b840cb7c709f8e1788fed"; public static final String USERNAME = "sgtest"; public static final String PASSWORD_SHA_1 = "2a4d398c09ec9c6915d1f46710ceed9673fa4e3d"; private static final boolean DEBUG = true; private final Trakt manager = new Trakt(); @Override public void setUp() { manager.setApiKey(API_KEY); manager.setAuthentication(USERNAME, PASSWORD_SHA_1); manager.setIsDebug(DEBUG); } protected final Trakt getManager() { return manager; } }
Return file as part of upload
import Plugin from './Plugin'; export default class Multipart extends Plugin { constructor(core, opts) { super(core, opts); this.type = 'uploader'; } run(results) { console.log({ class : 'Multipart', method : 'run', results: results }); const files = this.extractFiles(results); this.core.setProgress(this, 0); var uploaded = []; var uploaders = []; for (var i in files) { var file = files[i]; uploaders.push(this.upload(file, i, files.length)); } return Promise.all(uploaders); } upload(file, current, total) { var formPost = new FormData(); formPost.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('POST', this.opts.endpoint, true); xhr.addEventListener('progress', (e) => { var percentage = (e.loaded / e.total * 100).toFixed(2); this.setProgress(percentage, current, total); }); xhr.addEventListener('load', () => { var upload = {file: file}; return Promise.resolve(upload); }); xhr.addEventListener('error', () => { return Promise.reject('fucking error!'); }); xhr.send(formPost); } }
import Plugin from './Plugin'; export default class Multipart extends Plugin { constructor(core, opts) { super(core, opts); this.type = 'uploader'; } run(results) { console.log({ class : 'Multipart', method : 'run', results: results }); const files = this.extractFiles(results); this.core.setProgress(this, 0); var uploaded = []; var uploaders = []; for (var i in files) { var file = files[i]; uploaders.push(this.upload(file, i, files.length)); } return Promise.all(uploaders); } upload(file, current, total) { var formPost = new FormData(); formPost.append('file', file); var xhr = new XMLHttpRequest(); xhr.open('POST', this.opts.endpoint, true); xhr.addEventListener('progress', (e) => { var percentage = (e.loaded / e.total * 100).toFixed(2); this.setProgress(percentage, current, total); }); xhr.addEventListener('load', () => { return Promise.resolve(upload); }); xhr.addEventListener('error', () => { return Promise.reject('fucking error!'); }); xhr.send(formPost); } }
Add Creative Commons to CC licence names
<?php global $gds_image_licences; $gds_image_licences = [ 'ogl' => 'OGL', 'cc-by' => 'Creative Commons Attribution', 'cc-by-sa' => 'Creative Commons Attribution-ShareAlike', 'cc-by-nd' => 'Creative Commons Attribution-NoDerivs', 'cc-by-nc' => 'Creative Commons Attribution-NonCommercial', 'cc-by-nc-sa' => 'Creative Commons Attribution-NonCommercial-ShareAlike', 'cc-by-nc-nd' => 'Creative Commons Attribution-NonCommercial-NoDerivs', 'other' => 'Other', ]; add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) { global $gds_image_licences; $_licence = get_post_meta($id, 'licence', true); $licence = $gds_image_licences[$_licence]; $copyright_holder = get_post_meta($id, 'copyright_holder', true); $link_to_source = get_post_meta($id, 'link_to_source', true); $caption = 'Licence: '.esc_html($licence).' <a href="'.esc_attr($link_to_source).'">'.esc_html($copyright_holder).'</a>'; return '<figure>'.$html.'<figcaption>'.$caption.'</figcaption></figure>'; }, 999, 8);
<?php global $gds_image_licences; $gds_image_licences = [ 'ogl' => 'OGL', 'cc-by' => 'Attribution', 'cc-by-sa' => 'Attribution-ShareAlike', 'cc-by-nd' => 'Attribution-NoDerivs', 'cc-by-nc' => 'Attribution-NonCommercial', 'cc-by-nc-sa' => 'Attribution-NonCommercial-ShareAlike', 'cc-by-nc-nd' => 'Attribution-NonCommercial-NoDerivs', 'other' => 'Other', ]; add_filter('image_send_to_editor', function ($html, $id, $caption, $title, $align, $url, $size, $alt) { global $gds_image_licences; $_licence = get_post_meta($id, 'licence', true); $licence = $gds_image_licences[$_licence]; $copyright_holder = get_post_meta($id, 'copyright_holder', true); $link_to_source = get_post_meta($id, 'link_to_source', true); $caption = 'Licence: '.esc_html($licence).' <a href="'.esc_attr($link_to_source).'">'.esc_html($copyright_holder).'</a>'; return '<figure>'.$html.'<figcaption>'.$caption.'</figcaption></figure>'; }, 999, 8);
Correct trove classifier for license
from setuptools import setup, find_packages with open('README.rst') as fd: long_description = fd.read() setup(name='Flask-ESClient', version='0.1.1', description='Flask extension for ESClient (elasticsearch client)', long_description=long_description, author='Baiju Muthukadan', author_email='baiju.m.mail@gmail.com', url='https://github.com/baijum/flask-esclient', py_modules=['flask_esclient', 'test_flask_esclient'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'Flask', 'ESClient', ], test_suite='test_flask_esclient.suite', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
from setuptools import setup, find_packages with open('README.rst') as fd: long_description = fd.read() setup(name='Flask-ESClient', version='0.1.1', description='Flask extension for ESClient (elasticsearch client)', long_description=long_description, author='Baiju Muthukadan', author_email='baiju.m.mail@gmail.com', url='https://github.com/baijum/flask-esclient', py_modules=['flask_esclient', 'test_flask_esclient'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'Flask', 'ESClient', ], test_suite='test_flask_esclient.suite', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD 2-Clause License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Fix save disable currency on admin
TinyCore.AMD.define('currency-table', ['devicePackage' ], function () { return { onStart: function () { setTimeout( function() { $('#currency-loading').fadeOut('fast', function() { $('#currency-table').fadeIn(); }); $('.switch input').change( function() { var sUrl = this.checked === true ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value ; $.ajax({ url: sUrl, type: 'post' }); }); } , 1500); } }; });
TinyCore.AMD.define('currency-table', ['devicePackage' ], function () { return { onStart: function () { setTimeout( function() { $('#currency-loading').fadeOut('fast', function() { $('#currency-table').fadeIn(); }); $('.switch input').change( function() { var sUrl = this.value === 'on' ? document.getElementById('enable-' + this.id).value : document.getElementById('disable-' + this.id).value ; $.ajax({ url: sUrl, type: 'post' }); }); } , 1500); } }; });
Add api_key to filtered variables. We don't use it yet, but the plan is the migrate there and it's better to just have the filtering in place. (imported from commit d0e7f40e8a439b8e8751da954e79b5f67226e5a9)
from __future__ import absolute_import from django.views.debug import SafeExceptionReporterFilter from django.http import build_request_repr class ZulipExceptionReporterFilter(SafeExceptionReporterFilter): def get_post_parameters(self, request): filtered_post = SafeExceptionReporterFilter.get_post_parameters(self, request).copy() filtered_vars = ['content', 'secret', 'password', 'key', 'api-key', 'subject', 'stream', 'subscriptions', 'to', 'csrfmiddlewaretoken', 'api_key'] for var in filtered_vars: if var in filtered_post: filtered_post[var] = '**********' return filtered_post def get_request_repr(self, request): if request is None: return repr(None) else: return build_request_repr(request, POST_override=self.get_post_parameters(request), COOKIES_override="**********", META_override="**********")
from __future__ import absolute_import from django.views.debug import SafeExceptionReporterFilter from django.http import build_request_repr class ZulipExceptionReporterFilter(SafeExceptionReporterFilter): def get_post_parameters(self, request): filtered_post = SafeExceptionReporterFilter.get_post_parameters(self, request).copy() filtered_vars = ['content', 'secret', 'password', 'key', 'api-key', 'subject', 'stream', 'subscriptions', 'to', 'csrfmiddlewaretoken'] for var in filtered_vars: if var in filtered_post: filtered_post[var] = '**********' return filtered_post def get_request_repr(self, request): if request is None: return repr(None) else: return build_request_repr(request, POST_override=self.get_post_parameters(request), COOKIES_override="**********", META_override="**********")
Use iteritems in Python 2.
import os import tee class Process(object): """Process related functions using the tee module.""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ if self.quiet: echo = echo2 = False return tee.popen(cmd, echo, echo2, env=self.env) def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc def os_system(self, cmd): # env *updates* os.environ if self.quiet: cmd = cmd + ' >%s 2>&1' % os.devnull if self.env: cmd = ''.join('export %s="%s"\n' % (k, v) for k, v in self.env.iteritems()) + cmd return os.system(cmd)
import os import tee class Process(object): """Process related functions using the tee module.""" def __init__(self, quiet=False, env=None): self.quiet = quiet self.env = env def popen(self, cmd, echo=True, echo2=True): # env *replaces* os.environ if self.quiet: echo = echo2 = False return tee.popen(cmd, echo, echo2, env=self.env) def pipe(self, cmd): rc, lines = self.popen(cmd, echo=False) if rc == 0 and lines: return lines[0] return '' def system(self, cmd): rc, lines = self.popen(cmd) return rc def os_system(self, cmd): # env *updates* os.environ if self.quiet: cmd = cmd + ' >%s 2>&1' % os.devnull if self.env: cmd = ''.join('export %s="%s"\n' % (k, v) for k, v in self.env.items()) + cmd return os.system(cmd)
Add LICENSE to package data The LICENSE file isn't included with the version found on PyPI. Including it in the `package_data` argument passed to `setup` should fix this.
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup settings = dict() # Publish if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() settings.update( name='whenpy', version='0.1.0', description='Friendly Dates and Times', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/when.py', packages=['when'], package_data={'': ['LICENSE']}, include_package_data=True, install_requires=['pytz'], license=open('LICENSE').read(), classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), ) setup(**settings)
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup settings = dict() # Publish if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() settings.update( name='whenpy', version='0.1.0', description='Friendly Dates and Times', long_description=open('README.rst').read(), author='Andy Dirnberger', author_email='dirn@dirnonline.com', url='https://github.com/dirn/when.py', packages=['when'], install_requires=['pytz'], license=open('LICENSE').read(), classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules', ), ) setup(**settings)
Add pretty print for msg object
package messages import ( "encoding/json" "code.google.com/p/go-uuid/uuid" "github.com/qp/go/utils" ) // Message is the standard QP messaging object. // It is used to facilitate all communication between // QP nodes, as well as containing the metadata // necessary to implement the pipeline functionality. type Message struct { To utils.StringDES `json:"to"` // array of destination addresses From utils.StringDES `json:"from"` // array of addresses encountered thus far ID string `json:"id"` // a UUID identifying this message Data interface{} `json:"data"` // arbitrary data payload Err interface{} `json:"err,omitempty"` // arbitrary error payload. nil if no error } // NewMessage creates a new Message object with appropriate fields set. func NewMessage(serviceName string, data interface{}, to ...string) *Message { id := uuid.New() return &Message{To: to, From: []string{serviceName}, ID: id, Data: data} } // HasError returns true if the Err field is set func (m *Message) HasError() bool { return m.Err != nil } // String provides a pretty JSON string representation of the message func (m *Message) String() string { bytes, _ := json.MarshalIndent(m, "", " ") return string(bytes) }
package messages import ( "code.google.com/p/go-uuid/uuid" "github.com/qp/go/utils" ) // Message is the standard QP messaging object. // It is used to facilitate all communication between // QP nodes, as well as containing the metadata // necessary to implement the pipeline functionality. type Message struct { To utils.StringDES `json:"to"` // array of destination addresses From utils.StringDES `json:"from"` // array of addresses encountered thus far ID string `json:"id"` // a UUID identifying this message Data interface{} `json:"data"` // arbitrary data payload Err interface{} `json:"err,omitempty"` // arbitrary error payload. nil if no error } // NewMessage creates a new Message object with appropriate fields set. func NewMessage(serviceName string, data interface{}, to ...string) *Message { id := uuid.New() return &Message{To: to, From: []string{serviceName}, ID: id, Data: data} } // HasError returns true if the Err field is set func (m *Message) HasError() bool { return m.Err != nil }
Fix dispose (WeakMap.clear is obsolete and should not be used)
/** * @author mrdoob / http://mrdoob.com/ */ function WebGLObjects( gl, geometries, attributes, info ) { var updateMap = new WeakMap(); function update( object ) { var frame = info.render.frame; var geometry = object.geometry; var buffergeometry = geometries.get( object, geometry ); // Update once per frame if ( updateMap.get( buffergeometry ) !== frame ) { if ( geometry.isGeometry ) { buffergeometry.updateFromObject( object ); } geometries.update( buffergeometry ); updateMap.set( buffergeometry, frame ); } if ( object.isInstancedMesh ) { attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); } return buffergeometry; } function dispose() { updateMap = new WeakMap(); } return { update: update, dispose: dispose }; } export { WebGLObjects };
/** * @author mrdoob / http://mrdoob.com/ */ function WebGLObjects( gl, geometries, attributes, info ) { var updateMap = new WeakMap(); function update( object ) { var frame = info.render.frame; var geometry = object.geometry; var buffergeometry = geometries.get( object, geometry ); // Update once per frame if ( updateMap.get( buffergeometry ) !== frame ) { if ( geometry.isGeometry ) { buffergeometry.updateFromObject( object ); } geometries.update( buffergeometry ); updateMap.set( buffergeometry, frame ); } if ( object.isInstancedMesh ) { attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER ); } return buffergeometry; } function dispose() { updateMap.clear(); } return { update: update, dispose: dispose }; } export { WebGLObjects };
Add blank line at end of file
<?php namespace Byng\Pimcore\Elasticsearch\Gateway; use Byng\Pimcore\Elasticsearch\Model\ResultsList; use Byng\Pimcore\Elasticsearch\Query\QueryBuilder; /** * Raw Gateway Interface * @author Max Baldanza <mbaldanza@inviqa.com> */ interface RawGatewayInterface { /** * @param string $index * @param string $type * @param QueryBuilder $query * * @return ResultsList */ public function findByQueryBuilder($index, $type, QueryBuilder $query); /** * @param string $index * @param string $type * @param array $query * * @return ResultsList */ public function findByArray($index, $type, array $query); /** * @param array $data */ public function save(array $data); /** * @param string $index * @param string $type * @param int $id */ public function delete($index, $type, $id); }
<?php namespace Byng\Pimcore\Elasticsearch\Gateway; use Byng\Pimcore\Elasticsearch\Model\ResultsList; use Byng\Pimcore\Elasticsearch\Query\QueryBuilder; /** * Raw Gateway Interface * @author Max Baldanza <mbaldanza@inviqa.com> */ interface RawGatewayInterface { /** * @param string $index * @param string $type * @param QueryBuilder $query * * @return ResultsList */ public function findByQueryBuilder($index, $type, QueryBuilder $query); /** * @param string $index * @param string $type * @param array $query * * @return ResultsList */ public function findByArray($index, $type, array $query); /** * @param array $data */ public function save(array $data); /** * @param string $index * @param string $type * @param int $id */ public function delete($index, $type, $id); }
Improve logic for more edge cases
const UPower = imports.ui.status.power.UPower const Main = imports.ui.main let watching function bind () { getBattery(proxy => { watching = proxy.connect('g-properties-changed', update) }) } function unbind () { getBattery(proxy => { proxy.disconnect(watching) }) } function show () { getBattery((proxy, icon) => { icon.show() }) } function hide () { getBattery((proxy, icon) => { icon.hide() }) } function update () { getBattery(proxy => { let isDischarging = proxy.State === UPower.DeviceState.DISCHARGING let isFullyCharged = proxy.State === UPower.DeviceState.FULLY_CHARGED if (proxy.Type !== UPower.DeviceKind.BATTERY) { show() } else if (isFullyCharged) { hide() } else if (proxy.Percentage === 100 && !isDischarging) { hide() } else { show() } }) } function getBattery (callback) { let menu = Main.panel.statusArea.aggregateMenu if (menu && menu._power) { callback(menu._power._proxy, menu._power.indicators) } } /* exported init, enable, disable */ function init () { } function enable () { bind() update() } function disable () { unbind() show() }
const UPower = imports.ui.status.power.UPower const Main = imports.ui.main let watching function bind () { getBattery(proxy => { watching = proxy.connect('g-properties-changed', update) }) } function unbind () { getBattery(proxy => { proxy.disconnect(watching) }) } function show () { getBattery((proxy, icon) => { icon.show() }) } function hide () { getBattery((proxy, icon) => { icon.hide() }) } function update () { getBattery(proxy => { let isBattery = proxy.Type === UPower.DeviceKind.BATTERY let notDischarging = proxy.State !== UPower.DeviceState.DISCHARGING if (isBattery && notDischarging && proxy.Percentage === 100) { hide() } else { show() } }) } function getBattery (callback) { let menu = Main.panel.statusArea.aggregateMenu if (menu && menu._power) { callback(menu._power._proxy, menu._power.indicators) } } /* exported init, enable, disable */ function init () { } function enable () { bind() update() } function disable () { unbind() show() }
Fix var reference (caused infinite loop)
'use strict'; var isCallable = require('es5-ext/lib/Object/is-callable') , name, now, round, dateNow; if ((typeof performance !== 'undefined') && performance) { if (isCallable(performance.now)) { name = 'now'; } else if (isCallable(performance.mozNow)) { name = 'mozNow'; } else if (isCallable(performance.msNow)) { name = 'msNow'; } else if (isCallable(performance.oNow)) { name = 'oNow'; } else if (isCallable(performance.webkitNow)) { name = 'webkitNow'; } if (name) { round = Math.round; dateNow = Date.now; now = function () { return round((dateNow() + performance[name]() % 1) * 1000); }; } } if (!now && (typeof process !== 'undefined') && process && (process.title === 'node')) { try { now = (require)('microtime').now; } catch (e) {} } if (!now) { dateNow = Date.now; now = function () { return dateNow() * 1000; }; } module.exports = now;
'use strict'; var isCallable = require('es5-ext/lib/Object/is-callable') , name, now, round, dateNow; if ((typeof performance !== 'undefined') && performance) { if (isCallable(performance.now)) { name = 'now'; } else if (isCallable(performance.mozNow)) { name = 'mozNow'; } else if (isCallable(performance.msNow)) { name = 'msNow'; } else if (isCallable(performance.oNow)) { name = 'oNow'; } else if (isCallable(performance.webkitNow)) { name = 'webkitNow'; } if (name) { round = Math.round; dateNow = Date.now; now = function () { return round((now() + performance[name]() % 1) * 1000); }; } } if (!now && (typeof process !== 'undefined') && process && (process.title === 'node')) { try { now = (require)('microtime').now; } catch (e) {} } if (!now) { dateNow = Date.now; now = function () { return dateNow() * 1000; }; } module.exports = now;
Remove silent option for debugging
const ghpages = require('gh-pages') const gitRemoteOriginUrl = require('git-remote-origin-url') const path = require('path') const GH_TOKEN = process.env.GH_TOKEN const GH_USER = process.env.GH_USER const GH_EMAIL = process.env.GH_EMAIL function publish (remoteUrl) { const repo = GH_TOKEN ? remoteUrl.replace(/(\/\/)/, `$1${GH_TOKEN}@`) : remoteUrl const user = GH_USER && GH_EMAIL ? { name: GH_USER, email: GH_EMAIL } : {} console.log('Starting deployment to GitHub pages') ghpages.publish(path.join(__dirname, 'dist'), Object.assign({}, { repo: repo }, user), function (err) { if (err) { console.error(`Deployment error: ${err.message}`) return process.exit(1) } console.log('Deployment complete!') return process.exit(0) }) } gitRemoteOriginUrl().then(publish)
const ghpages = require('gh-pages') const gitRemoteOriginUrl = require('git-remote-origin-url') const path = require('path') const GH_TOKEN = process.env.GH_TOKEN const GH_USER = process.env.GH_USER const GH_EMAIL = process.env.GH_EMAIL function publish (remoteUrl) { const repo = GH_TOKEN ? remoteUrl.replace(/(\/\/)/, `$1${GH_TOKEN}@`) : remoteUrl const user = GH_USER && GH_EMAIL ? { name: GH_USER, email: GH_EMAIL } : {} console.log('Starting deployment to GitHub pages') ghpages.publish(path.join(__dirname, 'dist'), Object.assign({}, { silent: true, repo: repo }, user), function (err) { if (err) { console.error(`Deployment error: ${err.message}`) return process.exit(1) } console.log('Deployment complete!') return process.exit(0) }) } gitRemoteOriginUrl().then(publish)
Fix typo and use span for upgrade notice block (already nested in p tag)
<?php /** * Adds the WordPress plugin update action if we are on the plugins page. * * @since v1.1.1 */ global $pagenow; /** * WordPress action for setting the upgrade notification message at the plugins page. * @param array $plugin_data Array of plugin data. * @param array $r Array of metadata about the plugin update. */ function in_plugin_update_message_acf_recaptcha($plugin_data, $r) { if (isset($r->upgrade_notice) && strlen(trim($r->upgrade_notice)) > 0) { ?> <span style="display: block; background-color: #d54e21; padding: 10px; color: #f9f9f9; margin: 10px 0"> <strong>Upgrade Notice:</strong> <?php echo esc_html($r->upgrade_notice); ?> </span> <?php } } if ('plugins.php' === $pagenow) { $file = ACF_RECAPTCHA_BASENAME; $folder = basename(ACF_RECAPTCHA_ABSPATH); $hook = "in_plugin_update_message-{$folder}/{$file}"; add_action($hook, 'in_plugin_update_message_acf_recaptcha', 20, 2); }
<?php /** * Adds the WordPress plugin update action if we are on the plugins page. * * @since v1.1.1 */ global $pagenow; /** * WordPress action for setting the upgrade notification message at the plugins page. * @param array $plugin_data Array of plugin data. * @param array $r Array of metadata about the plugin update. */ function in_plugin_update_message($plugin_data, $r) { if (isset($r->upgrade_notice) && strlen(trim($r->upgrade_notice)) > 0) { ?> <p style="background-color: #d54e21; padding: 10px; color: #f9f9f9; margin-top: 10px"> <strong>Upgrade Notice:</strong> <?php echo esc_html($r->upgrade_notice); ?> </p> <?php } } if ('plugins.php' === $pagenow) { $file = ACF_RECAPTCHA_BASENAME; $folder = basename(ACF_RECAPTCHA_ABSPATH); $hook = "in_plugin_update_message-{$folder}/{$file}"; add_action($hook, 'in_plugin_update_message_acf_recaptcha', 20, 2); }
Fix user profile signal handler.
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(**kwargs): if kwargs["created"]: try: get_profile_for_user(kwargs["instance"]) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
from django.db import DatabaseError, connection from django.db.models.signals import post_save from mezzanine.accounts import get_profile_for_user from mezzanine.conf import settings __all__ = () if getattr(settings, "AUTH_PROFILE_MODULE", None): def create_profile(user_model, instance, created, **kwargs): if created: try: get_profile_for_user(instance) except DatabaseError: # User creation in initial syncdb may have been triggered, # while profile model is under migration management and # doesn't exist yet. We close the connection so that it # gets re-opened, allowing syncdb to continue and complete. connection.close() post_save.connect(create_profile, sender=settings.AUTH_USER_MODEL, weak=False)
Add callback to updateStateValue function
import React from 'react'; import curry from 'lodash/function/curry'; import isFunction from 'lodash/lang/isFunction'; import wrapDisplayName from './wrapDisplayName'; export const withState = ( stateName, stateUpdaterName, initialState, BaseComponent ) => ( class extends React.Component { static displayName = wrapDisplayName(BaseComponent, 'withState'); state = { stateValue: initialState }; updateStateValue = (updateFn, callback) => ( this.setState(({ stateValue }) => ({ stateValue: isFunction(updateFn) ? updateFn(stateValue) : updateFn }), callback) ) render() { const childProps = { ...this.props, [stateName]: this.state.stateValue, [stateUpdaterName]: this.updateStateValue }; return <BaseComponent {...childProps}/>; } } ); export default curry(withState);
import React from 'react'; import curry from 'lodash/function/curry'; import isFunction from 'lodash/lang/isFunction'; import wrapDisplayName from './wrapDisplayName'; export const withState = ( stateName, stateUpdaterName, initialState, BaseComponent ) => ( class extends React.Component { static displayName = wrapDisplayName(BaseComponent, 'withState'); state = { stateValue: initialState }; updateStateValue = updateFn => ( this.setState(({ stateValue }) => ({ stateValue: isFunction(updateFn) ? updateFn(stateValue) : updateFn })) ) render() { const childProps = { ...this.props, [stateName]: this.state.stateValue, [stateUpdaterName]: this.updateStateValue }; return <BaseComponent {...childProps}/>; } } ); export default curry(withState);
Change lock reason -> info This makes it more apparent that the information passed in isn't required nor will it conform to any standard. There may be call sites that can't provide good contextual info, and we don't want to count on that value.
package state import ( "github.com/hashicorp/terraform/terraform" ) // State is the collection of all state interfaces. type State interface { StateReader StateWriter StateRefresher StatePersister } // StateReader is the interface for things that can return a state. Retrieving // the state here must not error. Loading the state fresh (an operation that // can likely error) should be implemented by RefreshState. If a state hasn't // been loaded yet, it is okay for State to return nil. type StateReader interface { State() *terraform.State } // StateWriter is the interface that must be implemented by something that // can write a state. Writing the state can be cached or in-memory, as // full persistence should be implemented by StatePersister. type StateWriter interface { WriteState(*terraform.State) error } // StateRefresher is the interface that is implemented by something that // can load a state. This might be refreshing it from a remote location or // it might simply be reloading it from disk. type StateRefresher interface { RefreshState() error } // StatePersister is implemented to truly persist a state. Whereas StateWriter // is allowed to perhaps be caching in memory, PersistState must write the // state to some durable storage. type StatePersister interface { PersistState() error } // Locker is implemented to lock state during command execution. // The optional info parameter can be recorded with the lock, but the // implementation should not depend in its value. type Locker interface { Lock(info string) error Unlock() error }
package state import ( "github.com/hashicorp/terraform/terraform" ) // State is the collection of all state interfaces. type State interface { StateReader StateWriter StateRefresher StatePersister } // StateReader is the interface for things that can return a state. Retrieving // the state here must not error. Loading the state fresh (an operation that // can likely error) should be implemented by RefreshState. If a state hasn't // been loaded yet, it is okay for State to return nil. type StateReader interface { State() *terraform.State } // StateWriter is the interface that must be implemented by something that // can write a state. Writing the state can be cached or in-memory, as // full persistence should be implemented by StatePersister. type StateWriter interface { WriteState(*terraform.State) error } // StateRefresher is the interface that is implemented by something that // can load a state. This might be refreshing it from a remote location or // it might simply be reloading it from disk. type StateRefresher interface { RefreshState() error } // StatePersister is implemented to truly persist a state. Whereas StateWriter // is allowed to perhaps be caching in memory, PersistState must write the // state to some durable storage. type StatePersister interface { PersistState() error } // Locker is implemented to lock state during command execution. type Locker interface { Lock(reason string) error Unlock() error }
Replace the exceptions in backend classes
# author: Milan Kubik NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass" from ipaqe_provision_hosts.errors import IPAQEProvisionerError class VMsNotCreatedError(IPAQEProvisionerError): pass class IDMBackendBase(object): """IDMBackendBase class This class represents a contract between the idm-prepare-hosts utility and a backend implementation. """ def __init__(self, config=None): self._config = config or {} self._vms = [] @property def vms(self): """The attribute returns a list of host entries""" if not self._vms: raise VMsNotCreatedError("No VMs were provisioned yet") else: return self._vms def provision_resources(self, vm_count): """Provision the hosts in a backend""" raise NotImplementedError(NOT_IMPLEMENTED_MSG) def delete_resources(self): """Delete the resources provisioned by the backend""" raise NotImplementedError(NOT_IMPLEMENTED_MSG)
# author: Milan Kubik NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass" class IDMBackendException(Exception): pass class VMsNotCreatedError(IDMBackendException): pass class IDMBackendMissingName(IDMBackendException): pass class IDMBackendBase(object): """IDMBackendBase class This class represents a contract between the idm-prepare-hosts utility and a backend implementation. """ def __init__(self, config=None): self._config = config or {} self._vms = [] @property def vms(self): """The attribute returns a list of host entries""" if not self._vms: raise VMsNotCreatedError("No VMs were provisioned yet") else: return self._vms def provision_resources(self, vm_count): """Provision the hosts in a backend""" raise NotImplementedError(NOT_IMPLEMENTED_MSG) def delete_resources(self): """Delete the resources provisioned by the backend""" raise NotImplementedError(NOT_IMPLEMENTED_MSG)
Add password as a write_only field on CreateUserSerializer
from django.core.exceptions import ValidationError from django.contrib.auth.password_validation import validate_password from ovp_users import models from rest_framework import serializers class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['id', 'name', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def validate(self, data): password = data.get('password') errors = dict() try: validate_password(password=password) except ValidationError as e: errors['password'] = list(e.messages) if errors: raise serializers.ValidationError(errors) return super(UserCreateSerializer, self).validate(data) class UserSearchSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['name'] class RecoveryTokenSerializer(serializers.Serializer): email = serializers.CharField(required=True) class Meta: fields = ['email'] class RecoverPasswordSerializer(serializers.Serializer): email = serializers.CharField(required=True) token = serializers.CharField(required=True) new_password = serializers.CharField(required=True) class Meta: fields = ['email', 'token', 'new_password']
from django.core.exceptions import ValidationError from django.contrib.auth.password_validation import validate_password from ovp_users import models from rest_framework import serializers class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['id', 'name', 'email', 'password'] def validate(self, data): password = data.get('password') errors = dict() try: validate_password(password=password) pass except ValidationError as e: errors['password'] = list(e.messages) if errors: raise serializers.ValidationError(errors) return super(UserCreateSerializer, self).validate(data) class UserSearchSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['name'] class RecoveryTokenSerializer(serializers.Serializer): email = serializers.CharField(required=True) class Meta: fields = ['email'] class RecoverPasswordSerializer(serializers.Serializer): email = serializers.CharField(required=True) token = serializers.CharField(required=True) new_password = serializers.CharField(required=True) class Meta: fields = ['email', 'token', 'new_password']
Add a print with file where mistake is
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") print(infile) sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as ET import glob import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def parse(): for infile in glob.glob('*.xml'): try: tree = ET.parse(infile) root = tree.getroot() if root.findall('.//FatalError'): eprint("Error detected") sys.exit(1) except ParseError: eprint("The file xml isn't correct. There were some mistakes in the tests ") sys.exit(1) def main(): parse() if __name__ == '__main__': main()
Add logic to separate target from message and recombine message.
var l10n_file = __dirname + '/../l10n/commands/whisper.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { console.log(args); args = args.split(' '); console.log(args); var target = args.shift(); var msg = args.join(''); if (args.length > 1) { player.sayL10n(l10n, 'YOU_WHISPER', target, msg); players.eachIf(function(p) { return otherPlayersInRoom(p); }, function(p) { if (p.getName() == target) p.sayL10n(l10n, 'THEY_WHISPER', player.getName(), msg); else p.sayL10n(l10n, 'OTHERS_WHISPER', player.getName(), target); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
var l10n_file = __dirname + '/../l10n/commands/whisper.yml'; var l10n = require('../src/l10n')(l10n_file); var CommandUtil = require('../src/command_util').CommandUtil; exports.command = function(rooms, items, players, npcs, Commands) { return function(args, player) { console.log(args); args = args.split(' '); console.log(args); if (args.length > 1) { player.sayL10n(l10n, 'YOU_WHISPER', args[0], args[1]); players.eachIf(function(p) { return otherPlayersInRoom(p); }, function(p) { if (p.getName() == args[0]) p.sayL10n(l10n, 'THEY_WHISPER', player.getName(), args[1]); else p.sayL10n(l10n, 'OTHERS_WHISPER', player.getName(), args[0]); }); return; } player.sayL10n(l10n, 'NOTHING_SAID'); return; } function otherPlayersInRoom(p) { if (p) return (p.getName() !== player.getName() && p.getLocation() === player.getLocation()); }; };
Fix JS bug in FAQ
document.addEventListener("DOMContentLoaded", function(){ var select = document.querySelector('.locales select'); select.addEventListener('change', function(event){ origin = window.location.origin; languageCode = event.currentTarget.selectedOptions[0].value window.location.replace(origin + "/" + languageCode) }); var faqHeaders = document.querySelectorAll('.frequently-asked-questions h4'); for (var i = 0; i < faqHeaders.length; ++i) { header = faqHeaders[i] header.addEventListener('click', toggleVisibility); } function toggleVisibility(event) { element = event.target; element.classList.toggle('is-visible') lastParagraph = element.nextElementSibling; paragraphs = []; paragraphs.push(lastParagraph); while (lastParagraph.nextElementSibling && lastParagraph.nextElementSibling.tagName == "P") { lastParagraph = lastParagraph.nextElementSibling; paragraphs.push(lastParagraph) } for (var i = 0; i < paragraphs.length; ++i) { paragraph = paragraphs[i] paragraph.classList.toggle('is-visible'); } } });
document.addEventListener("DOMContentLoaded", function(){ var select = document.querySelector('.locales select'); select.addEventListener('change', function(event){ origin = window.location.origin; languageCode = event.currentTarget.selectedOptions[0].value window.location.replace(origin + "/" + languageCode) }); var faqHeaders = document.querySelectorAll('.frequently-asked-questions h4'); for (var i = 0; i < faqHeaders.length; ++i) { header = faqHeaders[i] header.addEventListener('click', toggleVisibility); } function toggleVisibility(event) { element = event.target; element.classList.toggle('is-visible') lastParagraph = element.nextElementSibling; paragraphs = []; paragraphs.push(lastParagraph); while (lastParagraph.nextElementSibling.tagName == "P") { lastParagraph = lastParagraph.nextElementSibling; paragraphs.push(lastParagraph) } for (var i = 0; i < paragraphs.length; ++i) { paragraph = paragraphs[i] paragraph.classList.toggle('is-visible'); } } });
Fix SequenceLabelLearner to ensure it sets the preprocessors
package com.davidbracewell.apollo.ml.sequence; import com.davidbracewell.apollo.ml.Learner; import com.davidbracewell.apollo.ml.data.Dataset; import lombok.Getter; import lombok.NonNull; import lombok.Setter; /** * The type Sequence labeler learner. * * @author David B. Bracewell */ public abstract class SequenceLabelerLearner extends Learner<Sequence, SequenceLabeler> { private static final long serialVersionUID = 1L; @Getter @Setter protected Decoder decoder = new BeamDecoder(5); @Getter @Setter protected TransitionFeature transitionFeatures = TransitionFeature.FIRST_ORDER; @Getter @Setter protected SequenceValidator validator = SequenceValidator.ALWAYS_TRUE; @Override public SequenceLabeler train(@NonNull Dataset<Sequence> dataset) { dataset.encode(); update(dataset.getEncoderPair(), dataset.getPreprocessors()); transitionFeatures.fit(dataset); dataset.getEncoderPair().freeze(); SequenceLabeler model = trainImpl(dataset); model.finishTraining(); model.getFeatureEncoder().freeze(); return model; } }// END OF SequenceLabelerLearner
package com.davidbracewell.apollo.ml.sequence; import com.davidbracewell.apollo.ml.Learner; import com.davidbracewell.apollo.ml.data.Dataset; import lombok.Getter; import lombok.NonNull; import lombok.Setter; /** * The type Sequence labeler learner. * * @author David B. Bracewell */ public abstract class SequenceLabelerLearner extends Learner<Sequence, SequenceLabeler> { private static final long serialVersionUID = 1L; @Getter @Setter protected Decoder decoder = new BeamDecoder(5); @Getter @Setter protected TransitionFeature transitionFeatures = TransitionFeature.FIRST_ORDER; @Getter @Setter protected SequenceValidator validator = SequenceValidator.ALWAYS_TRUE; @Override public SequenceLabeler train(@NonNull Dataset<Sequence> dataset) { dataset.encode(); transitionFeatures.fit(dataset); dataset.getEncoderPair().freeze(); SequenceLabeler model = trainImpl(dataset); model.finishTraining(); model.getFeatureEncoder().freeze(); return model; } }// END OF SequenceLabelerLearner
Add newline to end of Pug generated HTML.
/* ___ usage ___ en_US ___ node highlight.bin.js <options> [sockets directory, sockets directory...] options: --help display help message -j, --json <string> optional json to feed to template ___ $ ___ en_US ___ select is required: the `--select` argument is a required argument language is required: the `--language` argument is a required argument ___ . ___ */ require('arguable')(module, require('cadence')(function (async, program) { var pug = require('pug') var delta = require('delta') program.helpIf(program.ultimate.help) async(function () { program.stdin.resume() delta(async()).ee(program.stdin).on('data', []).on('end') }, function (lines) { var f = pug.compile(Buffer.concat(lines).toString('utf8')) program.stdout.write(f(JSON.parse(program.ultimate.json || '{}')) + '\n') }) }))
/* ___ usage ___ en_US ___ node highlight.bin.js <options> [sockets directory, sockets directory...] options: --help display help message -j, --json <string> optional json to feed to template ___ $ ___ en_US ___ select is required: the `--select` argument is a required argument language is required: the `--language` argument is a required argument ___ . ___ */ require('arguable')(module, require('cadence')(function (async, program) { var pug = require('pug') var delta = require('delta') program.helpIf(program.ultimate.help) async(function () { program.stdin.resume() delta(async()).ee(program.stdin).on('data', []).on('end') }, function (lines) { var f = pug.compile(Buffer.concat(lines).toString('utf8')) program.stdout.write(f(JSON.parse(program.ultimate.json || '{}'))) }) }))
Remove console.log call on load
/** * @license Copyright (c) 2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/volojs/grunt-volo for details */ /*jslint node: true */ 'use strict'; module.exports = function (grunt) { grunt.registerTask('volo', 'Use volo to fetch code from GitHub', function () { var volo = require('volo'), args = this.args, //Tell grunt this is an async task. done = this.async(); volo(args).then(function (okText) { if (okText) { grunt.log.ok(okText); done(true); } }, function (errText) { grunt.log.error('ERROR: ' + errText); done(false); }); }); };
/** * @license Copyright (c) 2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/volojs/grunt-volo for details */ /*jslint node: true */ 'use strict'; console.log('LOADING VOLO'); module.exports = function (grunt) { grunt.registerTask('volo', 'Use volo to fetch code from GitHub', function () { var volo = require('volo'), args = this.args, //Tell grunt this is an async task. done = this.async(); volo(args).then(function (okText) { if (okText) { grunt.log.ok(okText); done(true); } }, function (errText) { grunt.log.error('ERROR: ' + errText); done(false); }); }); };
Update to prep for v0.3.0.2
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) description = 'The official Python3 Domo API SDK - Domo, Inc.' long_description = 'See https://github.com/domoinc/domo-python-sdk for more details.' setup( name='pydomo', version='0.3.0.2', description=description, long_description=long_description, author='Jeremy Morris', author_email='jeremy.morris@domo.com', url='https://github.com/domoinc/domo-python-sdk', download_url='https://github.com/domoinc/domo-python-sdk/tarball/0.2.2.1', keywords='domo api sdk', license='MIT', packages=find_packages(exclude=['examples']), install_requires=[ 'requests', 'requests_toolbelt', ], python_requires='>=3', )
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) description = 'The official Python3 Domo API SDK - Domo, Inc.' long_description = 'See https://github.com/domoinc/domo-python-sdk for more details.' setup( name='pydomo', version='0.3.0.01', description=description, long_description=long_description, author='Jeremy Morris', author_email='jeremy.morris@domo.com', url='https://github.com/domoinc/domo-python-sdk', download_url='https://github.com/domoinc/domo-python-sdk/tarball/0.2.2.1', keywords='domo api sdk', license='MIT', packages=find_packages(exclude=['examples']), install_requires=[ 'requests', 'requests_toolbelt', ], python_requires='>=3', )
Fix 2FA token selector, ensuring token is cleared after invalid token
$(function() { load($('form.login')); }); function load($f) { $f.submit(function() { $f.find('.submit').attr('disabled', true); $.ajax({ url: $f.attr('action'), method: $f.attr('method'), data: { username: $f.find('#form3-username').val(), password: $f.find('#form3-password').val(), token: $f.find('#form3-token').val() }, success: function(res) { if (res === 'MissingTotpToken' || res === 'InvalidTotpToken') { $f.find('.one-factor').hide(); $f.find('.two-factor').show(); $f.find('.two-factor input').val(''); $f.find('.submit').attr('disabled', false); if (res === 'InvalidTotpToken') $f.find('.two-factor .error').show(); } else lichess.redirect(res.indexOf('ok:') === 0 ? res.substr(3) : '/'); }, error: function(err) { $f.replaceWith($(err.responseText).find('form.login')); load($('form.login')); } }); return false; }); }
$(function() { load($('form.login')); }); function load($f) { $f.submit(function() { $f.find('.submit').attr('disabled', true); $.ajax({ url: $f.attr('action'), method: $f.attr('method'), data: { username: $f.find('#form3-username').val(), password: $f.find('#form3-password').val(), token: $f.find('#form3-token').val() }, success: function(res) { if (res === 'MissingTotpToken' || res === 'InvalidTotpToken') { $f.find('.one-factor').hide(); $f.find('.two-factor').show(); $f.find('.token input').val(''); $f.find('.submit').attr('disabled', false); if (res === 'InvalidTotpToken') $f.find('.two-factor .error').show(); } else lichess.redirect(res.indexOf('ok:') === 0 ? res.substr(3) : '/'); }, error: function(err) { $f.replaceWith($(err.responseText).find('form.login')); load($('form.login')); } }); return false; }); }
Add webtest as a dependency.
import os from setuptools import setup, find_packages long_description = ( open('README.rst').read() + '\n' + open('CHANGES.txt').read()) setup(name='more.static', version='0.1.dev0', description="BowerStatic integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath bowerstatic bower', license="BSD", url="http://pypi.python.org/pypi/more.static", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath', 'bowerstatic', ], extras_require = dict( test=['pytest >= 2.0', 'pytest-cov', 'WebTest >= 2.0.14'], ), )
import os from setuptools import setup, find_packages long_description = ( open('README.rst').read() + '\n' + open('CHANGES.txt').read()) setup(name='more.static', version='0.1.dev0', description="BowerStatic integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath bowerstatic bower', license="BSD", url="http://pypi.python.org/pypi/more.static", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath', 'bowerstatic', ], extras_require = dict( test=['pytest >= 2.0', 'pytest-cov'], ), )
Fix naming convention for protected method
<?php namespace Elastica\Test\Exception; use Elastica\Test\Base as BaseTest; abstract class AbstractExceptionTest extends BaseTest { protected function _getExceptionClass() { $reflection = new \ReflectionObject($this); // Elastica\Test\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeExceptionTest $name = preg_replace('/^Elastica\\\\Test/', 'Elastica', $reflection->getName()); // Elastica\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeException $name = preg_replace('/Test$/', '', $name); return $name; } public function testInheritance() { $className = $this->_getExceptionClass(); $reflection = new \ReflectionClass($className); $this->assertTrue($reflection->isSubclassOf('Exception')); $this->assertTrue($reflection->implementsInterface('Elastica\Exception\ExceptionInterface')); } }
<?php namespace Elastica\Test\Exception; use Elastica\Test\Base as BaseTest; abstract class AbstractExceptionTest extends BaseTest { protected function getExceptionClass() { $reflection = new \ReflectionObject($this); // Elastica\Test\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeExceptionTest $name = preg_replace('/^Elastica\\\\Test/', 'Elastica', $reflection->getName()); // Elastica\Exception\RuntimeExceptionTest => Elastica\Exception\RuntimeException $name = preg_replace('/Test$/', '', $name); return $name; } public function testInheritance() { $className = $this->getExceptionClass(); $reflection = new \ReflectionClass($className); $this->assertTrue($reflection->isSubclassOf('Exception')); $this->assertTrue($reflection->implementsInterface('Elastica\Exception\ExceptionInterface')); } }
Add caniuse keys to activation map
// Some features might affect others (eg: var() in a calc() // in order to prevent issue, the map contains a sort of dependencies list // // null == always enable (& no caniuse data) export default { customProperties: [ "css-variables" ], // calc() transformation only make sense with transformed custom properties, // don't you think ? // calc: null, // @todo open PR on caniuse repo https://github.com/Fyrd/caniuse // customMedia: [ null ], // mediaQueriesRange: [ null ], // customSelectors: [ null ], // colorRebeccapurple: [ null ], // @todo can be done easily // colorHwb: [ null ], // colorGray: [ null ], // colorHexAlpha: [ null ], // colorFunction:[ null], // fontVariant: [ null ], // @todo can be done using a callback, this is only used for Firefox < 35 // filter: [ null ], initial: [ "css-all", "css-initial-value" ], rem: [ "rem" ], pseudoElements: [ "css-gencontent" ], // pseudoClassMatches: [ null ], // pseudoClassNot: [ null ], colorRgba: [ "css3-colors" ], // will always be null since autoprefixer does the same game as we do // autoprefixer: [ null ] }
// Some features might affect others (eg: var() in a calc() // in order to prevent issue, the map contains a sort of dependencies list // // null == always enable (& no caniuse data) export default { customProperties: [ "css-variables" ], // calc() transformation only make sense with transformed custom properties, // don't you think ? // calc: null, // @todo open PR on caniuse repo https://github.com/Fyrd/caniuse // customMedia: [ null ], // mediaQueriesRange: [ null ], // customSelectors: [ null ], // colorRebeccapurple: [ null ], // @todo can be done easily // colorHwb: [ null ], // colorGray: [ null ], // colorHexAlpha: [ null ], // colorFunction:[ null], // fontVariant: [ null ], // @todo can be done using a callback, this is only used for Firefox < 35 // filter: [ null ], rem: [ "rem" ], pseudoElements: [ "css-gencontent" ], // pseudoClassMatches: [ null ], // pseudoClassNot: [ null ], colorRgba: [ "css3-colors" ], // will always be null since autoprefixer does the same game as we do // autoprefixer: [ null ] }
Switch logOut and TripCount buttons
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { hideTrip, showTrip } from 'lib/actions/trip'; import { logOut } from 'lib/actions/auth'; import TripCount from 'components/trip-count'; const HeaderLogo = () => <Link to="/"><img className="header-logo" src="/assets/logo-small.png" /></Link>; const HeaderSummary = ( props ) => { return ( <div className="header-summary"> <TripCount isShowingTrip={ props.isShowingTrip } hideTrip={ props.hideTrip } showTrip={ props.showTrip } trip={ props.trip } /> <HeaderLogo /> <button className="btn log-out-button" onClick={ props.logOut }>Log out</button> </div> ); }; HeaderSummary.propTypes = { isShowingTrip: React.PropTypes.bool, trip: React.PropTypes.array, hideTrip: React.PropTypes.func.isRequired, showTrip: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; const mapStateToProps = state => ( { isShowingTrip: state.ui.isShowingTrip, trip: state.trip } ); export default connect( mapStateToProps, { hideTrip, showTrip, logOut } )( HeaderSummary );
import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { hideTrip, showTrip } from 'lib/actions/trip'; import { logOut } from 'lib/actions/auth'; import TripCount from 'components/trip-count'; const HeaderLogo = () => <Link to="/"><img className="header-logo" src="/assets/logo-small.png" /></Link>; const HeaderSummary = ( props ) => { return ( <div className="header-summary"> <button className="btn log-out-button" onClick={ props.logOut }>Log out</button> <HeaderLogo /> <TripCount isShowingTrip={ props.isShowingTrip } hideTrip={ props.hideTrip } showTrip={ props.showTrip } trip={ props.trip } /> </div> ); }; HeaderSummary.propTypes = { isShowingTrip: React.PropTypes.bool, trip: React.PropTypes.array, hideTrip: React.PropTypes.func.isRequired, showTrip: React.PropTypes.func.isRequired, logOut: React.PropTypes.func.isRequired, }; const mapStateToProps = state => ( { isShowingTrip: state.ui.isShowingTrip, trip: state.trip } ); export default connect( mapStateToProps, { hideTrip, showTrip, logOut } )( HeaderSummary );
Fix no log in /var/log/kuryr/kuryr.log code misuse "Kuryr" in log.setup, it should be "kuryr". Change-Id: If36c9e03a01dae710ca12cf340abbb0c5647b47f Closes-bug: #1617863
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from oslo_log import log from six.moves.urllib import parse from kuryr_libnetwork import app from kuryr_libnetwork.common import config from kuryr_libnetwork import controllers def start(): config.init(sys.argv[1:]) log.setup(config.CONF, 'kuryr') controllers.neutron_client() controllers.check_for_neutron_ext_support() controllers.check_for_neutron_ext_tag() kuryr_uri = parse.urlparse(config.CONF.kuryr_uri) app.run(kuryr_uri.hostname, kuryr_uri.port) if __name__ == '__main__': start()
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys from oslo_log import log from six.moves.urllib import parse from kuryr_libnetwork import app from kuryr_libnetwork.common import config from kuryr_libnetwork import controllers def start(): config.init(sys.argv[1:]) controllers.neutron_client() controllers.check_for_neutron_ext_support() controllers.check_for_neutron_ext_tag() log.setup(config.CONF, 'Kuryr') kuryr_uri = parse.urlparse(config.CONF.kuryr_uri) app.run(kuryr_uri.hostname, kuryr_uri.port) if __name__ == '__main__': start()
Fix deprecation warning in Symfony 4.2 This addresses `Not implementing the static getExtendedTypes() method in Limenius\Liform\Form\Extension\AddLiformExtension when implementing the Symfony\Component\Form\FormTypeExtensionInterface is deprecated since Symfony 4.2. The method will be added to the interface in 5.0.`
<?php /* * This file is part of the Limenius\Liform package. * * (c) Limenius <https://github.com/Limenius/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Limenius\Liform\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\FormType; /** * Adds a 'liform' configuration option to instances of FormType * * @author Nacho Martín <nacho@limenius.com> */ class AddLiformExtension extends AbstractTypeExtension { /** * Returns the name of the type being extended. * * @return string */ public function getExtendedType() { return FormType::class; } /** * {@inheritdoc} */ public static function getExtendedTypes(): iterable { return [FormType::class]; } /** * Add the liform option * * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefined(['liform']); } }
<?php /* * This file is part of the Limenius\Liform package. * * (c) Limenius <https://github.com/Limenius/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Limenius\Liform\Form\Extension; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\FormType; /** * Adds a 'liform' configuration option to instances of FormType * * @author Nacho Martín <nacho@limenius.com> */ class AddLiformExtension extends AbstractTypeExtension { /** * Returns the name of the type being extended. * * @return string */ public function getExtendedType() { return FormType::class; } /** * Add the liform option * * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefined(['liform']); } }
Check if classes are derived from object This makes sure we don't regress to old style classes
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes for clsname in ["virConnect", "virDomain", "virDomainSnapshot", "virInterface", "virNWFilter", "virNodeDevice", "virNetwork", "virSecret", "virStoragePool", "virStorageVol", "virStream", ]: assert(clsname in globals) assert(object in getattr(libvirt, clsname).__bases__) # Constants assert("VIR_CONNECT_RO" in globals) # Error related bits assert("libvirtError" in globals) assert("VIR_ERR_AUTH_FAILED" in globals) assert("virGetLastError" in globals) # Some misc methods assert("virInitialize" in globals) assert("virEventAddHandle" in globals) assert("virEventRegisterDefaultImpl" in globals)
#!/usr/bin/python import libvirt globals = dir(libvirt) # Sanity test that the generator hasn't gone wrong # Look for core classes assert("virConnect" in globals) assert("virDomain" in globals) assert("virDomainSnapshot" in globals) assert("virInterface" in globals) assert("virNWFilter" in globals) assert("virNodeDevice" in globals) assert("virNetwork" in globals) assert("virSecret" in globals) assert("virStoragePool" in globals) assert("virStorageVol" in globals) assert("virStream" in globals) assert("VIR_CONNECT_RO" in globals) # Error related bits assert("libvirtError" in globals) assert("VIR_ERR_AUTH_FAILED" in globals) assert("virGetLastError" in globals) # Some misc methods assert("virInitialize" in globals) assert("virEventAddHandle" in globals) assert("virEventRegisterDefaultImpl" in globals)
Make sure the ticker stopped when ActiveObject.ForceStop() called
package ActiveObject import ( "errors" "time" ) //ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval type ActiveObjectWithInterval struct { workerFunction func(params ...interface{}) ticker *time.Ticker duration time.Duration doneChannel chan bool } func NewActiveObjectWithInterval(duration time.Duration) *ActiveObjectWithInterval { return &ActiveObjectWithInterval{duration: duration, doneChannel: make(chan bool)} } func (activeObject *ActiveObjectWithInterval) SetWorkerFunction(workerFunction func(params ...interface{})) { activeObject.workerFunction = workerFunction } func (activeObject *ActiveObjectWithInterval) Run(params ...interface{}) error { if activeObject.ticker != nil { return errors.New("Already running") } activeObject.ticker = time.NewTicker(activeObject.duration) go func() { for { select { case <-activeObject.ticker.C: activeObject.workerFunction(params) case <-activeObject.doneChannel: activeObject.ticker.Stop() return } } }() return nil } func (activeObject *ActiveObjectWithInterval) ForceStop() { activeObject.doneChannel <- true }
package ActiveObject import ( "errors" "time" ) //ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval type ActiveObjectWithInterval struct { workerFunction func(params ...interface{}) ticker *time.Ticker duration time.Duration doneChannel chan bool } func NewActiveObjectWithInterval(duration time.Duration) *ActiveObjectWithInterval { return &ActiveObjectWithInterval{duration: duration, doneChannel: make(chan bool)} } func (activeObject *ActiveObjectWithInterval) SetWorkerFunction(workerFunction func(params ...interface{})) { activeObject.workerFunction = workerFunction } func (activeObject *ActiveObjectWithInterval) Run(params ...interface{}) error { if activeObject.ticker != nil { return errors.New("Already running") } activeObject.ticker = time.NewTicker(activeObject.duration) go func() { for { select { case <-activeObject.ticker.C: activeObject.workerFunction(params) case <-activeObject.doneChannel: return } } }() return nil } func (activeObject *ActiveObjectWithInterval) ForceStop() { activeObject.doneChannel <- true }
Use app.apruve.com as the prod environment URL
package com.apruve; /** * @author Robert Nelson * @since 0.1 */ public enum ApruveEnvironment { PROD("https://app.apruve.com"), TEST("https://test.apruve.com"), DEV("http://localhost:3000"); private static final String API_V3_PATH = "/api/v3"; private static final String JS_PATH = "/js/apruve.js"; private String baseUrl; private ApruveEnvironment(String baseURL) { this.baseUrl = baseURL; } public String getBaseUrl() { return baseUrl; } /** * @return The root URL for making API calls in the environment */ public String getApiV3Url() { return getBaseUrl() + API_V3_PATH; } /** * @return The apruve.js URL for the environment */ public String getJsUrl() { return getBaseUrl() + JS_PATH; } /** * @return HTML tag that will include apruve.js in a page */ public String getJsTag() { return "<script src=\"" + getJsUrl() + "\" type=\"text/javascript\"></script>"; } }
package com.apruve; /** * @author Robert Nelson * @since 0.1 */ public enum ApruveEnvironment { PROD("https://www.apruve.com"), TEST("https://test.apruve.com"), DEV("http://localhost:3000"); private static final String API_V3_PATH = "/api/v3"; private static final String JS_PATH = "/js/apruve.js"; private String baseUrl; private ApruveEnvironment(String baseURL) { this.baseUrl = baseURL; } public String getBaseUrl() { return baseUrl; } /** * @return The root URL for making API calls in the environment */ public String getApiV3Url() { return getBaseUrl() + API_V3_PATH; } /** * @return The apruve.js URL for the environment */ public String getJsUrl() { return getBaseUrl() + JS_PATH; } /** * @return HTML tag that will include apruve.js in a page */ public String getJsTag() { return "<script src=\"" + getJsUrl() + "\" type=\"text/javascript\"></script>"; } }
Remove call to parent constructor in Controller
<?php namespace Devfactory\Variables\Controllers; use Config; use Input; use Lang; use Redirect; use URL; use View; use \Variables; use Illuminate\Routing\Controller as BaseController; class VariablesController extends BaseController { /** * Initializer. * * @return void */ public function __construct() { View::composer('variables::*', 'Devfactory\Variables\Composers\VariablesComposer'); } /** * Show a list of all the variables. * * @return View */ public function getIndex() { $variables = Variables::getAll(); $edit_url = URL::action(get_class($this) . '@postUpdate'); return View::make('variables::index', compact('variables', 'edit_url')); } /** * Update all the variables according to the value set in the form * * @return */ public function postUpdate() { $variables = Variables::getAll(); foreach ($variables as $key => $variable) { if (Input::get($key) != $variable['value']) { Variables::set($key, Input::get($key)); } } return Redirect::to(URL::action(get_class($this) . '@getIndex')); } }
<?php namespace Devfactory\Variables\Controllers; use Config; use Input; use Lang; use Redirect; use URL; use View; use \Variables; use Illuminate\Routing\Controller as BaseController; class VariablesController extends BaseController { /** * Initializer. * * @return void */ public function __construct() { parent::__construct(); View::composer('variables::*', 'Devfactory\Variables\Composers\VariablesComposer'); } /** * Show a list of all the variables. * * @return View */ public function getIndex() { $variables = Variables::getAll(); $edit_url = URL::action(get_class($this) . '@postUpdate'); return View::make('variables::index', compact('variables', 'edit_url')); } /** * Update all the variables according to the value set in the form * * @return */ public function postUpdate() { $variables = Variables::getAll(); foreach ($variables as $key => $variable) { if (Input::get($key) != $variable['value']) { Variables::set($key, Input::get($key)); } } return Redirect::to(URL::action(get_class($this) . '@getIndex')); } }
Fix content_type for JSON responses
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse, HttpResponseServerError from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr( settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append( FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return HttpResponseServerError((json.dumps(details))) return HttpResponse(json.dumps(details))
Add stubs for missing acceptance tests
var assert = require('assert'); var request = require('supertest'); var app = request(require('../../')); describe('GET /api/v1/cabin', function() { it('returns list of cabins', function(done) { app.get('/api/v1/cabin').expect(200, done); }); }); describe('POST /api/v1/cabin', function() { it('creates a new cabin'); it('sets privat.hyttetype'); it('maps tilkomst.privat to adkomst'); }); describe('GET /api/v1/cabin/:id', function() { this.timeout(5000); it('returns 404 for non-existing cabin', function(done) { app.get('/api/v1/cabin/000000000000000000000000').expect(404, done); }); it('returns data for existing cabin', function(done) { app.get('/api/v1/cabin/52407fb375049e5615000118') .expect(200) .expect(function(res) { assert.equal(res.body.navn, 'Selhamar'); }) .end(done); }); }); describe('POST /api/v1/cabin/:id', function() { it('updates an existing cabin'); }); describe('DELETE /api/v1/cabin/:id', function() { it('deletes an existing cabin'); });
var assert = require('assert'); var request = require('supertest'); var app = request(require('../../')); describe('GET /api/v1/cabin', function() { it('returns list of cabins', function(done) { app.get('/api/v1/cabin').expect(200, done); }); }); describe('POST /api/v1/cabin', function() { it('creates a new cabin'); }); describe('GET /api/v1/cabin/:id', function() { this.timeout(5000); it('returns 404 for non-existing cabin', function(done) { app.get('/api/v1/cabin/000000000000000000000000').expect(404, done); }); it('returns data for existing cabin', function(done) { app.get('/api/v1/cabin/52407fb375049e5615000118') .expect(200) .expect(function(res) { assert.equal(res.body.navn, 'Selhamar'); }) .end(done); }); }); describe('POST /api/v1/cabin/:id', function() { it('updates an existing cabin'); }); describe('DELETE /api/v1/cabin/:id', function() { it('deletes an existing cabin'); });
Use the new configure command.
from setuptools import setup, find_packages from codecs import open from os import path _HERE = path.abspath(path.dirname(__file__)) def read(*names, **kwds): return open( path.join(_HERE, *names), encoding=kwds.get('encoding', 'utf-8') ).read() def find_version(*file_paths): import re version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find vresion string.") setup( name='wmtexe', version=find_version("wmtexe/__init__.py"), description='WMT execution server.', long_description=read('README.md'), url='https://github.com/csdms/wmt-exe', author='Eric Hutton', author_email='hutton.eric@gmail.com', license='MIT', packages=find_packages(), entry_points={ 'console_scripts': [ 'wmt-slave=wmtexe.slave:main', ], 'distutils.commands': [ 'configure = wmtexe.configure:Configure', ], }, )
from setuptools import setup, find_packages from codecs import open from os import path _HERE = path.abspath(path.dirname(__file__)) def read(*names, **kwds): return open( path.join(_HERE, *names), encoding=kwds.get('encoding', 'utf-8') ).read() def find_version(*file_paths): import re version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find vresion string.") setup( name='wmtexe', version=find_version("wmtexe/__init__.py"), description='WMT execution server.', long_description=read('README.md'), url='https://github.com/csdms/wmt-exe', author='Eric Hutton', author_email='hutton.eric@gmail.com', license='MIT', packages=find_packages(), entry_points={ 'console_scripts': [ 'wmt-slave=wmtexe.slave:main', ], }, )
Add human friendly date in component
import React, { PropTypes } from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import styles from './Incident.css'; import Map from './Map'; import GridTile from 'material-ui/lib/grid-list/grid-tile'; import Paper from 'material-ui/lib/paper'; const moment = require('moment'); const Incident = ({ incident }) => ( <ReactCSSTransitionGroup transitionName={styles} transitionEnterTimeout={500} transitionLeaveTimeout={300} transitionAppear transitionAppearTimeout={500} > <div className={styles.incident}> <Paper zDepth={2}> <GridTile key={incident.id} title={incident.description} subtitle={incident.address} > <Map address={incident.address} /> </GridTile> <div className={styles.incidentInfo}> <p>{"id: " + incident.id}</p> <p>{"date: " + moment(incident.date).format('llll')}</p> <p>{"address: " + incident.address}</p> <p>{"description: " + incident.narrative}</p> </div> </Paper> </div> </ReactCSSTransitionGroup> ); Incident.propTypes = { incident: PropTypes.object.isRequired }; export default Incident;
import React, { PropTypes } from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import styles from './Incident.css'; import Map from './Map'; import GridTile from 'material-ui/lib/grid-list/grid-tile'; import Paper from 'material-ui/lib/paper'; const Incident = ({ incident }) => ( <ReactCSSTransitionGroup transitionName={styles} transitionEnterTimeout={500} transitionLeaveTimeout={300} transitionAppear transitionAppearTimeout={500} > <div className={styles.incident}> <Paper zDepth={2}> <GridTile key={incident.id} title={incident.description} subtitle={incident.address} > <Map address={incident.address} /> </GridTile> <div className={styles.incidentInfo}> <p>{"id: " + incident.id}</p> <p>{"date: " + incident.date}</p> <p>{"address: " + incident.address}</p> <p>{"description: " + incident.narrative}</p> </div> </Paper> </div> </ReactCSSTransitionGroup> ); Incident.propTypes = { incident: PropTypes.object.isRequired }; export default Incident;
Use const instead of let.
'use strict'; module.exports = function(app) { app.controller('GamesController', ['$route', '$scope', 'GameService', 'UserService', function($route, $scope, gameService, userService) { const ctrl = this; $scope.gameService = gameService; $scope.gamesData = gameService.data.allGames; ctrl.user = userService.data.user; ctrl.creating = false; ctrl.getGamesData = function() { gameService.getAllById(ctrl.user.gameIds) .catch((err) => { console.log('Error getting games.'); }); }; ctrl.reloadPage = function() { $route.reload(); } ctrl.init = function() { ctrl.getGamesData(); }; ctrl.init(); }]); };
'use strict'; module.exports = function(app) { app.controller('GamesController', ['$route', '$scope', 'GameService', 'UserService', function($route, $scope, gameService, userService) { let ctrl = this; $scope.gameService = gameService; $scope.gamesData = gameService.data.allGames; ctrl.user = userService.data.user; ctrl.creating = false; ctrl.getGamesData = function() { gameService.getAllById(ctrl.user.gameIds) .catch((err) => { console.log('Error getting games.'); }); }; ctrl.reloadPage = function() { $route.reload(); } ctrl.init = function() { ctrl.getGamesData(); }; ctrl.init(); }]); };
Define M+ font subset that contains only those characters necessary for the site.
/** * aws - deploys "earth" files to AWS S3 */ "use strict"; var util = require("util"); var tool = require("./tool"); var aws = require("./aws"); console.log("============================================================"); console.log(new Date().toISOString() + " - Starting"); // UNDONE: delete objects in S3 but not in the list below // UNDONE: super awesome logic that defines and iterates file sets, to eliminate this list: [ "about.html", "index.html", "natural-earth.png", "css/styles.css", "css/mplus-2p-light-057.ttf", "css/mplus-2p-light-sub-1.ttf", "data/earth-topo.json", "libs/d3.geo/0.0.0/d3.geo.polyhedron.v0.min.js", "libs/d3.geo/0.0.0/d3.geo.projection.v0.min.js", "libs/earth/1.0.0/earth.js", "libs/earth/1.0.0/globes.js", "libs/earth/1.0.0/layers.js", "libs/earth/1.0.0/micro.js", "libs/when/2.6.0/when.js" ].forEach(function(key) { aws.uploadFile("public/" + key, aws.S3_BUCKET, key).then(function(result) { console.log(key + ": " + util.inspect(result)); }, tool.report); });
/** * aws - deploys "earth" files to AWS S3 */ "use strict"; var util = require("util"); var tool = require("./tool"); var aws = require("./aws"); console.log("============================================================"); console.log(new Date().toISOString() + " - Starting"); // UNDONE: delete objects in S3 but not in the list below // UNDONE: super awesome logic that defines and iterates file sets, to eliminate this list: [ "about.html", "index.html", "natural-earth.png", "css/styles.css", "css/mplus-2p-light-057.ttf", "data/earth-topo.json", "libs/d3.geo/0.0.0/d3.geo.polyhedron.v0.min.js", "libs/d3.geo/0.0.0/d3.geo.projection.v0.min.js", "libs/earth/1.0.0/earth.js", "libs/earth/1.0.0/globes.js", "libs/earth/1.0.0/layers.js", "libs/earth/1.0.0/micro.js", "libs/when/2.6.0/when.js" ].forEach(function(key) { aws.uploadFile("public/" + key, aws.S3_BUCKET, key).then(function(result) { console.log(key + ": " + util.inspect(result)); }, tool.report); });
Add ContactInfo pane to create vendor pane OPEN - task 79: Create Party Module http://github.com/DevOpsDistilled/OpERP/issues/issue/79
package devopsdistilled.operp.client.party.panes.controllers.impl; import javax.inject.Inject; import javax.swing.JPanel; import devopsdistilled.operp.client.commons.panes.controllers.CreateContactInfoPaneController; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.client.party.panes.CreateVendorPane; import devopsdistilled.operp.client.party.panes.controllers.CreateVendorPaneController; import devopsdistilled.operp.client.party.panes.models.CreateVendorPaneModel; import devopsdistilled.operp.server.data.entity.party.Vendor; public class CreateVendorPaneControllerImpl implements CreateVendorPaneController { @Inject private CreateVendorPane view; @Inject private CreateVendorPaneModel model; @Inject private CreateContactInfoPaneController createContactInfoPaneController; @Override public void validate(Vendor entity) throws EntityValidationException { // TODO Auto-generated method stub } @Override public Vendor save(Vendor entity) { // TODO Auto-generated method stub return null; } @Override public void init() { createContactInfoPaneController.getView().setController( createContactInfoPaneController); view.setContactInfopanel((JPanel) createContactInfoPaneController .getView().getPane()); view.init(); model.registerObserver(view); } }
package devopsdistilled.operp.client.party.panes.controllers.impl; import javax.inject.Inject; import devopsdistilled.operp.client.exceptions.EntityValidationException; import devopsdistilled.operp.client.party.panes.CreateVendorPane; import devopsdistilled.operp.client.party.panes.controllers.CreateVendorPaneController; import devopsdistilled.operp.client.party.panes.models.CreateVendorPaneModel; import devopsdistilled.operp.server.data.entity.party.Vendor; public class CreateVendorPaneControllerImpl implements CreateVendorPaneController { @Inject private CreateVendorPane view; @Inject private CreateVendorPaneModel model; @Override public void validate(Vendor entity) throws EntityValidationException { // TODO Auto-generated method stub } @Override public Vendor save(Vendor entity) { // TODO Auto-generated method stub return null; } @Override public void init() { view.init(); model.registerObserver(view); } }
Fix bug introduce by typo rename static method
/** * Base class for shared model logic * @module lib/models/base * @exports BaseModel */ 'use strict' const Immutable = require('seamless-immutable') const exists = require('101/exists') const keypather = require('keypather')() const httpClient = require('../http-client') class BaseModel { /** * Invoke superclass constructor method to set up immutable instance */ constructor (data) { this.attrs = Immutable(data) Object.freeze(this.attrs) } /** * Return a value at a given keypath * @param {String} keyPath */ get (keyPath) { return keypather.get(this.attrs, keyPath) } /** * Centralized API resource request handling * @param {Object} queryOpts */ static instanceResourceRequest (queryOpts) { return httpClient(queryOpts) .then((response) => { if (!exists(response) || response.statusCode === 404) { throw new Error(queryOpts) } return (Array.isArray(response.body)) ? response.body[0] : response.body }) } } module.exports = BaseModel
/** * Base class for shared model logic * @module lib/models/base * @exports BaseModel */ 'use strict' const Immutable = require('seamless-immutable') const exists = require('101/exists') const keypather = require('keypather')() const httpClient = require('../http-client') class BaseModel { /** * Invoke superclass constructor method to set up immutable instance */ constructor (data) { this.attrs = Immutable(data) Object.freeze(this.attrs) } /** * Return a value at a given keypath * @param {String} keyPath */ get (keyPath) { return keypather.get(this.attrs, keyPath) } /** * Centralized API resource request handling * @param {Object} queryOpts */ static instanceSesourceRequest (queryOpts) { return httpClient(queryOpts) .then((response) => { if (!exists(response) || response.statusCode === 404) { throw new Error(queryOpts) } return (Array.isArray(response.body)) ? response.body[0] : response.body }) } } module.exports = BaseModel
Fix a bug about the function, 'val'.
# encoding: utf-8 import six ### Attribute Wrapper class AttrWrapper(object): attrs = [] def __setattr__(self, name, value): if name not in self.attrs: raise AttributeError("'%s' is not supported" % name) object.__setattr__(self, name, value) def __repr__(self): attrs = [] template = "%s=%s" for name in self.attrs: try: attrs.append(template % (name, getattr(self, name))) except AttributeError: pass return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs)) def val(obj, name, default=None): if isinstance(name, six.string_types) and hasattr(obj, name): return getattr(obj, name) try: return obj[name] except Exception: return default v = val
# encoding: utf-8 ### Attribute Wrapper class AttrWrapper(object): attrs = [] def __setattr__(self, name, value): if name not in self.attrs: raise AttributeError("'%s' is not supported" % name) object.__setattr__(self, name, value) def __repr__(self): attrs = [] template = "%s=%s" for name in self.attrs: try: attrs.append(template % (name, getattr(self, name))) except AttributeError: pass return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs)) def val(obj, name, default=None): if hasattr(obj, name): return obj.name elif name in obj: return obj[name] elif isinstance(obj, (list, tuple)) and isinstance(name, int): try: return obj[name] except Exception: return default else: return default v = val
Fix bug which cause ENOENT window.json
const low = require('lowdb') const FileSync = require('lowdb/adapters/FileSync') const fs = require('fs') export default function (userAppPath) { if (!fs.existsSync(userAppPath.split('window.json')[0])) { fs.mkdirSync(userAppPath.split('window.json')[0]) } const windowAdapter = new FileSync(userAppPath) const windowSettings = low(windowAdapter) windowSettings.defaults({ windowState: { height: 800, useContentSize: true, width: 600, show: false, minWidth: 300, x: undefined, y: undefined } }).write() return { getWindowState () { return windowSettings.get('windowState') .cloneDeep() .value() }, updateWindowState (updateProp) { return windowSettings.get('windowState') .assign(updateProp) .write() } } }
const low = require('lowdb') const FileSync = require('lowdb/adapters/FileSync') export default function (userAppPath) { const windowAdapter = new FileSync(userAppPath) const windowSettings = low(windowAdapter) windowSettings.defaults({ windowState: { height: 800, useContentSize: true, width: 400, show: false, minWidth: 300, x: undefined, y: undefined } }).write() return { getWindowState () { return windowSettings.get('windowState') .cloneDeep() .value() }, updateWindowState (updateProp) { return windowSettings.get('windowState') .assign(updateProp) .write() } } }
Add ControlCharError for process_control_chars function
# -*- coding: utf-8 -*- # # Copyright (c) 2010 Red Hat, Inc # # kitchen 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. # # kitchen 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 python-fedora; if not, see <http://www.gnu.org/licenses/> # # Authors: # Toshio Kuratomi <toshio@fedoraproject.org> # from kitchen import exceptions class XmlEncodeError(exceptions.KitchenException): '''Exception thrown by error conditions when encoding an xml string. ''' pass class ControlCharError(exceptions.KitchenException): '''Exception thrown when an ascii control character is encountered. ''' pass
# -*- coding: utf-8 -*- # # Copyright (c) 2010 Red Hat, Inc # # kitchen 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. # # kitchen 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 python-fedora; if not, see <http://www.gnu.org/licenses/> # # Authors: # Toshio Kuratomi <toshio@fedoraproject.org> # from kitchen import exceptions class XmlEncodeError(exceptions.KitchenException): '''Exception thrown by error conditions when encoding an xml string. ''' pass
Add execution path for internal update
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): composer('install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): composer('self-update') composer('update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code)) def composer(command): base_dir = os.getcwd() os.chdir(get_value('checker-dir')) php('bin/composer '+command) os.chdir(base_dir)
import os from app.configuration import get_value from app.helper import php def initialization(): checker_dir = get_value('checker-dir') if not os.path.isfile(checker_dir+'bin/composer'): download(checker_dir) if not os.path.isfile(checker_dir+'bin/phpcs'): php('bin/composer install') def download(checker_dir): php_bin = get_value('php') if not os.path.exists(checker_dir+'bin'): os.makedirs(checker_dir+'bin') print('>>> Download composer') os.system('curl -sS https://getcomposer.org/installer | '+php_bin+' -- --install-dir='+checker_dir+'bin --filename=composer') def update(): php('bin/composer self-update') php('bin/composer update') def project_installation(): code = php('bin/composer install --optimize-autoloader') if code != 0: raise SystemExit('The composer install command for the project failed with the code '+str(code))
Remove lingering but unneeded requirement call
'use strict'; var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
'use strict'; var stringToNum = require( '../utils/handle-string-input' ); var getSchoolValues = { var values = {}; init: function( ) { values.programLength = this.getProgramLength(); values.gradRate = this.getGradRate(); values.medianDebt = this.getMedianDebt(); values.defaultRate = this.getDefaultRate(); values.medianSalary = this.getMedianSalary(); return values; }, getProgramLength: function() { // Rounds up to the nearest number of years. // Might need to change later, to address 18 month or 30 month programs. return Math.ceil(window.programData.programLength / 12) || ''; }, getGradRate: function() { if ( window.programData.completionRate == 'None' ) { return window.schoolData.gradRate; } else { return window.programData.completionRate || window.schoolData.gradRate; } }, getMedianDebt: function() { return window.programData.medianStudentLoanCompleters || window.schoolData.medianMonthlyDebt; }, getDefaultRate: function() { return (window.programData.defaultRate / 100) || window.schoolData.defaultRate; }, getMedianSalary: function() { return window.programData.salary || window.schoolData.medianAnnualPay; } }; module.exports = getSchoolValues;
Handle playback changes in FrontPanel
from __future__ import unicode_literals import logging from mopidy.core import CoreListener import pykka import .menu import BrowseMenu import .painter import Painter logger = logging.getLogger(__name__) class FrontPanel(pykka.ThreadingActor, CoreListener): def __init__(self, config, core): super(FrontPanel, self).__init__() self.core = core self.painter = Painter(core, self) self.menu = BrowseMenu(core) def on_start(self): self.painter.start() def handleInput(self, input): if (input == "play"): pass elif (input == "pause"): pass elif (input == "stop"): pass elif (input == "vol_up"): pass elif (input == "vol_down"): pass else: self.menu.handleInput(input) self.painter.update() def track_playback_started(self, tl_track): self.painter.update() def track_playback_ended(self, tl_track, time_position): self.painter.update()
from __future__ import unicode_literals import logging from mopidy.core import CoreListener import pykka import .menu import BrowseMenu import .painter import Painter logger = logging.getLogger(__name__) class FrontPanel(pykka.ThreadingActor, CoreListener): def __init__(self, config, core): super(FrontPanel, self).__init__() self.core = core self.painter = Painter(core, self) self.menu = BrowseMenu(core) def on_start(self): self.painter.start() def handleInput(self, input): self.menu.handleInput(input) self.painter.update() def track_playback_started(self, tl_track): self.painter.update() def track_playback_ended(self, tl_track, time_position): self.painter.update()
Use toString when printing proxy description
import _ from '../wrap/lodash' import isMatcher from '../matchers/is-matcher' import * as stringifyObject from 'stringify-object-es5' export default (anything) => { if (_.isString(anything)) { return stringifyString(anything) } else if (isMatcher(anything)) { return anything.__name } else if (anything && anything[Symbol("__is_proxy")]) { return anything.toString() } else { return stringifyObject(anything, { indent: ' ', singleQuotes: false, inlineCharacterLimit: 65, transform (obj, prop, originalResult) { if (isMatcher(obj[prop])) { return obj[prop].__name } else { return originalResult } } }) } } var stringifyString = (string) => _.includes(string, '\n') ? `"""\n${string}\n"""` : `"${string.replace(new RegExp('"', 'g'), '\\"')}"`
import _ from '../wrap/lodash' import isMatcher from '../matchers/is-matcher' import * as stringifyObject from 'stringify-object-es5' export default (anything) => { if (_.isString(anything)) { return stringifyString(anything) } else if (isMatcher(anything)) { return anything.__name } else { return stringifyObject(anything, { indent: ' ', singleQuotes: false, inlineCharacterLimit: 65, transform (obj, prop, originalResult) { if (isMatcher(obj[prop])) { return obj[prop].__name } else { return originalResult } } }) } } var stringifyString = (string) => _.includes(string, '\n') ? `"""\n${string}\n"""` : `"${string.replace(new RegExp('"', 'g'), '\\"')}"`
Allow for running with bin/index by stubbing sailsPackageJSON
/** * * @param {[type]} scope [description] * @return {[type]} [description] */ module.exports = function dataForPackageJSON (scope) { scope.sailsPackageJSON = { version: '?.?.?', dependencies: {} }; // Override sails version temporarily var sailsVersionDependency = '~' + scope.sailsPackageJSON.version; sailsVersionDependency = 'git://github.com/balderdashy/sails.git#v0.10'; return { name: scope.appName, 'private': true, version: '0.0.0', description: 'a Sails application', dependencies: { 'sails' : sailsVersionDependency, 'sails-disk' : scope.sailsPackageJSON.dependencies['sails-disk'], 'ejs' : scope.sailsPackageJSON.dependencies['ejs'], 'grunt' : scope.sailsPackageJSON.dependencies['grunt'] }, scripts: { // TODO: Include this later when we have "sails test" ready. // test: './node_modules/mocha/bin/mocha -b', start: 'node app.js', debug: 'node debug app.js' }, main: 'app.js', repository: '', author: scope.author, license: '' }; };
/** * * @param {[type]} scope [description] * @return {[type]} [description] */ module.exports = function dataForPackageJSON (scope) { var sails = scope.sails; // Override sails version temporarily var sailsVersionDependency = '~' + scope.sailsPackageJSON.version; sailsVersionDependency = 'git://github.com/balderdashy/sails.git#v0.10'; return { name: scope.appName, 'private': true, version: '0.0.0', description: 'a Sails application', dependencies: { 'sails' : sailsVersionDependency, 'sails-disk' : scope.sailsPackageJSON.dependencies['sails-disk'], 'ejs' : scope.sailsPackageJSON.dependencies['ejs'], 'grunt' : scope.sailsPackageJSON.dependencies['grunt'] }, scripts: { // TODO: Include this later when we have "sails test" ready. // test: './node_modules/mocha/bin/mocha -b', start: 'node app.js', debug: 'node debug app.js' }, main: 'app.js', repository: '', author: scope.author, license: '' }; };
Allow more types, as the helper allows more
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Model; /** * Trait for doctrine models that use a sortable handler */ trait SortableModelTrait { /** * Applies the sort order mapping as provided in the parameters. * * The model should wrap this method and use type hints on the $where parameter entries. * * @param array|mixed $sortMapping * @param array $where * * @return bool */ protected function flushSortOrderMapping ($sortMapping, array $where) : bool { if ($this->sortableHandler->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; } }
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Model; /** * Trait for doctrine models that use a sortable handler */ trait SortableModelTrait { /** * Applies the sort order mapping as provided in the parameters. * * The model should wrap this method and use type hints on the $where parameter entries. * * @param array $sortMapping * @param array $where * * @return bool */ protected function flushSortOrderMapping (array $sortMapping, array $where) : bool { if ($this->sortableHandler->applySorting($sortMapping, $where)) { $this->flush(); return true; } return false; } }
Fix library not found on linux
from __future__ import absolute_import import os import sys from .wrapper import _libgdf_wrapper from .wrapper import GDFError # re-exported try: from .libgdf_cffi import ffi except ImportError: pass else: def _get_lib_name(): if os.name == 'posix': # TODO this will need to be changed when packaged for distribution if sys.platform == 'darwin': path = 'libgdf.dylib' else: path = 'libgdf.so' else: raise NotImplementedError('OS {} not supported'.format(os.name)) # Prefer local version of the library if it exists localpath = os.path.join('.', path) if os.path.isfile(localpath): return localpath else: return path libgdf_api = ffi.dlopen(_get_lib_name()) libgdf = _libgdf_wrapper(ffi, libgdf_api) del _libgdf_wrapper
from __future__ import absolute_import import os, sys from .wrapper import _libgdf_wrapper from .wrapper import GDFError # re-exported try: from .libgdf_cffi import ffi except ImportError: pass else: def _get_lib_name(): if os.name == 'posix': # TODO this will need to be changed when packaged for distribution if sys.platform == 'darwin': return './libgdf.dylib' else: return './libgdf.so' raise NotImplementedError('OS {} not supported'.format(os.name)) libgdf_api = ffi.dlopen(_get_lib_name()) libgdf = _libgdf_wrapper(ffi, libgdf_api) del _libgdf_wrapper
Update currency directive to render 0's
/** * Created by rerobins on 10/6/15. */ var CurrencyDirectiveGenerator = function(formatters) { return { scope: { value: '&' }, template: '<span ng-style="style">{{currencyValue}}</span>', link: function($scope) { $scope.currencyValue = formatters.currency($scope.value()); if ($scope.value() > 0.0) { $scope.style = {color: 'green'}; } else if ($scope.value() < 0.0) { $scope.style = {color: 'red'}; } } }; }; angular.module('gnucash-reports-view.reports.base') .directive('currencyFormat', ['formatters', CurrencyDirectiveGenerator]);
/** * Created by rerobins on 10/6/15. */ var CurrencyDirectiveGenerator = function(formatters) { return { scope: { value: '&' }, template: '<span ng-style="style">{{currencyValue}}</span>', link: function($scope) { if ($scope.value() > 0.0) { $scope.style = {color: 'green'}; $scope.currencyValue = formatters.currency($scope.value()); } else if ($scope.value() < 0.0) { $scope.style = {color: 'red'}; $scope.currencyValue = formatters.currency($scope.value()); } } }; }; angular.module('gnucash-reports-view.reports.base') .directive('currencyFormat', ['formatters', CurrencyDirectiveGenerator]);
[CB-595] Check that Cordova global exists (for now, until we axe it)
describe('Platform (cordova)', function () { it("should exist", function() { expect(cordova).toBeDefined(); }); describe('Platform (Cordova)', function () { it("should exist", function() { expect(window.Cordova).toBeDefined(); }); }); describe('Platform (PhoneGap)', function () { it("should exist", function() { expect(PhoneGap).toBeDefined(); }); it("exec method should exist", function() { expect(PhoneGap.exec).toBeDefined(); expect(typeof PhoneGap.exec).toBe('function'); }); it("addPlugin method should exist", function() { expect(PhoneGap.addPlugin).toBeDefined(); expect(typeof PhoneGap.addPlugin).toBe('function'); }); it("addConstructor method should exist", function() { expect(PhoneGap.addConstructor).toBeDefined(); expect(typeof PhoneGap.addConstructor).toBe('function'); }); }); describe('Platform (window.plugins)', function () { it("should exist", function() { expect(window.plugins).toBeDefined(); }); }); });
describe('Platform (cordova)', function () { it("should exist", function() { expect(cordova).toBeDefined(); }); describe('Platform (Cordova)', function () { it("should not exist", function() { expect(window.Cordova).not.toBeDefined(); }); }); describe('Platform (PhoneGap)', function () { it("should exist", function() { expect(PhoneGap).toBeDefined(); }); it("exec method should exist", function() { expect(PhoneGap.exec).toBeDefined(); expect(typeof PhoneGap.exec).toBe('function'); }); it("addPlugin method should exist", function() { expect(PhoneGap.addPlugin).toBeDefined(); expect(typeof PhoneGap.addPlugin).toBe('function'); }); it("addConstructor method should exist", function() { expect(PhoneGap.addConstructor).toBeDefined(); expect(typeof PhoneGap.addConstructor).toBe('function'); }); }); describe('Platform (window.plugins)', function () { it("should exist", function() { expect(window.plugins).toBeDefined(); }); }); });
Exclude generated files from testing
module.exports = { transform: { "^.+\\.tsx?$": "ts-jest", }, testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", moduleFileExtensions: [ "ts", "tsx", "js", "jsx", "json", "node" ], moduleNameMapper: { "\\.(png|css)$": "<rootDir>/__mocks__/fileMock.js", }, setupFiles: ["./test/jestsetup.ts"], snapshotSerializers: ["enzyme-to-json/serializer"], coverageThreshold: { global: { statements: -91, branches: -65, lines: -86, functions: -34, } }, collectCoverage: true, collectCoverageFrom: [ "src/**", "!src/**/*.min.js", "!**/__tests__/**", "!**/*.d.ts", "!src/main.ts", "!src/peg/**" ], testURL: "http://localhost" };
module.exports = { transform: { "^.+\\.tsx?$": "ts-jest", }, testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", moduleFileExtensions: [ "ts", "tsx", "js", "jsx", "json", "node" ], moduleNameMapper: { "\\.(png|css)$": "<rootDir>/__mocks__/fileMock.js", }, setupFiles: ["./test/jestsetup.ts"], snapshotSerializers: ["enzyme-to-json/serializer"], coverageThreshold: { global: { statements: -91, branches: -65, lines: -86, functions: -34, } }, collectCoverage: true, collectCoverageFrom: [ "src/**", "!**/__tests__/**", "!**/*.d.ts", "!src/main.ts", "!src/peg/**" ], testURL: "http://localhost" };
Modify shops for dynamic columns Refs SH-64
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ from shuup.admin.toolbar import Toolbar from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter from shuup.admin.utils.views import PicotableListView from shuup.core.models import Shop, ShopStatus class ShopListView(PicotableListView): model = Shop default_columns = [ Column("name", _(u"Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("domain", _(u"Domain")), Column("identifier", _(u"Identifier")), Column("status", _(u"Status"), filter_config=ChoicesFilter(choices=ShopStatus.choices)), ] def get_toolbar(self): if settings.SHUUP_ENABLE_MULTIPLE_SHOPS: return super(ShopListView, self).get_toolbar() else: return Toolbar([])
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.conf import settings from django.utils.translation import ugettext_lazy as _ from shuup.admin.toolbar import Toolbar from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter from shuup.admin.utils.views import PicotableListView from shuup.core.models import Shop, ShopStatus class ShopListView(PicotableListView): model = Shop columns = [ Column("name", _(u"Name"), sort_field="translations__name", display="name", filter_config=TextFilter( filter_field="translations__name", placeholder=_("Filter by name...") )), Column("domain", _(u"Domain")), Column("identifier", _(u"Identifier")), Column("status", _(u"Status"), filter_config=ChoicesFilter(choices=ShopStatus.choices)), ] def get_toolbar(self): if settings.SHUUP_ENABLE_MULTIPLE_SHOPS: return super(ShopListView, self).get_toolbar() else: return Toolbar([])
Add 2011 to the year range in the about dialog
''' File : AboutDialog.py Author : Nadav Samet Contact : thesamet@gmail.com Date : 2010 Jun 17 Description : Controller for the about dialog. ''' from webilder import __version__ import gtk import pkg_resources def show_about_dialog(name): """Shows the about dialog.""" about = gtk.AboutDialog() about.set_name(name) about.set_version(__version__) about.set_copyright('Nadav Samet, 2005-2011') about.set_website('http://www.webilder.org') about.set_authors(['Nadav Samet <thesamet@gmail.com>']) about.set_translator_credits( 'French by Nicolas ELIE <chrystalyst@free.fr>\n' 'Alessio Leonarduzzi <alessio.leonarduzzi@gmail.com>') icon = gtk.gdk.pixbuf_new_from_file( pkg_resources.resource_filename(__name__, 'ui/camera48.png')) about.set_logo(icon), about.set_icon(icon), about.run() about.destroy()
''' File : AboutDialog.py Author : Nadav Samet Contact : thesamet@gmail.com Date : 2010 Jun 17 Description : Controller for the about dialog. ''' from webilder import __version__ import gtk import pkg_resources def show_about_dialog(name): """Shows the about dialog.""" about = gtk.AboutDialog() about.set_name(name) about.set_version(__version__) about.set_copyright('Nadav Samet, 2005-2010') about.set_website('http://www.webilder.org') about.set_authors(['Nadav Samet <thesamet@gmail.com>']) about.set_translator_credits( 'French by Nicolas ELIE <chrystalyst@free.fr>\n' 'Alessio Leonarduzzi <alessio.leonarduzzi@gmail.com>') icon = gtk.gdk.pixbuf_new_from_file( pkg_resources.resource_filename(__name__, 'ui/camera48.png')) about.set_logo(icon), about.set_icon(icon), about.run() about.destroy()
Add jsonsempai.tests to list of packages to install Closes: #10
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as file_readme: readme = file_readme.read() setup(name='json-sempai', version='0.3.0', description='Use JSON files as if they\'re python modules', long_description=readme, author='Louis Taylor', author_email='kragniz@gmail.com', license='MIT', url='https://github.com/kragniz/json-sempai', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='please don\'t use this library for anything', packages=['jsonsempai', 'jsonsempai.tests'], test_suite='jsonsempai.tests' )
#!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as file_readme: readme = file_readme.read() setup(name='json-sempai', version='0.3.0', description='Use JSON files as if they\'re python modules', long_description=readme, author='Louis Taylor', author_email='kragniz@gmail.com', license='MIT', url='https://github.com/kragniz/json-sempai', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', ], keywords='please don\'t use this library for anything', packages=['jsonsempai'], test_suite='jsonsempai.tests' )
Remove public network from openstack jumpbox deployment. [#155017559]
package bosh const GCPBoshDirectorEphemeralIPOps = ` - type: replace path: /networks/name=default/subnets/0/cloud_properties/ephemeral_external_ip? value: true ` const AWSBoshDirectorEphemeralIPOps = ` - type: replace path: /resource_pools/name=vms/cloud_properties/auto_assign_public_ip? value: true ` const AWSEncryptDiskOps = `--- - type: replace path: /disk_pools/name=disks/cloud_properties? value: type: gp2 encrypted: true kms_key_arn: ((kms_key_arn)) ` const VSphereJumpboxNetworkOps = `--- - type: remove path: /instance_groups/name=jumpbox/networks/name=public ` const OpenStackJumpboxKeystoneV3Ops = `--- - type: remove path: /instance_groups/name=jumpbox/networks/name=public - type: remove path: /networks/name=public - type: remove path: /cloud_provider/properties/openstack/tenant - type: replace path: /cloud_provider/properties/openstack/project? value: ((openstack_project)) - type: replace path: /cloud_provider/properties/openstack/domain? value: ((openstack_domain)) - type: replace path: /cloud_provider/properties/openstack/human_readable_vm_names? value: true `
package bosh const GCPBoshDirectorEphemeralIPOps = ` - type: replace path: /networks/name=default/subnets/0/cloud_properties/ephemeral_external_ip? value: true ` const AWSBoshDirectorEphemeralIPOps = ` - type: replace path: /resource_pools/name=vms/cloud_properties/auto_assign_public_ip? value: true ` const AWSEncryptDiskOps = `--- - type: replace path: /disk_pools/name=disks/cloud_properties? value: type: gp2 encrypted: true kms_key_arn: ((kms_key_arn)) ` const VSphereJumpboxNetworkOps = `--- - type: remove path: /instance_groups/name=jumpbox/networks/name=public ` const OpenStackJumpboxKeystoneV3Ops = `--- - type: remove path: /cloud_provider/properties/openstack/tenant - type: replace path: /cloud_provider/properties/openstack/project? value: ((openstack_project)) - type: replace path: /cloud_provider/properties/openstack/domain? value: ((openstack_domain)) - type: replace path: /cloud_provider/properties/openstack/human_readable_vm_names? value: true `
Update PSR-2 and remove unused use
<?php namespace Concrete\Core\Form\Service\Widget; use View; class Typography { /** * Creates form fields and JavaScript includes to add a font picker widget. * <code> * $dh->output('background-color', '#f00'); * </code> * @param string $inputName * @param array $value * @param array $options */ public function output($inputName, $value = array(), $options = array()) { $view = View::getInstance(); $view->requireAsset('core/style-customizer'); $options['inputName'] = $inputName; $options = array_merge($options, $value); $strOptions = json_encode($options); print '<span class="ccm-style-customizer-display-swatch-wrapper" data-font-selector="' . $inputName . '"></span>'; print "<script type=\"text/javascript\">"; print "$(function () { $('span[data-font-selector={$inputName}]').concreteTypographySelector({$strOptions}); })"; print "</script>"; } }
<?php namespace Concrete\Core\Form\Service\Widget; use Loader; use View; use Request; class Typography { /** * Creates form fields and JavaScript includes to add a font picker widget. * <code> * $dh->output('background-color', '#f00'); * </code> * @param string $inputName * @param array $value * @param array $options */ public function output($inputName, $value = array(), $options = array()) { $view = View::getInstance(); $view->requireAsset('core/style-customizer'); $options['inputName'] = $inputName; $options = array_merge($options, $value); $strOptions = json_encode($options); print '<span class="ccm-style-customizer-display-swatch-wrapper" data-font-selector="' . $inputName . '"></span>'; print "<script type=\"text/javascript\">"; print "$(function() { $('span[data-font-selector={$inputName}]').concreteTypographySelector({$strOptions}); })"; print "</script>"; } }
Add keywords and bump to 0.2.9
from setuptools import setup VERSION = '0.2.9' setup( name='jinja2_standalone_compiler', packages=['jinja2_standalone_compiler', ], version=VERSION, author='Filipe Waitman', author_email='filwaitman@gmail.com', install_requires=[x.strip() for x in open('requirements.txt').readlines()], url='https://github.com/filwaitman/jinja2-standalone-compiler', download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION), test_suite='tests', keywords=['Jinja2', 'Jinja', 'renderer', 'compiler', 'HTML'], classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Operating System :: OS Independent", ], entry_points="""\ [console_scripts] jinja2_standalone_compiler = jinja2_standalone_compiler:main_command """, )
from setuptools import setup VERSION = '0.2.8' setup( name='jinja2_standalone_compiler', packages=['jinja2_standalone_compiler', ], version=VERSION, author='Filipe Waitman', author_email='filwaitman@gmail.com', install_requires=[x.strip() for x in open('requirements.txt').readlines()], url='https://github.com/filwaitman/jinja2-standalone-compiler', download_url='https://github.com/filwaitman/jinja2-standalone-compiler/tarball/{}'.format(VERSION), test_suite='tests', classifiers=[ "Development Status :: 1 - Planning", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Operating System :: OS Independent", ], entry_points="""\ [console_scripts] jinja2_standalone_compiler = jinja2_standalone_compiler:main_command """, )
Allow arbitrary resources after ontology
from django.conf.urls import url from django.conf.urls.static import static from django.views.generic import TemplateView, RedirectView from os import walk from ontology import views from oeplatform import settings urlpatterns = [ url(r"^$", TemplateView.as_view(template_name="ontology/about.html")), url(r"^ontology/oeo-steering-committee$", TemplateView.as_view(template_name="ontology/oeo-steering-committee.html"), name="oeo-s-c"), url(r"^oeo", views.OntologyOverview.as_view(), name="oeo"), url(r"^releases\/(?P<ontology>[\w_-]+)(\/(?P<version>[\d\.]+))?\/(?P<file>[\w_-]+)(.(?P<extension>[\w_-]+))?$", views.OntologyStatics.as_view()), ]
from django.conf.urls import url from django.conf.urls.static import static from django.views.generic import TemplateView, RedirectView from os import walk from ontology import views from oeplatform import settings urlpatterns = [ url(r"^$", TemplateView.as_view(template_name="ontology/about.html")), url(r"^ontology/oeo-steering-committee$", TemplateView.as_view(template_name="ontology/oeo-steering-committee.html"), name="oeo-s-c"), url(r"^oeo$", views.OntologyOverview.as_view(), name="oeo"), url(r"^releases\/(?P<ontology>[\w_-]+)(\/(?P<version>[\d\.]+))?\/(?P<file>[\w_-]+)(.(?P<extension>[\w_-]+))?$", views.OntologyStatics.as_view()), ]
Add post json request method
var request = require('request') var constants = require('../custom_modules/constants') var headers = require('../custom_modules/headers') var cookie_jar = request.jar() var request = request.defaults({jar: cookie_jar, strictSSL: false}) var Requester = function(){ } Requester.prototype.postRequest = function(endpoint, data, callback){ request({ method: 'POST', url: endpoint, form: data, headers: headers.getHeaders(), json: true }, callback) } Requester.prototype.postJsonRequest = function(endpoint, data, callback){ request({ method: 'POST', url: endpoint, body: data, headers: headers.getHeaders(), json: true }, callback) } Requester.prototype.getRequest = function(endpoint, callback){ request({ method: 'GET', url: endpoint, headers: headers.getHeaders(), json: true }, callback) } module.exports = Requester
var request = require('request') var constants = require('../custom_modules/constants') var headers = require('../custom_modules/headers') var cookie_jar = request.jar() var request = request.defaults({jar: cookie_jar, strictSSL: false}) var Requester = function(){ } Requester.prototype.postRequest = function(endpoint, data, callback){ request({ method: 'POST', url: endpoint, form: data, headers: headers.getHeaders(), json: true }, callback) } Requester.prototype.getRequest = function(endpoint, callback){ request({ method: 'GET', url: endpoint, headers: headers.getHeaders(), json: true }, callback) } module.exports = Requester
Fix error caused by wrong reference of Container
<?php namespace App\Action; use Interop\Container\ContainerInterface; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; class BaseAction { protected $ci; protected $csrf; protected $db; protected $flash; protected $helper; protected $logger; protected $router; protected $view; public function __construct(ContainerInterface $ci) { $this->ci = $ci; $this->csrf = $ci->get('csrf'); $this->db = $ci->get('db'); $this->flash = $ci->get('flash'); $this->helper = $ci->get('helper'); $this->logger = $ci->get('logger'); $this->router = $ci->get('router'); $this->view = $ci->get('view'); } }
<?php namespace App\Action; use Interop\Container\ContainerInterface; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface as Response; class BaseAction { protected $ci; protected $csrf; protected $db; protected $flash; protected $helper; protected $logger; protected $router; protected $view; public function __construct(ContainerInterface $ci) { $this->ci = $ci->get('ci'); $this->csrf = $ci->get('csrf'); $this->db = $ci->get('db'); $this->flash = $ci->get('flash'); $this->helper = $ci->get('helper'); $this->logger = $ci->get('logger'); $this->router = $ci->get('router'); $this->view = $ci->get('view'); } }
Order backups by date descending
<?php /** * @package BaseX * * @copyright Copyright (c) 2012, Alexandors Sigalas * @author Alexandros Sigalas <alxarch@gmail.com> * @license BSD License */ namespace BaseX\Database; use BaseX\Query\Result\MapperInterface; use BaseX\Query; use BaseX\Database; /** * Maps query result data to Backup class. * * @author alxarch */ class BackupProvider implements MapperInterface { /** * * @var \BaseX\Database */ protected $db; public function __construct(Database $db) { $this->db = $db; } public function supportsType($type) { return $type === Query::TYPE_ELEMENT; } public function getResult($data, $type) { $backup = new Backup(); $backup->unserialize($data); return $backup; } /** * @todo implement date filters. */ public function get() { $xql = "for \$d in db:backups('$this->db') order by \$d descending return \$d"; return $this->db->getSession()->query($xql)->getResults($this); } }
<?php /** * @package BaseX * * @copyright Copyright (c) 2012, Alexandors Sigalas * @author Alexandros Sigalas <alxarch@gmail.com> * @license BSD License */ namespace BaseX\Database; use BaseX\Query\Result\MapperInterface; use BaseX\Query; use BaseX\Database; /** * Maps query result data to Backup class. * * @author alxarch */ class BackupProvider implements MapperInterface { /** * * @var \BaseX\Database */ protected $db; public function __construct(Database $db) { $this->db = $db; } public function supportsType($type) { return $type === Query::TYPE_ELEMENT; } public function getResult($data, $type) { $backup = new Backup(); $backup->unserialize($data); return $backup; } /** * @todo implement date filters. */ public function get() { $xql = "db:backups('$this->db')"; return $this->db->getSession()->query($xql)->getResults($this); } }
Make Sublime plugin work with new Fuse install location We changed the location of fuse from /usr/bin to /usr/local/bin to be compatible with El Capitan. The latter is not on path in Sublime, so use absolute paths for fuse.
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: if os.path.isfile("/usr/bin/fuse"): return "/usr/bin/fuse" else: return "/usr/local/bin/fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): base = os.path.basename(path) return os.path.splitext(base)[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
import sublime import os def getSetting(key,default=None): s = sublime.load_settings("Fuse.sublime-settings") return s.get(key, default) def getFusePathFromSettings(): path = getSetting("fuse_path_override") if path == "" or path == None: return "fuse" else: return path+"/fuse" def setSetting(key,value): s = sublime.load_settings("Fuse.sublime-settings") s.set(key, value) sublime.save_settings("Fuse.sublime-settings") def isSupportedSyntax(syntaxName): return syntaxName == "Uno" or syntaxName == "UX" def getExtension(path): base = os.path.basename(path) return os.path.splitext(base)[0] def getRowCol(view, pos): rowcol = view.rowcol(pos) rowcol = (rowcol[0] + 1, rowcol[1] + 1) return {"Line": rowcol[0], "Character": rowcol[1]}
Make rpc pubsub example stable
import asyncio import aiozmq.rpc from itertools import count class Handler(aiozmq.rpc.AttrHandler): def __init__(self): self.connected = False @aiozmq.rpc.method def remote_func(self, step, a: int, b: int): self.connected = True print("HANDLER", step, a, b) @asyncio.coroutine def go(): handler = Handler() subscriber = yield from aiozmq.rpc.serve_pubsub( handler, subscribe='topic', bind='tcp://127.0.0.1:*', log_exceptions=True) subscriber_addr = next(iter(subscriber.transport.bindings())) print("SERVE", subscriber_addr) publisher = yield from aiozmq.rpc.connect_pubsub( connect=subscriber_addr) for step in count(0): yield from publisher.publish('topic').remote_func(step, 1, 2) if handler.connected: break else: yield from asyncio.sleep(0.1) subscriber.close() yield from subscriber.wait_closed() publisher.close() yield from publisher.wait_closed() def main(): asyncio.get_event_loop().run_until_complete(go()) print("DONE") if __name__ == '__main__': main()
import asyncio import aiozmq.rpc class Handler(aiozmq.rpc.AttrHandler): @aiozmq.rpc.method def remote_func(self, a: int, b: int): pass @asyncio.coroutine def go(): subscriber = yield from aiozmq.rpc.serve_pubsub( Handler(), subscribe='topic', bind='tcp://*:*') subscriber_addr = next(iter(subscriber.transport.bindings())) publisher = yield from aiozmq.rpc.connect_pubsub( connect=subscriber_addr) yield from publisher.publish('topic').remote_func(1, 2) subscriber.close() publisher.close() def main(): asyncio.get_event_loop().run_until_complete(go()) print("DONE") if __name__ == '__main__': main()
Set booked_by for cloned/additional showings
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'roles')
from django import forms import cube.diary.models class DiaryIdeaForm(forms.ModelForm): class Meta(object): model = cube.diary.models.DiaryIdea class EventForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Event # Ensure soft wrapping is set for textareas: widgets = { 'copy': forms.Textarea(attrs={'wrap':'soft'}), 'copy_summary': forms.Textarea(attrs={'wrap':'soft'}), 'terms': forms.Textarea(attrs={'wrap':'soft'}), 'notes': forms.Textarea(attrs={'wrap':'soft'}), } class ShowingForm(forms.ModelForm): class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by') class NewShowingForm(forms.ModelForm): # Same as Showing, but without the role field class Meta(object): model = cube.diary.models.Showing # Exclude these for now: exclude = ('event', 'extra_copy', 'extra_copy_summary', 'booked_by', 'roles')
Fix classpath after update to Smack to 4.4
package org.jivesoftware.fastpath; /** * Fastpath / Workgroup related code is available in smack-legacy.jar. Sadly, only part of the IQ providers and packet * extensions is loaded by default by Smack (see SMACK-729 in the issue tracker). * <p> * To work around this issue, this class initializes the remaining classes. This class should no longer be needed when * the original problem in Smack is fixed. * * @author Guus der Kinderen, guus.der.kinderen@gmail.com * @see <a href="https://igniterealtime.atlassian.net/browse/SMACK-729">Issue SMACK-729</a> */ import org.jivesoftware.smack.initializer.UrlInitializer; public class WorkgroupInitializer extends UrlInitializer { public WorkgroupInitializer() { } @Override protected String getProvidersUri() { return "classpath:org.jivesoftware.smack.legacy/legacy.providers"; } }
package org.jivesoftware.fastpath; /** * Fastpath / Workgroup related code is available in smack-legacy.jar. Sadly, only part of the IQ providers and packet * extensions is loaded by default by Smack (see SMACK-729 in the issue tracker). * <p> * To work around this issue, this class initializes the remaining classes. This class should no longer be needed when * the original problem in Smack is fixed. * * @author Guus der Kinderen, guus.der.kinderen@gmail.com * @see <a href="https://igniterealtime.atlassian.net/browse/SMACK-729">Issue SMACK-729</a> */ import org.jivesoftware.smack.initializer.UrlInitializer; public class WorkgroupInitializer extends UrlInitializer { public WorkgroupInitializer() { } @Override protected String getProvidersUri() { return "classpath:org.jivesoftware.smack.legacy/workgroup.providers"; } }
Split the event category into yes/no
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful: yes', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful: no', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: -1 }); });
var helpful_yes = document.querySelector( '.helpful_yes' ); var helpful_no = document.querySelector( '.helpful_no' ); var helpful_text = document.querySelector( '.helpful__question' ); function thanks(){ helpful_text.innerHTML = "Thanks for your response and helping us improve our content."; helpful_no.remove(); helpful_yes.remove(); } AddEvent( helpful_yes, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: yes', eventValue: 1 }); }); AddEvent( helpful_no, 'click', function( event, $this ) { PreventEvent( event ); thanks(); ga('send', { hitType: 'event', eventCategory: 'helpful', eventAction: window.location.href, eventLabel: 'helpful: no', eventValue: -1 }); });
Revert "switched to execut ckfinder" This reverts commit a9657b395a551b96211ca18f60258ec6bfb533bb.
<?php /** * @author Mamaev Yuriy (eXeCUT) * @link https://github.com/execut * @copyright Copyright (c) 2020 Mamaev Yuriy (eXeCUT) * @license http://www.apache.org/licenses/LICENSE-2.0 */ namespace execut\crudFields\fields\detailViewField; use execut\crudFields\fields\DetailViewField; use iutbay\yii2kcfinder\CKEditor; use kartik\detail\DetailView; /** * DetailViewField for WYSIWYG HTML editor widget * @package execut\crudFields\fields\detailViewField */ class Editor extends DetailViewField { /** * {@inheritdoc} */ public function getConfig($model = null) { return array_merge(parent::getConfig($model), [ 'type' => DetailView::INPUT_WIDGET, 'format' => 'html', 'widgetOptions' => [ 'class' => CKEditor::class, 'preset' => 'full', 'clientOptions' => [ 'language' => \yii::$app ? \yii::$app->language : null, 'allowedContent' => true, ], ], ]); } }
<?php /** * @author Mamaev Yuriy (eXeCUT) * @link https://github.com/execut * @copyright Copyright (c) 2020 Mamaev Yuriy (eXeCUT) * @license http://www.apache.org/licenses/LICENSE-2.0 */ namespace execut\crudFields\fields\detailViewField; use execut\crudFields\fields\DetailViewField; use execut\yii2kcfinder\CKEditor; use kartik\detail\DetailView; /** * DetailViewField for WYSIWYG HTML editor widget * @package execut\crudFields\fields\detailViewField */ class Editor extends DetailViewField { /** * {@inheritdoc} */ public function getConfig($model = null) { return array_merge(parent::getConfig($model), [ 'type' => DetailView::INPUT_WIDGET, 'format' => 'html', 'widgetOptions' => [ 'class' => CKEditor::class, 'preset' => 'full', 'clientOptions' => [ 'language' => \yii::$app ? \yii::$app->language : null, 'allowedContent' => true, ], ], ]); } }
Add placeholder for CSV file
from collections import OrderedDict import os import sys import json try: gb_home = os.environ["GB_HOME"] except KeyError: raise RuntimeError("Please set the environment variable GB_HOME") repo_dir = os.path.join(gb_home, 'repos') data_dir = os.path.join(gb_home, 'data') log_dir = os.path.join(gb_home, 'log') grade_file = 'grades.json' instructor_home = os.path.join(repo_dir, 'instructor', 'assignments') student_grades = grade_file class_grades = os.path.join(data_dir, grade_file) config_file = os.path.join(data_dir, 'config.json') csv_file = os.path.join(data_home, 'grades.csv') class_log = os.path.join(log_dir, 'grade.log') def get_grades(filename=class_grades): try: with open(filename) as infile: grades = json.load(infile, object_pairs_hook=OrderedDict) except: print("Trouble loading " + filename) sys.exit(1) return grades def save_grades(content, filename): with open(filename, 'w') as outfile: json.dump(content, outfile, indent=4) grades = get_grades()
from collections import OrderedDict import os import sys import json try: gb_home = os.environ["GB_HOME"] except KeyError: raise RuntimeError("Please set the environment variable GB_HOME") repo_dir = os.path.join(gb_home, 'repos') data_dir = os.path.join(gb_home, 'data') log_dir = os.path.join(gb_home, 'log') grade_file = 'grades.json' instructor_home = os.path.join(repo_dir, 'instructor', 'assignments') student_grades = grade_file class_grades = os.path.join(data_dir, grade_file) config_file = os.path.join(data_dir, 'config.json') class_log = os.path.join(log_dir, 'grade.log') def get_grades(filename=class_grades): try: with open(filename) as infile: grades = json.load(infile, object_pairs_hook=OrderedDict) except: print("Trouble loading " + filename) sys.exit(1) return grades def save_grades(content, filename): with open(filename, 'w') as outfile: json.dump(content, outfile, indent=4) grades = get_grades()
Increase timeout to avoid breaking build
import { expect } from 'chai'; import { createStream } from './helper'; describe('build.js', () => { describe('Failures', () => { it('should stop when there is no index file', () => { const stream = createStream(['build']); return stream.once('data') .then(output => { expect(output).to.match(/something went wrong/); return stream.once('data'); }) .then(output => { expect(output).to.match(/Error: Missing index/); }) .finally(stream.close); }).timeout(10000); }); });
import { expect } from 'chai'; import { createStream } from './helper'; describe('build.js', () => { describe('Failures', () => { it('should stop when there is no index file', () => { const stream = createStream(['build']); return stream.once('data') .then(output => { expect(output).to.match(/something went wrong/); return stream.once('data'); }) .then(output => { expect(output).to.match(/Error: Missing index/); }) .finally(stream.close); }); }); });
Handle audience as an array According to RFC7519, `aud` claim is an array of strings; only in case there's one audience, `aud` can be a string. See https://tools.ietf.org/html/rfc7519#page-9 This fix allows for audience claim to be both string and array of strings.
const isAudienceValid = (aud, key) => (Array.isArray(aud) && aud.indexOf(key) !== -1) || aud === key; module.exports = (provider, body, session) => { if (!/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/.test(body.id_token)) { return {error: 'Grant: OpenID Connect invalid id_token format'} } var [header, payload, signature] = body.id_token.split('.') try { header = JSON.parse(Buffer.from(header, 'base64').toString('binary')) payload = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) } catch (err) { return {error: 'Grant: OpenID Connect error decoding id_token'} } if (!isAudienceValid(payload.aud, provider.key)) { return {error: 'Grant: OpenID Connect invalid id_token audience'} } else if ((payload.nonce && session.nonce) && (payload.nonce !== session.nonce)) { return {error: 'Grant: OpenID Connect nonce mismatch'} } return {header, payload, signature} }
module.exports = (provider, body, session) => { if (!/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/.test(body.id_token)) { return {error: 'Grant: OpenID Connect invalid id_token format'} } var [header, payload, signature] = body.id_token.split('.') try { header = JSON.parse(Buffer.from(header, 'base64').toString('binary')) payload = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')) } catch (err) { return {error: 'Grant: OpenID Connect error decoding id_token'} } if (payload.aud !== provider.key) { return {error: 'Grant: OpenID Connect invalid id_token audience'} } else if ((payload.nonce && session.nonce) && (payload.nonce !== session.nonce)) { return {error: 'Grant: OpenID Connect nonce mismatch'} } return {header, payload, signature} }
Fix bug: continue running when fail to open file
#--coding:utf-8-- #StartPage.py #Create/Edit file:'../cfg/StartPage.json' import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) if not cfgfile: prompt.Exit() sys.exit(False) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
#--coding:utf-8-- #StartPage.py #Create/Edit file:'../cfg/StartPage.json' import os import re import sys import json from __common__code__ import CreateFile from __tmpl__ import Prompt class PromptClass(Prompt.ErrPrompt): def InitInput(self): print ("Please input URL(s), use EOF to finish. \n(CTRL+D. if not work for Windows, try CTRL+Z)") def main(): prompt = PromptClass() cfgfile = CreateFile('StartPage.json', 'cfg', TransferredMeaning = True, Prompt = True) URL = [] IllegalChars = r"[^ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\-\.\_\~\:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]" try: prompt.InitInput() while True: tmp = raw_input() if re.search(IllegalChars, tmp): prompt.IllegalURL() URL.append(tmp) except EOFError: prompt.Exit() json.dump(URL, cfgfile) cfgfile.close() return if __name__ == '__main__': main() else: raise EnvironmentError("Please do not import this script as a module!")
Replace lambda with a method reference
package com.nilhcem.droidcontn.core.dagger.module; import android.app.Application; import android.database.sqlite.SQLiteOpenHelper; import com.nilhcem.droidcontn.data.database.DbOpenHelper; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import timber.log.Timber; @Module public class DatabaseModule { static final String TAG = "database"; @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { return new DbOpenHelper(application); } @Provides @Singleton SqlBrite provideSqlBrite() { return SqlBrite.create(Timber.tag(TAG)::v); } @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { return sqlBrite.wrapDatabaseHelper(helper); } }
package com.nilhcem.droidcontn.core.dagger.module; import android.app.Application; import android.database.sqlite.SQLiteOpenHelper; import com.nilhcem.droidcontn.data.database.DbOpenHelper; import com.squareup.sqlbrite.BriteDatabase; import com.squareup.sqlbrite.SqlBrite; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import timber.log.Timber; @Module public class DatabaseModule { static final String TAG = "database"; @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) { return new DbOpenHelper(application); } @Provides @Singleton SqlBrite provideSqlBrite() { return SqlBrite.create(message -> Timber.tag(TAG).v(message)); } @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) { return sqlBrite.wrapDatabaseHelper(helper); } }
Fix `language_choose_control` migration default value. Co-Authored-By: Éric <34afff4eac2f9b94bd269db558876db6be315161@users.noreply.github.com>
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("admin_interface", "0024_remove_theme_css"), ] operations = [ migrations.AddField( model_name="theme", name="language_chooser_control", field=models.CharField( choices=[ ("default-select", "Default Select"), ("minimal-select", "Minimal Select"), ], default="default-select", max_length=20, verbose_name="control", ), ), ]
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("admin_interface", "0024_remove_theme_css"), ] operations = [ migrations.AddField( model_name="theme", name="language_chooser_control", field=models.CharField( choices=[ ("default-select", "Default Select"), ("minimal-select", "Minimal Select"), ], default="select", max_length=20, verbose_name="control", ), ), ]
Fix redirect so it only applies when mode is missing
import React from 'react' import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom' import Header from './components/header' import Footer from './components/footer' import Homepage from './screens/homepage' import UserDashboard from './screens/userDashboard' import ProjectScreen from './screens/project' export default () => <Router> <div className="wrapper"> <Header /> <Route exact path="/" component={Homepage} /> <Route exact path="/:username" component={UserDashboard} /> <Route exact path="/:username/:project" render={({ match }) => <Redirect to={`${match.url}/edit`.replace('//', '/')} />} /> <Switch> <Route path="/:username/:project/:mode" component={ProjectScreen} /> <Route path="/:username/:owner/:project/:mode" component={ProjectScreen} /> </Switch> <Footer /> </div> </Router>
import React from 'react' import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom' import Header from './components/header' import Footer from './components/footer' import Homepage from './screens/homepage' import UserDashboard from './screens/userDashboard' import ProjectScreen from './screens/project' export default () => <Router> <div className="wrapper"> <Header /> <Route exact path="/" component={Homepage} /> <Route exact path="/:username" component={UserDashboard} /> <Route path="/:username/:project" render={({ match }) => <Redirect to={`${match.url}/edit`.replace('//', '/')} />} /> <Switch> <Route path="/:username/:project/:mode" component={ProjectScreen} /> <Route path="/:username/:owner/:project/:mode" component={ProjectScreen} /> </Switch> <Footer /> </div> </Router>
Update native client to new API
<?php /** * @package Tivoka * @author Marcel Klehr <mklehr@gmx.net> * @copyright (c) 2011, Marcel Klehr */ /** * JSON-RPC client * @package Tivoka */ class Tivoka_Client { /** * Acts as a counter for the request IDs used * @var integer */ public $id = 0; /** * Holds the connection to the remote server * @var Tivoka_Connection */ public $connection; /** * Construct a native client * @access private * @param string $target URL */ public function __construct($target) { $this->connection = Tivoka::connect($target); } /** * Sends a JSON-RPC request * @param Tivoka_Request $request A Tivoka request * @return void */ public function __call($method, $args) { $request = Tivoka::createRequest($this->id++, $method, $args); $this->connection->send($request); if($request->isError()) { throw new Tivoka_Exception($request->errorMessage, $request->error); } return $request->result; } } ?>
<?php /** * @package Tivoka * @author Marcel Klehr <mklehr@gmx.net> * @copyright (c) 2011, Marcel Klehr */ /** * JSON-RPC client * @package Tivoka */ class Tivoka_Client { /** * Acts as a counter for the request IDs used * @var integer */ public $id = 0; /** * Holds the connection to the remote server * @var Tivoka_Connection */ public $connection; /** * Construct a native client * @access private * @param string $target URL */ public function __construct($target) { $this->connection = Tivoka::connect($target); } /** * Sends a JSON-RPC request * @param Tivoka_Request $request A Tivoka request * @return void */ public function __call($method, $args) { $request = Tivoka::createRequest($this->id++, $method, $args); $this->connection->send($request); if($request->response->isError()) { throw new Tivoka_Exception($request->response->errorMessage, $request->response->error); } return $request->response->result; } } ?>
Use insert instead store (update or insert)
package com.kdemo.jooq.dao.impl; import static com.kdemo.jooq.domain.Tables.USERS; import java.util.List; import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.kdemo.jooq.dao.UserDAO; import com.kdemo.jooq.domain.tables.pojos.Users; import com.kdemo.jooq.domain.tables.records.UsersRecord; @Repository @Transactional public class UserDAOImpl implements UserDAO { @Autowired private DSLContext dsl; @Override public List<Users> getUsers() { return dsl .select(USERS.fields()) .from(USERS) .fetchInto(Users.class); } @Override public int insert(Users user) { // option 1 : with fetch auto ID UsersRecord newRecord = dsl.newRecord(USERS, user); int store = newRecord.insert(); if(store > 0) { user.setId(newRecord.getId()); } return store; // Otion 2 /* return dsl.insertInto(USERS, USERS.NAME, USERS.GENDER) .values(user.getName(), user.getGender()) .execute();*/ } }
package com.kdemo.jooq.dao.impl; import static com.kdemo.jooq.domain.Tables.USERS; import java.util.List; import org.jooq.DSLContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.kdemo.jooq.dao.UserDAO; import com.kdemo.jooq.domain.tables.pojos.Users; import com.kdemo.jooq.domain.tables.records.UsersRecord; @Repository @Transactional public class UserDAOImpl implements UserDAO { @Autowired private DSLContext dsl; @Override public List<Users> getUsers() { return dsl .select(USERS.fields()) .from(USERS) .fetchInto(Users.class); } @Override public int insert(Users user) { // option 1 : with fetch auto ID UsersRecord newRecord = dsl.newRecord(USERS, user); int store = newRecord.store(); if(store > 0) { user.setId(newRecord.getId()); } return store; // Otion 2 /* return dsl.insertInto(USERS, USERS.NAME, USERS.GENDER) .values(user.getName(), user.getGender()) .execute();*/ } }
Update the event name in the test, too.
require('./common'); var DB_NAME = 'node-couchdb-test', callbacks = { A: false, B1: false, B2: false, C: false, }, db = client.db(DB_NAME); // Init fresh db db.remove(); db .create(function(er) { if (er) throw er; var stream = db.changesStream(); stream .addListener('data', function(change) { callbacks['B'+change.seq] = true; if (change.seq == 2) { stream.close(); } }) .addListener('end', function() { callbacks.C = true; }); }); db.saveDoc({test: 1}); db.saveDoc({test: 2}); db.changes({since: 1}, function(er, r) { if (er) throw er; callbacks.A = true; assert.equal(2, r.results[0].seq); assert.equal(1, r.results.length); }); process.addListener('exit', function() { checkCallbacks(callbacks); });
require('./common'); var DB_NAME = 'node-couchdb-test', callbacks = { A: false, B1: false, B2: false, C: false, }, db = client.db(DB_NAME); // Init fresh db db.remove(); db .create(function(er) { if (er) throw er; var stream = db.changesStream(); stream .addListener('change', function(change) { callbacks['B'+change.seq] = true; if (change.seq == 2) { stream.close(); } }) .addListener('end', function() { callbacks.C = true; }); }); db.saveDoc({test: 1}); db.saveDoc({test: 2}); db.changes({since: 1}, function(er, r) { if (er) throw er; callbacks.A = true; assert.equal(2, r.results[0].seq); assert.equal(1, r.results.length); }); process.addListener('exit', function() { checkCallbacks(callbacks); });
Update the PyPI version to 8.0.0.
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='8.0.0', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
# -*- coding: utf-8 -*- import os from setuptools import setup def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() except: return '' setup( name='todoist-python', version='7.0.18', packages=['todoist', 'todoist.managers'], author='Doist Team', author_email='info@todoist.com', license='BSD', description='todoist-python - The official Todoist Python API library', long_description = read('README.md'), install_requires=[ 'requests', ], # see here for complete list of classifiers # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=( 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', ), )
Remove version from Build filter.
from django.utils.translation import ugettext_lazy as _ import django_filters from builds import constants from builds.models import Build, Version ANY_REPO = ( ('', _('Any')), ) BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES class VersionFilter(django_filters.FilterSet): project = django_filters.CharFilter(name='project__name', lookup_type="icontains") slug= django_filters.CharFilter(label=_("Slug"), name='slug', lookup_type='icontains') class Meta: model = Version fields = ['project', 'slug'] class BuildFilter(django_filters.FilterSet): date = django_filters.DateRangeFilter(label=_("Build Date"), name="date") type = django_filters.ChoiceFilter(label=_("Build Type"), choices=BUILD_TYPES) class Meta: model = Build fields = ['type', 'date', 'success']
from django.utils.translation import ugettext_lazy as _ import django_filters from builds import constants from builds.models import Build, Version ANY_REPO = ( ('', _('Any')), ) BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES class VersionFilter(django_filters.FilterSet): project = django_filters.CharFilter(name='project__name', lookup_type="icontains") slug= django_filters.CharFilter(label=_("Slug"), name='slug', lookup_type='icontains') class Meta: model = Version fields = ['project', 'slug'] class BuildFilter(django_filters.FilterSet): date = django_filters.DateRangeFilter(label=_("Build Date"), name="date") type = django_filters.ChoiceFilter(label=_("Build Type"), choices=BUILD_TYPES) class Meta: model = Build fields = ['type', 'date', 'version', 'success']
Increase waitress setting max_request_body_size to 5GiB Python waitress limits the body size to 1GiB by default, thus uploading of larger objects will fail if this value is not increased. Please note that this value should be increased if your Swift cluster supports uploading of objects larger than 5GiB.
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000, max_request_body_size=5*1024*1024*1024)
from swiftdav.swiftdav import SwiftProvider, WsgiDAVDomainController from waitress import serve from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp proxy = 'http://127.0.0.1:8080/auth/v1.0' insecure = False # Set to True to disable SSL certificate validation config = DEFAULT_CONFIG.copy() config.update({ "provider_mapping": {"": SwiftProvider()}, "verbose": 1, "propsmanager": True, "locksmanager": True, "acceptbasic": True, "acceptdigest": False, "defaultdigest": False, "domaincontroller": WsgiDAVDomainController(proxy, insecure) }) app = WsgiDAVApp(config) serve(app, host="0.0.0.0", port=8000)
Use trove classifiers from official list (aligned with https://pypi.python.org/pypi?%3Aaction=list_classifiers)
import sys if sys.version_info < (2, 7): print sys.stderr, "{}: need Python 2.7 or later.".format(sys.argv[0]) print sys.stderror, "Your python is {}".format(sys.version) sys.exit(1) from setuptools import setup setup( name = "python-json-logger", version = "0.0.1", url = "http://github.com/madzak/python-json-logger", license = "BSD", description = "A python library adding a json log formatter", author = "Zakaria Zajac", author_email = "zak@madzak.com", package_dir = {'': 'src'}, packages = [''], test_suite = "tests.tests", install_requires = ['setuptools'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Logging', ] )
import sys if sys.version_info < (2, 7): print sys.stderr, "{}: need Python 2.7 or later.".format(sys.argv[0]) print sys.stderror, "Your python is {}".format(sys.version) sys.exit(1) from setuptools import setup setup( name = "python-json-logger", version = "0.0.1", url = "http://github.com/madzak/python-json-logger", license = "BSD", description = "A python library adding a json log formatter", author = "Zakaria Zajac", author_email = "zak@madzak.com", package_dir = {'': 'src'}, packages = [''], test_suite = "tests.tests", install_requires = ['setuptools'], classifiers = [ 'Development Status :: 1 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operation System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Logging', ] )
Use six function for input() in recent questions demo
#!/usr/bin/env python from __future__ import print_function from six.moves import input # Same directory hack import sys sys.path.append('.') sys.path.append('..') user_api_key = input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
#!/usr/bin/env python from __future__ import print_function # Same directory hack import sys sys.path.append('.') sys.path.append('..') try: get_input = raw_input except NameError: get_input = input user_api_key = get_input("Please enter an API key if you have one (Return for none):") if not user_api_key: user_api_key = None import stackexchange, thread so = stackexchange.Site(stackexchange.StackOverflow, app_key=user_api_key, impose_throttling=True) so.be_inclusive() sys.stdout.write('Loading...') sys.stdout.flush() questions = so.recent_questions(pagesize=10, filter='_b') print('\r # vote ans view') cur = 1 for question in questions: print('%2d %3d %3d %3d \t%s' % (cur, question.score, len(question.answers), question.view_count, question.title)) cur += 1 num = int(get_input('Question no.: ')) qu = questions[num - 1] print('--- %s' % qu.title) print('%d votes, %d answers, %d views.' % (qu.score, len(qu.answers), qu.view_count)) print('Tagged: ' + ', '.join(qu.tags)) print() print(qu.body[:250] + ('...' if len(qu.body) > 250 else ''))
Consolidate creation of AES-GCM cipher mode into a single function
package bletchley import ( "crypto/aes" "crypto/cipher" ) const ( symmetricNonceLength = 12 symmetricKeyLength = 32 ) // We are allowed to use an empty nonce because we never re-use keys // see Section 8.2.1 of NIST Special Publication 800-38D // http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf var zeroNonce []byte = make([]byte, symmetricNonceLength) func makeAESGCM(aesKey []byte) (cipher.AEAD, error) { blockCipher, err := aes.NewCipher(aesKey) if err != nil { return nil, err } return cipher.NewGCM(blockCipher) } func symmetricDecrypt(aesKey, ciphertext []byte) ([]byte, error) { gcm, err := makeAESGCM(aesKey) if err != nil { return nil, err } return gcm.Open(nil, zeroNonce, ciphertext, nil) } func symmetricEncrypt(aesKey, plaintext []byte) ([]byte, error) { gcm, err := makeAESGCM(aesKey) if err != nil { return nil, err } return gcm.Seal(nil, zeroNonce, plaintext, nil), nil }
package bletchley import ( "crypto/aes" "crypto/cipher" ) const ( symmetricNonceLength = 12 symmetricKeyLength = 32 ) // We are allowed to use an empty nonce because we never re-use keys // see Section 8.2.1 of NIST Special Publication 800-38D // http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf var zeroNonce []byte = make([]byte, symmetricNonceLength) func symmetricDecrypt(aesKey, ciphertext []byte) ([]byte, error) { blockCipher, err := aes.NewCipher(aesKey) if err != nil { return nil, err } streamCipher, err := cipher.NewGCM(blockCipher) if err != nil { return nil, err } return streamCipher.Open(nil, zeroNonce, ciphertext, nil) } func symmetricEncrypt(aesKey, plaintext []byte) ([]byte, error) { blockCipher, err := aes.NewCipher(aesKey) if err != nil { return []byte{}, err } streamCipher, err := cipher.NewGCM(blockCipher) if err != nil { return []byte{}, err } ciphertext := streamCipher.Seal(nil, zeroNonce, plaintext, nil) return ciphertext, nil }
Remove unnecessary spaces for readability
import express from 'express'; import validate from 'express-validation'; import paramValidation from './validation/user'; import userCtrl from '../controllers/user'; const router = express.Router(); // eslint-disable-line new-cap router.route('/') .post(validate(paramValidation.createUser), userCtrl.createUser); router.route('/:userId') .get(validate(paramValidation.byId), userCtrl.getUser) .put(validate(paramValidation.updateUser), userCtrl.updateUser) .delete(validate(paramValidation.byId), userCtrl.deleteUser); router.route('/:userId/device') .post(validate(paramValidation.addDevice), userCtrl.addDevice); router.route('/:userId/device/:deviceId') .get(validate(paramValidation.deviceById), userCtrl.getDevice) .put(validate(paramValidation.updateDevice), userCtrl.updateDevice) .post(validate(paramValidation.deviceById), userCtrl.sortDevices) .delete(validate(paramValidation.deviceById), userCtrl.removeDevice); router.route('/:userId/group') .get(validate(paramValidation.byId), userCtrl.getGroupsForUser); /** Load user when API with userId route parameter is hit */ router.param('userId', userCtrl.loadUser); export default router;
import express from 'express'; import validate from 'express-validation'; import paramValidation from './validation/user'; import userCtrl from '../controllers/user'; const router = express.Router(); // eslint-disable-line new-cap router.route('/') .post(validate(paramValidation.createUser), userCtrl.createUser); router.route('/:userId') .get(validate(paramValidation.byId), userCtrl.getUser) .put(validate(paramValidation.updateUser), userCtrl.updateUser) .delete(validate(paramValidation.byId), userCtrl.deleteUser); router.route('/:userId/device') .post(validate(paramValidation.addDevice), userCtrl.addDevice); router.route('/:userId/device/:deviceId') .get(validate(paramValidation.deviceById), userCtrl.getDevice) .put(validate(paramValidation.updateDevice), userCtrl.updateDevice) .post(validate(paramValidation.deviceById), userCtrl.sortDevices) .delete(validate(paramValidation.deviceById), userCtrl.removeDevice); router.route('/:userId/group') .get(validate(paramValidation.byId), userCtrl.getGroupsForUser); /** Load user when API with userId route parameter is hit */ router.param('userId', userCtrl.loadUser); export default router;
Reorder register and boot methods
<?php namespace Laravel\Lumen\Providers; use Illuminate\Support\ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event handler mappings for the application. * * @var array */ protected $listen = []; /** * The subscriber classes to register. * * @var array */ protected $subscribe = []; /** * {@inheritdoc} */ public function register() { // } /** * Register the application's event listeners. * * @return void */ public function boot() { $events = app('events'); foreach ($this->listen as $event => $listeners) { foreach ($listeners as $listener) { $events->listen($event, $listener); } } foreach ($this->subscribe as $subscriber) { $events->subscribe($subscriber); } } /** * Get the events and handlers. * * @return array */ public function listens() { return $this->listen; } }
<?php namespace Laravel\Lumen\Providers; use Illuminate\Support\ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event handler mappings for the application. * * @var array */ protected $listen = []; /** * The subscriber classes to register. * * @var array */ protected $subscribe = []; /** * Register the application's event listeners. * * @return void */ public function boot() { $events = app('events'); foreach ($this->listen as $event => $listeners) { foreach ($listeners as $listener) { $events->listen($event, $listener); } } foreach ($this->subscribe as $subscriber) { $events->subscribe($subscriber); } } /** * {@inheritdoc} */ public function register() { // } /** * Get the events and handlers. * * @return array */ public function listens() { return $this->listen; } }
Add missing binding for Logging
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.log; import com.google.common.annotations.Beta; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Provides; import com.google.inject.Scopes; import javax.inject.Singleton; import static org.weakref.jmx.guice.ExportBinder.newExporter; @Beta public class LogJmxModule implements Module { @Override public void configure(Binder binder) { binder.disableCircularProxies(); binder.bind(LoggingMBean.class).in(Scopes.SINGLETON); newExporter(binder).export(LoggingMBean.class).as("com.proofpoint.log:name=Logging"); } @Provides @Singleton public Logging getLogging() { return Logging.initialize(); } }
/* * Copyright 2010 Proofpoint, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.proofpoint.log; import com.google.common.annotations.Beta; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import static org.weakref.jmx.guice.ExportBinder.newExporter; @Beta public class LogJmxModule implements Module { @Override public void configure(Binder binder) { binder.disableCircularProxies(); binder.bind(LoggingMBean.class).in(Scopes.SINGLETON); newExporter(binder).export(LoggingMBean.class).as("com.proofpoint.log:name=Logging"); } }