text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add methods withDateTime(String) and withPriority(String)
package tars.testutil; import tars.commons.exceptions.IllegalValueException; import tars.model.task.*; import tars.model.tag.Tag; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Name(name)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withDateTime(String dateTime) throws IllegalValueException { this.task.setDateTime(new DateTime(dateTime, "")); return this; } public TaskBuilder withPriority(String priority) throws IllegalValueException { this.task.setPriority(new Priority(priority)); return this; } public TestTask build() { return this.task; } }
package tars.testutil; import tars.commons.exceptions.IllegalValueException; import tars.model.task.*; import tars.model.tag.Tag; /** * */ public class TaskBuilder { private TestTask task; public TaskBuilder() { this.task = new TestTask(); } public TaskBuilder withName(String name) throws IllegalValueException { this.task.setName(new Name(name)); return this; } public TaskBuilder withTags(String ... tags) throws IllegalValueException { for (String tag: tags) { task.getTags().add(new Tag(tag)); } return this; } public TaskBuilder withAddress(String address) throws IllegalValueException { this.task.setAddress(new Address(address)); return this; } public TaskBuilder withPhone(String phone) throws IllegalValueException { this.task.setPhone(new Phone(phone)); return this; } public TaskBuilder withEmail(String email) throws IllegalValueException { this.task.setEmail(new Email(email)); return this; } public TestTask build() { return this.task; } }
Change logic of where href is set for the root anchor
'use strict'; // DEV TIME CODE if (FAKE_SERVER) { require('fake'); } // DEV TIME CODE require('./index.scss'); var $ = require('$jquery'); var util = require('lib/util'); var state = require('./state'); var repository = require('./repository'); var sections = require('./sections/section'); //var details = args.newData.hud; var setup = state.current(); // get into dom asap to trigger asset loading $(function() { var url = util.resolveClientUrl(util.currentRequestId(), true); var html = '<div class="glimpse"><a class="glimpse-icon" target="_blank" href="' + url + '"><div class="glimpse-icon-text">Glimpse</div></a><div class="glimpse-hud"></div></div>' $(html).appendTo('body'); }); // only load things when we have the data ready to go repository.getData(function(details) { $(function() { setTimeout(function() { // generate the html needed for the sections var html = sections.render(details, setup); // insert the html into the dom var holder = $(html).appendTo('.glimpse-hud'); // force the correct state from previous load state.setup(holder); // setup events that we need to listen to sections.postRender(holder); }, 0); }); });
'use strict'; // DEV TIME CODE if (FAKE_SERVER) { require('fake'); } // DEV TIME CODE require('./index.scss'); var $ = require('$jquery'); var util = require('lib/util'); var state = require('./state'); var repository = require('./repository'); var sections = require('./sections/section'); //var details = args.newData.hud; var setup = state.current(); // get into dom asap to trigger asset loading $(function() { var html = '<div class="glimpse"><a class="glimpse-icon" target="_blank"><div class="glimpse-icon-text">Glimpse</div></a><div class="glimpse-hud"></div></div>' $(html).appendTo('body'); }); // only load things when we have the data ready to go repository.getData(function(details) { $(function() { setTimeout(function() { // TODO: need to find a better place for this $('.glimpse-icon').attr('href', util.resolveClientUrl(util.currentRequestId(), true)) // generate the html needed for the sections var html = sections.render(details, setup); // insert the html into the dom var holder = $(html).appendTo('.glimpse-hud'); // force the correct state from previous load state.setup(holder); // setup events that we need to listen to sections.postRender(holder); }, 0); }); });
Fix incorrect proptype in native pdf viewer
'use strict'; var React = require('react'), GenericViewer = require('../../generic/viewer.js'); var NativeViewer = React.createClass({ propTypes: { resizeCallback: React.PropTypes.func, progressCallback: React.PropTypes.func, srcdownload: React.PropTypes.string, locale: React.PropTypes.string, src: React.PropTypes.string }, componentWillMount: function() { this.updateProgress(0); if (this.props.resizeCallback) { this.props.resizeCallback('100%', false); } }, componentDidMount: function() { this.updateProgress(100); }, updateProgress: function(progress) { if (this.props.progressCallback) { this.props.progressCallback(progress, 'none'); } }, render: function() { return <object data={this.props.src} type="application/pdf" className="vui-fileviewer-pdf-native"> <GenericViewer srcdownload={this.props.srcdownload} locale={this.props.locale} /> </object>; } }); module.exports = NativeViewer;
'use strict'; var React = require('react'), GenericViewer = require('../../generic/viewer.js'); var NativeViewer = React.createClass({ propTypes: { resizeCallback: React.PropTypes.func, progressCallback: React.PropTypes.func, srcdownload: React.PropTypes.string, locale: React.PropTypes.string, src: React.PropTypes.src }, componentWillMount: function() { this.updateProgress(0); if (this.props.resizeCallback) { this.props.resizeCallback('100%', false); } }, componentDidMount: function() { this.updateProgress(100); }, updateProgress: function(progress) { if (this.props.progressCallback) { this.props.progressCallback(progress, 'none'); } }, render: function() { return <object data={this.props.src} type="application/pdf" className="vui-fileviewer-pdf-native"> <GenericViewer srcdownload={this.props.srcdownload} locale={this.props.locale} /> </object>; } }); module.exports = NativeViewer;
api: Add interface directives for counterfeiter Signed-off-by: Stephen Augustus <0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33@auggie.dev>
/* Copyright 2021 The Kubernetes Authors. 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 api import ( "io" ) //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate //counterfeiter:generate . File // TODO(api): Populate interface and regenerate mocks type File interface { Parse(io.Reader) (Document, error) } //counterfeiter:generate . Document // Document is an interface satisfied by the following types: // - `Proposal` (KEP) // - `PRRApproval` // - `Receipt` (coming soon) // TODO(api): Populate interface and regenerate mocks type Document interface { Validate() error } type Parser struct { Groups []string PRRApprovers []string Errors []error }
/* Copyright 2021 The Kubernetes Authors. 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 api import ( "io" ) // TODO(api): Populate interface // TODO(api): Mock interface type File interface { Parse(io.Reader) (Document, error) } // TODO(api): Populate interface // TODO(api): Mock interface // Document is an interface satisfied by the following types: // - `Proposal` (KEP) // - `PRRApproval` // - `Receipt` (coming soon) type Document interface { Validate() error } type Parser struct { Groups []string PRRApprovers []string Errors []error }
Add tasks test and tdd
var gulp = require('gulp'), coffee = require('gulp-coffee'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), del = require('del'), karma = require('karma').server; var paths = { scripts: ['source/**/*.coffee'] }; gulp.task('clean', function (cb) { del(['build'], cb); }); // Compiles coffee to js gulp.task('scripts', ['clean'], function () { return gulp.src(paths.scripts) .pipe(sourcemaps.init()) .pipe(coffee({bare: true})) //.pipe(uglify()) .pipe(concat('all.min.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('build')); }); gulp.task('watch', function () { gulp.watch(paths.scripts, ['scripts']); }); // Run test once and exit gulp.task('test', function (done) { karma.start({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done); }); // Watch for file changes and re-run tests on each change gulp.task('tdd', function (done) { karma.start({ configFile: __dirname + '/karma.conf.js' }, done); }); gulp.task('default', ['tdd']);
var gulp = require('gulp'), coffee = require('gulp-coffee'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), del = require('del'); var paths = { scripts: ['source/**/*.coffee'] }; gulp.task('clean', function (cb) { del(['build'], cb); }); // Compiles coffee to js gulp.task('scripts', ['clean'], function () { return gulp.src(paths.scripts) .pipe(sourcemaps.init()) .pipe(coffee({bare: true})) //.pipe(uglify()) .pipe(concat('all.min.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest('build')); }); gulp.task('watch', function () { gulp.watch(paths.scripts, ['scripts']); }); gulp.task('default', ['watch', 'scripts']);
Simplify implementation and achieve full test coverage
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var defineProperty = require( './define_property.js' ); // MAIN // /** * Tests for `Object.defineProperty` support. * * @private * @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support * * @example * var bool = hasDefinePropertySupport(); * // returns <boolean> */ function hasDefinePropertySupport() { // Test basic support... try { defineProperty( {}, 'x', {} ); return true; } catch ( err ) { // eslint-disable-line no-unused-vars return false; } } // EXPORTS // module.exports = hasDefinePropertySupport;
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var defineProperty = require( './define_property.js' ); // MAIN // /** * Tests for `Object.defineProperty` support. * * @private * @returns {boolean} boolean indicating if an environment has `Object.defineProperty` support * * @example * var bool = hasDefinePropertySupport(); * // returns <boolean> */ function hasDefinePropertySupport() { var bool; if ( defineProperty === null ) { return false; } // Test basic support... try { defineProperty( {}, 'x', {} ); bool = true; } catch ( err ) { // eslint-disable-line no-unused-vars bool = false; } return bool; } // EXPORTS // module.exports = hasDefinePropertySupport;
Change add debit note to greedy credit note.
<?php require __DIR__.'/autoload.php'; use LaravelLb\LogicBoxesReseller; // Setup user id and api key $userId = getenv('LB_AUTH_USERID'); $apiKey = getenv('LB_API_KEY'); // Setup reseller username and password $resellerId = getenv('RESELLER_ID'); $resellerUserName = getenv('RESELLER_USERNAME'); $resellerPassword = getenv('RESELLER_PASSWORD'); $variables = [ "selling-amount" => 0.15, "description" => "Test add debit note", "debit-note-date" => time(), "transaction-key" => generateRandomString(15), "update-total-receipt" => true, ]; $reseller = new LogicBoxesReseller($resellerId, $resellerUserName, $resellerPassword); /** No need to set user id if you're using Laravel, it will automatically get the credential from config/logicboxes.php */ $reseller->setUserId($userId)->setApiKey($apiKey); $response = $reseller->addGreedyDebitNote($variables)->toArray(); print_r($response);
<?php require __DIR__.'/autoload.php'; use LaravelLb\LogicBoxesReseller; // Setup user id and api key $userId = getenv('LB_AUTH_USERID'); $apiKey = getenv('LB_API_KEY'); // Setup reseller username and password $resellerId = getenv('RESELLER_ID'); $resellerUserName = getenv('RESELLER_USERNAME'); $resellerPassword = getenv('RESELLER_PASSWORD'); $variables = [ "selling-amount" => 0.5, "description" => "Test add debit note", "debit-note-date" => time(), "transaction-key" => generateRandomString(15), "update-total-receipt" => true, ]; $reseller = new LogicBoxesReseller($resellerId, $resellerUserName, $resellerPassword); /** No need to set user id if you're using Laravel, it will automatically get the credential from config/logicboxes.php */ $reseller->setUserId($userId)->setApiKey($apiKey); $response = $reseller->addDebitNote($variables)->toArray(); print_r($response);
Fix buggy use of pytest.raises() in tests.
from __future__ import absolute_import, print_function, unicode_literals import os import pytest import _test_utilities def test_fix_outsourcing_contrib_comments(): if os.environ.get( "IGNORE_CONTRIB_COMMENTS" ): # case where external dependency "django_comments" isn't loaded with pytest.raises(ImportError) as excinfo: from django.contrib import comments exc = excinfo.value expected_error = str(exc) assert ( "No module named 'django_comments' (when loading alias name 'django.contrib.comments')" in expected_error ) else: from django.contrib import comments import django.contrib.comments import django.contrib.comments.urls assert isinstance(django.contrib.comments.urls.urlpatterns, list) from django.contrib.comments.views import comments as comments_views assert callable(comments_views.post_comment)
from __future__ import absolute_import, print_function, unicode_literals import os import pytest import _test_utilities def test_fix_outsourcing_contrib_comments(): if os.environ.get( "IGNORE_CONTRIB_COMMENTS" ): # case where external dependency "django_comments" isn't loaded with pytest.raises(ImportError) as exc: from django.contrib import comments expected_error = str(exc) expected_error = expected_error.replace(r"\'", "'") # Sometimes quotes are escaped... assert ( "No module named 'django_comments' (when loading alias name 'django.contrib.comments')" in expected_error ) else: from django.contrib import comments import django.contrib.comments import django.contrib.comments.urls assert isinstance(django.contrib.comments.urls.urlpatterns, list) from django.contrib.comments.views import comments as comments_views assert callable(comments_views.post_comment)
Add dependency on requets module.
import os from setuptools import setup def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='pykismet3', version='0.1.0', description='A Python 3 module for the Akismet spam comment-spam-detection web service.', long_description=(read('README.md')), url='https://github.com/grundleborg/pykismet', license='MIT', author='George Goldberg', author_email='george@grundleborg.com', py_modules=['pykismet3'], include_package_data=True, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', ], install_requires=[ "requests", ], )
import os from setuptools import setup def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='pykismet3', version='0.1.0', description='A Python 3 module for the Akismet spam comment-spam-detection web service.', long_description=(read('README.md')), url='https://github.com/grundleborg/pykismet', license='MIT', author='George Goldberg', author_email='george@grundleborg.com', py_modules=['pykismet3'], include_package_data=True, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Use an application defined exception.
/* * MIT License * * Copyright (c) 2017 Hindol Adhya * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * https://github.com/Hindol/commons */ package net.aeronica.mods.mxtune.caches; import net.aeronica.mods.mxtune.util.MXTuneException; /** * Interface definition for services. */ public interface Service { /** * Starts the service. This method blocks until the service has completely started. */ void start() throws MXTuneException; /** * Stops the service. This method blocks until the service has completely shut down. */ void stop(); }
/* * MIT License * * Copyright (c) 2017 Hindol Adhya * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * https://github.com/Hindol/commons */ package net.aeronica.mods.mxtune.caches; /** * Interface definition for services. */ public interface Service { /** * Starts the service. This method blocks until the service has completely started. */ void start() throws Exception; /** * Stops the service. This method blocks until the service has completely shut down. */ void stop(); }
Remove version for now, since it's messing up beta deployment.
#!/usr/bin/python """Install, build, or test the HXL Proxy. For details, try python setup.py -h """ import sys, setuptools from hxl_proxy import __version__ if sys.version_info.major != 3: raise SystemExit("The HXL Proxy requires Python 3.x") setuptools.setup( name = 'hxl-proxy', packages = ['hxl_proxy'], package_data={'hxl_proxy': ['*.sql']}, version = __version__, description = 'Flask-based web proxy for HXL', author='David Megginson', author_email='contact@megginson.com', url='https://github.com/HXLStandard/hxl-proxy', include_package_data = True, zip_safe = False, install_requires=['flask-cache>=0.13', 'libhxl', 'ckanapi>=3.5', 'flask==0.12.4', 'requests_cache', 'mysql-connector-python'], test_suite = "tests", tests_require = ['mock'] )
#!/usr/bin/python """Install, build, or test the HXL Proxy. For details, try python setup.py -h """ import sys, setuptools from hxl_proxy import __version__ if sys.version_info.major != 3: raise SystemExit("The HXL Proxy requires Python 3.x") setuptools.setup( name = 'hxl-proxy', packages = ['hxl_proxy'], package_data={'hxl_proxy': ['*.sql']}, version = __version__, description = 'Flask-based web proxy for HXL', author='David Megginson', author_email='contact@megginson.com', url='https://github.com/HXLStandard/hxl-proxy', include_package_data = True, zip_safe = False, install_requires=['flask-cache>=0.13', 'libhxl==4.8', 'ckanapi>=3.5', 'flask==0.12.4', 'requests_cache', 'mysql-connector-python'], test_suite = "tests", tests_require = ['mock'] )
Clear form fields before entering new values
var helper = require('massah/helper') module.exports = (function() { var library = helper.getLibrary() .given('I enter \'(.*)\' in the \'(.*)\' field', function(value, field) { this.driver.input('*[name="' + field + '"]').clear() this.driver.input('*[name="' + field + '"]').enter(value) if (!this.params.fields) this.params.fields = {} this.params.fields[field] = value }) .then('the \'(.*)\' field has error \'(.*)\'', function(field, error) { var selector = 'div.error span.help-inline' this.driver.element(selector).text(function(text) { text.should.equal(error) }) this.driver.element('div.error input[name="' + field + '"]').then( function() {}, function() { throw new Error('Expected error field') } ) }) return library })()
var helper = require('massah/helper') module.exports = (function() { var library = helper.getLibrary() .given('I enter \'(.*)\' in the \'(.*)\' field', function(value, field) { this.driver.input('*[name="' + field + '"]').enter(value) if (!this.params.fields) this.params.fields = {} this.params.fields[field] = value }) .then('the \'(.*)\' field has error \'(.*)\'', function(field, error) { var selector = 'div.error span.help-inline' this.driver.element(selector).text(function(text) { text.should.equal(error) }) this.driver.element('div.error input[name="' + field + '"]').then( function() {}, function() { throw new Error('Expected error field') } ) }) return library })()
Fix cross linking to EG problem in compara trees
Ensembl.Panel.ZMenu.prototype.populateAjax = function(url, expand) { var timeout = this.timeout; url = url || this.href; this.crossOrigin = url && url.match(/^http/) ? url.split('/').slice(0,3).join('/') : false; if (url && window.location.pathname.match(/\/Gene\/Variation_Gene/) && !url.match(/\/ZMenu\//)) { url = url.replace(/\/(\w+\/\w+)\?/, '/ZMenu/$1?'); } if(url && url.match('www.wormbase.org')) { this.populateNoAjax(); } else if (url && url.match('/ZMenu/')) { $.extend($.ajax({ url: url, data: this.coords.clickStart ? { click_chr: this.coords.clickChr || Ensembl.location.name, click_start: this.coords.clickStart, click_end: this.coords.clickEnd } : {}, dataType: this.crossOrigin ? 'jsonp' : 'json', context: this, success: $.proxy(this.buildMenuAjax, this), error: $.proxy(this.populateNoAjax, this) }), { timeout: timeout, expand: expand }); } else { this.populateNoAjax(); } };
Ensembl.Panel.ZMenu.prototype.populateAjax = function(url, expand) { var timeout = this.timeout; url = url || this.href; if(url && url.match('www.wormbase.org')) { this.populateNoAjax(); } else if (url && url.match('/ZMenu/')) { $.extend($.ajax({ url: url, data: this.coords.clickStart ? { click_chr: this.coords.clickChr || Ensembl.location.name, click_start: this.coords.clickStart, click_end: this.coords.clickEnd } : {}, dataType: this.crossOrigin ? 'jsonp' : 'json', context: this, success: $.proxy(this.buildMenuAjax, this), error: $.proxy(this.populateNoAjax, this) }), { timeout: timeout, expand: expand }); } else { this.populateNoAjax(); } };
Rename package, add script to manifest
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages, Command import os packages = find_packages() class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) def get_locals(filename): l = {} execfile(filename, {}, l) return l metadata = get_locals(os.path.join('markdown_to_json', '_metadata.py')) setup( name="markdown-to-json", version=metadata['version'], author=metadata['author'], author_email=metadata['author_email'], license=metadata['license'], url=metadata['url'], packages=find_packages(), cmdclass={'test': PyTest}, entry_points={ 'console_scripts': [ 'md_to_json = markdown_to_json.scripts.md_to_json:main' ]} )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages, Command import os packages = find_packages() class PyTest(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys import subprocess errno = subprocess.call([sys.executable, 'runtests.py']) raise SystemExit(errno) def get_locals(filename): l = {} execfile(filename, {}, l) return l metadata = get_locals(os.path.join('bids_writer', '_metadata.py')) setup( name="bids-json-writer", version=metadata['version'], author=metadata['author'], author_email=metadata['author_email'], license=metadata['license'], url=metadata['url'], packages=find_packages(), cmdclass={'test': PyTest}, entry_points={ 'console_scripts': [ ]} )
Add charset to HTML5 doc (and make more XHTML friendly)
<!DOCTYPE html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script> </head><body></body> </html>
<!doctype html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script>
Improve efficiency of matching categories
<?php namespace Craft; class InstagramLoader_CategoriesService extends BaseApplicationComponent { private $categories = array(); function __construct() { // Get our category group id $categoryGroupId = craft()->plugins->getPlugin('instagramLoader')->getSettings()->categoryGroupId; // If there is no category group specified, don't do this if (!$categoryGroupId) { return; } // Create a Craft Element Criteria Model $criteria = craft()->elements->getCriteria(ElementType::Category); // Restrict the parameters to the correct category group $criteria->groupId = $categoryGroupId; // For each category foreach ($criteria as $category) { // Add its slug and id to our array $this->categories[$category->slug] = $category->id; } } public function parseCategories($tags) { $categoryIds = array(); foreach ($tags as $tag) { // If it matches one of the handles if (isset($this->categories[$tag])) { // Add the id to the array $categoryIds[] = $this->categories[$tag]; } } return $categoryIds; } }
<?php namespace Craft; class InstagramLoader_CategoriesService extends BaseApplicationComponent { private $categories = array(); function __construct() { // Get our category group id $categoryGroupId = craft()->plugins->getPlugin('instagramLoader')->getSettings()->categoryGroupId; // If there is no category group specified, don't do this if (!$categoryGroupId) { return; } // Create a Craft Element Criteria Model $criteria = craft()->elements->getCriteria(ElementType::Category); // Restrict the parameters to the correct category group $criteria->groupId = $categoryGroupId; // For each category foreach ($criteria as $category) { // Add its slug and id to our array $this->categories[$category->slug] = $category->id; } } public function parseCategories($tags) { $categoryIds = array(); foreach ($tags as $tag) { // If it matches one of the handles, add the id to the array and continue foreach ($this->categories as $slug => $id) { if ($tag === $slug) { $categoryIds[] = $id; } } } return $categoryIds; } }
Revert "Use strings.Builder instead of string concatenation." This reverts commit f10c846ab60d234aa449c042068ce461b2f6ed9a.
// Copyright 2015 Google Inc. All Rights Reserved. // This file is available under the Apache license. package errors import ( "fmt" "github.com/google/mtail/internal/vm/position" "github.com/pkg/errors" ) type compileError struct { pos position.Position msg string } func (e compileError) Error() string { return e.pos.String() + ": " + e.msg } // ErrorList contains a list of compile errors. type ErrorList []*compileError // Add appends an error at a position to the list of errors. func (p *ErrorList) Add(pos *position.Position, msg string) { *p = append(*p, &compileError{*pos, msg}) } // Append puts an ErrorList on the end of this ErrorList. func (p *ErrorList) Append(l ErrorList) { *p = append(*p, l...) } // ErrorList implements the error interface. func (p ErrorList) Error() string { switch len(p) { case 0: return "no errors" case 1: return p[0].Error() } var r string for _, e := range p { r = r + fmt.Sprintf("%s\n", e) } return r[:len(r)-1] } func Errorf(format string, args ...interface{}) error { return errors.Errorf(format, args...) }
// Copyright 2015 Google Inc. All Rights Reserved. // This file is available under the Apache license. package errors import ( "fmt" "strings" "github.com/google/mtail/internal/vm/position" "github.com/pkg/errors" ) type compileError struct { pos position.Position msg string } func (e compileError) Error() string { return e.pos.String() + ": " + e.msg } // ErrorList contains a list of compile errors. type ErrorList []*compileError // Add appends an error at a position to the list of errors. func (p *ErrorList) Add(pos *position.Position, msg string) { *p = append(*p, &compileError{*pos, msg}) } // Append puts an ErrorList on the end of this ErrorList. func (p *ErrorList) Append(l ErrorList) { *p = append(*p, l...) } // ErrorList implements the error interface. func (p ErrorList) Error() string { switch len(p) { case 0: return "no errors" case 1: return p[0].Error() } var r strings.Builder for _, e := range p { r.WriteString(fmt.Sprintf("%s\n", e)) } return r.String() } func Errorf(format string, args ...interface{}) error { return errors.Errorf(format, args...) }
Allow adjusting of RoomHistoryEntry attributes in UserFactory
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at for key, value in kwargs.items(): setattr(rhe, key, value) class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
# -*- coding: utf-8 -*- # Copyright (c) 2016 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
Add a timestamp to the filename to allow for chronological ordering in the filesystem
import datetime from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain self.created = datetime.datetime.fromtimestamp(post.created).strftime("%y%m%d") if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.created, self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
from utils.utils import limit_file_name class Image(): _file_name_pattern = "reddit_%s_%s_album_%s_%s_%s" def __init__(self, url, post, image_file): self.post_id = post.id self.url = url self.sub_display_name = post.subreddit.display_name self.image_file = limit_file_name(image_file) self.domain = post.domain if "/a/" in post.url: self.album_id = post.url[post.url.index("/a/") + 3:] elif "/gallery/" in post.url: self.album_id = post.url[post.url.index("/gallery/") + 9:] else: self.album_id = None self.local_file_name = self._file_name_pattern % ( self.sub_display_name, self.post_id, self.album_id, self.domain, self.image_file)
Add backbone and it's dependencies using componentDidMount
/** * @jsx React.DOM */ /* Requiring dependencies for demo purposes, this should be done only when required */ var React = require('React'); var SiteBoilerPlate = require('../views/core/SiteBoilerPlate.js'); var Skeleton = require('../views/Skeleton/Skeleton.js'); var ProfileCards = require('../views/ProfileCards/ProfileCards.js'); var Router = require('../routes/Routes.js'); var index = React.createClass({ componentDidMount: function() { /** * This runs on the client side. Add Jquery and Underscore to the window. * Initialize Backbone app once the dependencies are set up. */ window._ = require('underscore/underscore.js')({}); window.jQuery = require('../../bower_components/jquery/jquery.js'); window.Backbone = require('backbone/backbone.js'); var reactbackbone = require('../../bower_components/react.backbone/react.backbone.js'); }, render: function() { return ( <SiteBoilerPlate> <Skeleton> <ProfileCards items={["profile-card", "profile-card extra"]} /> </Skeleton> </SiteBoilerPlate> ); } }); module.exports = index;
/** * @jsx React.DOM */ /* Requiring dependencies for demo purposes, this should be done only when required */ var React = require('React'); var jquery = require('../vendor/jquery-2.1.0.js'); var UnderScore = require('underscore/underscore.js'); var Backbone = require('backbone/backbone.js'); var Reactbone = require('../patch/react.backbone.js'); var SiteBoilerPlate = require('../views/core/SiteBoilerPlate.js'); var Skeleton = require('../views/Skeleton/Skeleton.js'); var ProfileCards = require('../views/ProfileCards/ProfileCards.js'); var Router = require('../routes/Routes.js'); var index = React.createClass({ componentDidMount: function() { /** * This runs on the client side. Add Jquery and Underscore to the window. * Initialize Backbone app once the dependencies are set up. */ }, render: function() { return ( <SiteBoilerPlate> <Skeleton> <ProfileCards items={["profile-card", "profile-card extra"]} /> </Skeleton> </SiteBoilerPlate> ); } }); module.exports = index;
Allow searching restricted courses by key
""" Django admin page for embargo models """ import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blacklisting/whitelisting specific IP addresses""" form = IPFilterForm fieldsets = ( (None, { 'fields': ('enabled', 'whitelist', 'blacklist'), 'description': textwrap.dedent("""Enter specific IP addresses to explicitly whitelist (not block) or blacklist (block) in the appropriate box below. Separate IP addresses with a comma. Do not surround with quotes. """) }), ) class CountryAccessRuleInline(admin.StackedInline): """Inline editor for country access rules. """ model = CountryAccessRule extra = 1 def has_delete_permission(self, request, obj=None): return True class RestrictedCourseAdmin(admin.ModelAdmin): """Admin for configuring course restrictions. """ inlines = [CountryAccessRuleInline] form = RestrictedCourseForm search_fields = ('course_key',) admin.site.register(IPFilter, IPFilterAdmin) admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
""" Django admin page for embargo models """ import textwrap from config_models.admin import ConfigurationModelAdmin from django.contrib import admin from .forms import IPFilterForm, RestrictedCourseForm from .models import CountryAccessRule, IPFilter, RestrictedCourse class IPFilterAdmin(ConfigurationModelAdmin): """Admin for blacklisting/whitelisting specific IP addresses""" form = IPFilterForm fieldsets = ( (None, { 'fields': ('enabled', 'whitelist', 'blacklist'), 'description': textwrap.dedent("""Enter specific IP addresses to explicitly whitelist (not block) or blacklist (block) in the appropriate box below. Separate IP addresses with a comma. Do not surround with quotes. """) }), ) class CountryAccessRuleInline(admin.StackedInline): """Inline editor for country access rules. """ model = CountryAccessRule extra = 1 def has_delete_permission(self, request, obj=None): return True class RestrictedCourseAdmin(admin.ModelAdmin): """Admin for configuring course restrictions. """ inlines = [CountryAccessRuleInline] form = RestrictedCourseForm admin.site.register(IPFilter, IPFilterAdmin) admin.site.register(RestrictedCourse, RestrictedCourseAdmin)
Fix broken my playlists dropdown
require('../../navbar.js'); require('../../auth.js'); import { sendGoogleAnalyticsPageView, sendGoogleAnalyticsEvent } from '../../googleAnalytics.js'; $('#myPlaylistsDropdown a').on('click', function () { var selectedVal = $(this).html(); $('#playlist-list-my-playlists').hide(); $('#playlist-list-recommended-for-me').hide(); $('#playlist-list-recommended-by-me').hide(); if (selectedVal === 'All Playlists') { $('#playlist-list-my-playlists').show(); $('#playlist-list-recommended-for-me').show(); $('#playlist-list-recommended-by-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show All Playlists'); } else if (selectedVal === 'My Playlists') { $('#playlist-list-my-playlists').show(); sendGoogleAnalyticsEvent('Playlists', 'show My Playlists'); } else if (selectedVal === 'Shared with Me') { $('#playlist-list-recommended-for-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show Recommended for Me'); } else if (selectedVal === 'Shared by Me') { $('#playlist-list-recommended-by-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show Recommended by Me'); } $('#myPlaylistsDropdown button').html(selectedVal); }); sendGoogleAnalyticsPageView();
require('../../navbar.js'); require('../../auth.js'); import { sendGoogleAnalyticsPageView, sendGoogleAnalyticsEvent } from '../../googleAnalytics.js'; $('#myPlaylistsDropdown a').on('click', function () { var selectedVal = $(this).html(); $('#playlist-list-my-playlists').hide(); $('#playlist-list-recommended-for-me').hide(); $('#playlist-list-recommended-by-me').hide(); if (selectedVal === 'All Playlists') { $('#playlist-list-my-playlists').show(); $('#playlist-list-recommended-for-me').show(); $('#playlist-list-recommended-by-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show All Playlists'); } else if (selectedVal === 'My Playlists') { $('#playlist-list-my-playlists').show(); sendGoogleAnalyticsEvent('Playlists', 'show My Playlists'); } else if (selectedVal === 'Recommended for Me') { $('#playlist-list-recommended-for-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show Recommended for Me'); } else if (selectedVal === 'Recommended by Me') { $('#playlist-list-recommended-by-me').show(); sendGoogleAnalyticsEvent('Playlists', 'show Recommended by Me'); } $('#myPlaylistsDropdown button').html(selectedVal); }); sendGoogleAnalyticsPageView();
Fix GH-115 Cannot select documents with checkboxes on DNN 9
function r7d_selectDocument(documentId, checked, value) { var values = JSON.parse(value); var index = values.indexOf(documentId); if (checked) { if (index < 0) { values.push(documentId); } } else { if (index >= 0) { values.splice(index, 1); } } return JSON.stringify(values); } function r7d_getModuleId(target) { var c = $(target).closest("div.DnnModule").attr("class"); var moduleId = c.match("DnnModule-(\\d+)")[1]; return moduleId; } function r7d_selectDocument2(target) { var documentId = $(target).data("document-id"); var moduleId = r7d_getModuleId(target); var field = document.getElementById("dnn_ctr" + moduleId + "_ViewDocuments_hiddenSelectedDocuments"); field.value = r7d_selectDocument(documentId, target.checked, field.value); } function r7d_selectDeselectAll(target) { var moduleId = r7d_getModuleId(target); $("div.DnnModule-" + moduleId + " .EditCell input[type='checkbox']").prop("checked", target.checked).trigger("change"); }
function r7d_selectDocument(documentId, checked, value) { var values = JSON.parse(value); var index = values.indexOf(documentId); if (checked) { if (index < 0) { values.push(documentId); } } else { if (index >= 0) { values.splice(index, 1); } } return JSON.stringify(values); } function r7d_getModuleId(target) { var c = $(target).closest("div.DnnModule").attr("class"); return c.substr(c.lastIndexOf("DnnModule-") + 10); } function r7d_selectDocument2(target) { var documentId = $(target).data("document-id"); var moduleId = r7d_getModuleId(target); var field = document.getElementById("dnn_ctr" + moduleId + "_ViewDocuments_hiddenSelectedDocuments"); field.value = r7d_selectDocument(documentId, target.checked, field.value); } function r7d_selectDeselectAll(target) { var moduleId = r7d_getModuleId(target); $("div.DnnModule-" + moduleId + " .EditCell input[type='checkbox']").prop("checked", target.checked).trigger("change"); }
Replace deprecated By.name locators with By.xpath
package com.testdroid.appium.ios.sample; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.testdroid.appium.BaseIOSTest; import java.util.concurrent.TimeUnit; public class IosAppiumExampleTest extends BaseIOSTest { @BeforeClass public void setUp() throws Exception { setUpTest(); } @AfterClass public void tearDown() { quitAppiumSession(); } @Test public void mainPageTest() throws Exception { wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.findElement(By.xpath("//*[contains(@name, 'answer1')]")).click(); WebElement element = wd.findElement(By.xpath("//*[contains(@name, 'userName')]")); takeScreenshot("example_screenshot"); element.click(); element.sendKeys("Testdroid"); wd.findElement(By.xpath("//*[contains(@name, 'Return')]")).click(); wd.findElement(By.xpath("//*[contains(@name, 'sendAnswer')]")).click(); } }
package com.testdroid.appium.ios.sample; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.testdroid.appium.BaseIOSTest; import java.util.concurrent.TimeUnit; public class IosAppiumExampleTest extends BaseIOSTest { @BeforeClass public void setUp() throws Exception { setUpTest(); } @AfterClass public void tearDown() { quitAppiumSession(); } @Test public void mainPageTest() throws Exception { wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); wd.findElement(By.name("answer1")).click(); WebElement element = wd.findElement(By.name("userName")); takeScreenshot("example_screenshot"); element.click(); element.sendKeys("Testdroid"); wd.findElement(By.name("Return")).click(); wd.findElement(By.name("sendAnswer")).click(); } }
Change version and license for 0.2
from setuptools import setup setup(name = 'OWSLib', version = '0.2.0', description = 'OGC Web Service utility library', license = 'BSD', keywords = 'gis ogc ows wfs wms capabilities metadata', author = 'Sean Gillies', author_email = 'sgillies@frii.com', maintainer = 'Sean Gillies', maintainer_email = 'sgillies@frii.com', url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib', packages = ['owslib'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: GIS', ], )
from setuptools import setup setup(name = 'OWSLib', version = '0.1.0', description = 'OGC Web Service utility library', license = 'GPL', keywords = 'gis ogc ows wfs wms capabilities metadata', author = 'Sean Gillies', author_email = 'sgillies@frii.com', maintainer = 'Sean Gillies', maintainer_email = 'sgillies@frii.com', url = 'http://trac.gispython.org/projects/PCL/wiki/OwsLib', packages = ['owslib'], classifiers = [ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering :: GIS', ], )
Add navigation to system settings and updates
package de.philipphager.disclosure.feature.navigation; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.provider.Settings; import de.philipphager.disclosure.database.app.model.App; import de.philipphager.disclosure.database.library.model.Library; import de.philipphager.disclosure.feature.app.detail.DetailActivity; import de.philipphager.disclosure.feature.home.HomeActivity; import de.philipphager.disclosure.feature.library.detail.LibraryOverviewActivity; import javax.inject.Inject; public class Navigator { private Activity activity; @SuppressWarnings("PMD.UnnecessaryConstructor") @Inject public Navigator() { // Needed for dagger injection. } public void setActivity(Activity activity) { this.activity = activity; } public void toHome() { activity.startActivity(HomeActivity.launch(activity)); } public void toAppDetail(App app) { activity.startActivity(DetailActivity.launch(activity, app)); } public void toLibraryOverview(Library library) { activity.startActivity(LibraryOverviewActivity.launch(activity, library)); } public void toAppSystemSettings(String packageName) { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", packageName, null)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } public void toSystemUpdates() { Intent intent = new Intent("android.settings.SYSTEM_UPDATE_SETTINGS"); activity.startActivity(intent); } }
package de.philipphager.disclosure.feature.navigation; import android.app.Activity; import de.philipphager.disclosure.database.app.model.App; import de.philipphager.disclosure.database.library.model.Library; import de.philipphager.disclosure.feature.app.detail.DetailActivity; import de.philipphager.disclosure.feature.home.HomeActivity; import de.philipphager.disclosure.feature.library.detail.LibraryOverviewActivity; import javax.inject.Inject; public class Navigator { private Activity activity; @SuppressWarnings("PMD.UnnecessaryConstructor") @Inject public Navigator() { // Needed for dagger injection. } public void setActivity(Activity activity) { this.activity = activity; } public void toHome() { activity.startActivity(HomeActivity.launch(activity)); } public void toAppDetail(App app) { activity.startActivity(DetailActivity.launch(activity, app)); } public void toLibraryOverview(Library library) { activity.startActivity(LibraryOverviewActivity.launch(activity, library)); } }
Reset registry modal step on each open The modal was persisting the selection state between multiple closing and openings of the modal. This now resets the selection state. rancher/rancher#27339
import { inject as service } from '@ember/service'; import { get } from '@ember/object'; import { alias } from '@ember/object/computed'; import Component from '@ember/component'; import ModalBase from 'shared/mixins/modal-base'; import layout from './template'; import { eachLimit } from 'async'; export default Component.extend(ModalBase, { growl: service(), layout, classNames: ['medium-modal'], selection: {}, resources: alias('modalService.modalOpts.resources'), init() { this._super(...arguments); this.selection = {}; }, actions: { drain() { const nodeDrainInput = { ...get(this, 'selection') }; const resources = get(this, 'resources').slice(); eachLimit(resources, 5, (resource, cb) => { if ( !resource ) { return cb(); } resource.doAction('drain', nodeDrainInput).finally(cb); }); this.send('cancel'); }, }, });
import { inject as service } from '@ember/service'; import { get } from '@ember/object'; import { alias } from '@ember/object/computed'; import Component from '@ember/component'; import ModalBase from 'shared/mixins/modal-base'; import layout from './template'; import { eachLimit } from 'async'; export default Component.extend(ModalBase, { growl: service(), layout, classNames: ['medium-modal'], selection: {}, resources: alias('modalService.modalOpts.resources'), actions: { drain() { const nodeDrainInput = { ...get(this, 'selection') }; const resources = get(this, 'resources').slice(); eachLimit(resources, 5, (resource, cb) => { if ( !resource ) { return cb(); } resource.doAction('drain', nodeDrainInput).finally(cb); }); this.send('cancel'); }, }, });
Fix: Add strong attributes of Sizebay
package sizebay.catalog.client.model; import java.io.Serializable; import java.util.Map; import lombok.*; import lombok.experimental.Accessors; @Data @Accessors(chain = true) @NoArgsConstructor public class ProductBasicInformation implements Serializable { long id; @NonNull String name; @NonNull String permalink; String genderTheWearWasDesignedFor; String coverImage; int isShoe; @Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead @Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead @Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead @Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead String categoryName; String modelingName; @Deprecated boolean bottomOnly; ClothesType clothesType; String sizeType; Boolean status; Product.AgeGroupEnum ageGroup = null; Map<String, ModelingSizeMeasures> measures; Boolean accessory; int strongBrandId; String strongBrandName; int strongCategoryTypeId; String strongCategoryTypeName; int strongCategoryId; String strongCategoryName; int strongSubcategoryId; String strongSubcategoryName; int strongModelId; String strongModelName; }
package sizebay.catalog.client.model; import java.io.Serializable; import java.util.Map; import lombok.*; import lombok.experimental.Accessors; @Data @Accessors(chain = true) @NoArgsConstructor public class ProductBasicInformation implements Serializable { long id; @NonNull String name; @NonNull String permalink; String genderTheWearWasDesignedFor; String coverImage; int isShoe; @Deprecated int szbMainCategoryId; // FIXME Remove this field after legacy virtual dead @Deprecated int szbSubCategoryId; // FIXME Remove this field after legacy virtual dead @Deprecated String szbMainCategoryName = null; // FIXME Remove this field after legacy virtual dead @Deprecated String szbSubCategoryName = null; // FIXME Remove this field after legacy virtual dead String categoryName; String modelingName; @Deprecated boolean bottomOnly; ClothesType clothesType; String sizeType; Boolean status; Product.AgeGroupEnum ageGroup = null; Map<String, ModelingSizeMeasures> measures; Boolean accessory; }
Improve schema version error message
package com.faforever.api.db; import com.faforever.api.config.ApplicationProfile; import com.faforever.api.config.FafApiProperties; import org.springframework.context.annotation.Profile; import org.springframework.core.PriorityOrdered; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import javax.annotation.PostConstruct; import java.util.Objects; @Component @Profile("!" + ApplicationProfile.INTEGRATION_TEST) public class SchemaVersionVerifier implements PriorityOrdered { private final SchemaVersionRepository schemaVersionRepository; private final FafApiProperties properties; public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository, FafApiProperties properties) { this.schemaVersionRepository = schemaVersionRepository; this.properties = properties; } @PostConstruct public void postConstruct() { String requiredVersion = properties.getDatabase().getSchemaVersion(); String actualVersion = schemaVersionRepository.findMaxVersion() .orElseThrow(() -> new IllegalStateException("No database version is available")); Assert.state(Objects.equals(requiredVersion, actualVersion), String.format("Database version is '%s' but this software requires '%s'. If you are sure that this version is " + "compatible, you can override the expected version by setting the environment variable DATABASE_SCHEMA_VERSION.", actualVersion, requiredVersion)); } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
package com.faforever.api.db; import com.faforever.api.config.ApplicationProfile; import com.faforever.api.config.FafApiProperties; import org.springframework.context.annotation.Profile; import org.springframework.core.PriorityOrdered; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import javax.annotation.PostConstruct; import java.util.Objects; @Component @Profile("!" + ApplicationProfile.INTEGRATION_TEST) public class SchemaVersionVerifier implements PriorityOrdered { private final SchemaVersionRepository schemaVersionRepository; private final FafApiProperties properties; public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository, FafApiProperties properties) { this.schemaVersionRepository = schemaVersionRepository; this.properties = properties; } @PostConstruct public void postConstruct() { String requiredVersion = properties.getDatabase().getSchemaVersion(); String actualVersion = schemaVersionRepository.findMaxVersion() .orElseThrow(() -> new IllegalStateException("No database version is available")); Assert.state(Objects.equals(requiredVersion, actualVersion), String.format("Database version is '%s' but this software requires '%s'", actualVersion, requiredVersion)); } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
Remove lineHeight from unitless values
// Taken from: // https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js const unitlessNumbers = { boxFlex: true, boxFlexGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, fontWeight: true, lineClamp: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true, // SVG-related fillOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true, scaleX: true, scaleY: true, scaleZ: true, scale: true, }; const normalizeValue = (property, value) => { if (!unitlessNumbers[property] && typeof value === 'number') { return `${value}px`; // TODO(lmr): what if we used `em` or `rem` here? } return value; }; module.exports = normalizeValue;
// Taken from: // https://github.com/necolas/react-native-web/blob/master/src/apis/StyleSheet/normalizeValue.js const unitlessNumbers = { boxFlex: true, boxFlexGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, widows: true, zIndex: true, zoom: true, // SVG-related fillOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true, scaleX: true, scaleY: true, scaleZ: true, scale: true, }; const normalizeValue = (property, value) => { if (!unitlessNumbers[property] && typeof value === 'number') { return `${value}px`; // TODO(lmr): what if we used `em` or `rem` here? } return value; }; module.exports = normalizeValue;
Fix site label decorate example - specify correct accessors and pad x-domain
var width = 500, height = 250; var container = d3.select('#decorate-labels') .append('svg') .attr({'width': width, 'height': height}); var dataGenerator = fc.data.random.financial() .startDate(new Date(2014, 1, 1)); var data = dataGenerator(10); var xScale = fc.scale.dateTime() .domain(fc.util.extent().fields('date').pad(0.1)(data)) .range([0, width]); var yScale = d3.scale.linear() .domain(fc.util.extent().fields(['high', 'low'])(data)) .range([height, 0]); //START var color = d3.scale.category10(); var point = fc.series.point() .xScale(xScale) .yScale(yScale) .xValue(function(d) { return d.date; }) .yValue(function(d) { return d.close; }) .decorate(function(s) { s.enter() .append('text') .style('text-anchor', 'middle') .attr('transform', 'translate(0, -10)') .text(function(d) { return d3.format('.2f')(d.close); }); }); //END container.append('g') .datum(data) .call(point);
var width = 500, height = 250; var container = d3.select('#decorate-labels') .append('svg') .attr({'width': width, 'height': height}); var dataGenerator = fc.data.random.financial() .startDate(new Date(2014, 1, 1)); var data = dataGenerator(10); var xScale = fc.scale.dateTime() .domain(fc.util.extent().fields('date')(data)) .range([0, width]); var yScale = d3.scale.linear() .domain(fc.util.extent().fields(['high', 'low'])(data)) .range([height, 0]); //START var color = d3.scale.category10(); var point = fc.series.point() .xScale(xScale) .yScale(yScale) .decorate(function(s) { s.enter() .append('text') .style('text-anchor', 'middle') .attr('transform', 'translate(0, -10)') .text(function(d) { return d3.format('.2f')(d.close); }); }); //END container.append('g') .datum(data) .call(point);
Use new 'tags' property instead of old 'tagged' property on posts
import React from 'react'; import Tags from '../Tags'; import StatusButton from '../StatusButton'; class ReviewBlock extends React.Component { setStatus(status) { this.props.onUpdate(this.props.post.id, { status: status }); } render() { const post = this.props.post; return ( <div> <ul className="form-actions -inline" style={{'marginTop': 0}}> <li><StatusButton type="accepted" label="accept" status={post.status} setStatus={this.setStatus.bind(this)}/></li> <li><StatusButton type="rejected" label="reject" status={post.status} setStatus={this.setStatus.bind(this)}/></li> </ul> <ul className="form-actions -inline"> <li><button className="button delete -tertiary" onClick={e => this.props.deletePost(post['id'], e)}>Delete</button></li> </ul> {post.status === 'accepted' ? <Tags id={post.id} tagged={post.tags} onTag={this.props.onTag} /> : null} </div> ) } } export default ReviewBlock;
import React from 'react'; import Tags from '../Tags'; import StatusButton from '../StatusButton'; class ReviewBlock extends React.Component { setStatus(status) { this.props.onUpdate(this.props.post.id, { status: status }); } render() { const post = this.props.post; return ( <div> <ul className="form-actions -inline" style={{'marginTop': 0}}> <li><StatusButton type="accepted" label="accept" status={post.status} setStatus={this.setStatus.bind(this)}/></li> <li><StatusButton type="rejected" label="reject" status={post.status} setStatus={this.setStatus.bind(this)}/></li> </ul> <ul className="form-actions -inline"> <li><button className="button delete -tertiary" onClick={e => this.props.deletePost(post['id'], e)}>Delete</button></li> </ul> {post.status === 'accepted' ? <Tags id={post.id} tagged={post.tagged} onTag={this.props.onTag} /> : null} </div> ) } } export default ReviewBlock;
Add error field to expected JSON
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class StoriesTestCase(TestCase): fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json'] def setUp(self): self.expected_json = """" { error": { "error_status": false, "error_name": null, "error_text": null, "error_level": null }, { "story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..." } }""" def test_url_endpoint(self): url = reverse('story-details', kwargs={'id': '1'}) self.assertEqual(url, '/stories/1') def test_json_equals(self): c = Client() response = c.get(reverse('story-details', kwargs={'id': '1'})).content parsed_answer = json.loads(response) expected_answer = json.loads(self.expected_json) self.assertTrue(parsed_answer == expected_answer)
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class StoriesTestCase(TestCase): fixtures = ['whats_fresh_api/tests/testdata/test_fixtures.json'] def setUp(self): self.expected_json = """ { "story": "These are the voyages of the Starfish Enterblub; her five year mission -- to seek out new fish and new fishilizations..." }""" def test_url_endpoint(self): url = reverse('story-details', kwargs={'id': '1'}) self.assertEqual(url, '/stories/1') def test_json_equals(self): c = Client() response = c.get(reverse('story-details', kwargs={'id': '1'})).content parsed_answer = json.loads(response) expected_answer = json.loads(self.expected_json) self.assertTrue(parsed_answer == expected_answer)
Reduce fetch size to 5000. Don't run job on startup.
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=5000): print("Running twinsy finder...") fetched_tweets = fetch_tweets('Kanye', fetch_size=fetch_size) tweets = dig_for_twins(fetched_tweets) if tweets: print("Twins found, updating status.") update_status(tweets) else: print("No twins found.") if __name__ == '__main__': print("Starting scheduler") sched.start()
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=10000): print("Running twinsy finder...") fetched_tweets = fetch_tweets('Kanye', fetch_size=fetch_size) tweets = dig_for_twins(fetched_tweets) if tweets: print("Twins found, updating status.") update_status(tweets) else: print("No twins found.") if __name__ == '__main__': twinsy_finder() print("Starting scheduler") sched.start()
Add in doRequest for the TradeApi Currently this code is absolutely useless. Just returns null
package com.popebp.bitcoin.exchange.btce; import org.json.JSONObject; public class BTCe { public static final String API_URL = "https://btc-e.com/tapi"; private String apiKey = null; private String apiSecret = null; /* * Needs * o Method that builds the QueryParams and signs * o Method that builds the Headers * o Method that takes in api path, query params, headers and makes request (returns JSONObject) * o ResultFactory that builds each result type */ public BTCe(String key, String secret) { this.apiKey = key; this.apiSecret = secret; } private JSONObject doRequest() { // TODO: This will make the request, based on the endpoint return null; } public Result getInfo() { return new GetInfoResult(); } public Result getTransactionHistory(Parameters params) { return new TransactionHistoryResult(); } public Result getTradeHistory(Parameters params) { return new TradeHistoryResult(); } public Result getActiveOrders(Parameters params) { return new ActiveOrdersResult(); } public Result doTrade(Parameters params) { return new TradeResult(); } public Result doCancelOrder(Parameters params) { return new CancelOrderResult(); } }
package com.popebp.bitcoin.exchange.btce; public class BTCe { public static final String API_URL = "https://btc-e.com/tapi"; private String apiKey = null; private String apiSecret = null; /* * Needs * o Method that builds the QueryParams and signs * o Method that builds the Headers * o Method that takes in api path, query params, headers and makes request (returns JSONObject) * o ResultFactory that builds each result type */ public BTCe(String key, String secret) { this.apiKey = key; this.apiSecret = secret; } public Result getInfo() { return new GetInfoResult(); } public Result getTransactionHistory(Parameters params) { return new TransactionHistoryResult(); } public Result getTradeHistory(Parameters params) { return new TradeHistoryResult(); } public Result getActiveOrders(Parameters params) { return new ActiveOrdersResult(); } public Result doTrade(Parameters params) { return new TradeResult(); } public Result doCancelOrder(Parameters params) { return new CancelOrderResult(); } }
Fix SSL Warnings with old python versions Signed-off-by: Xuanwo <9d9ffaee821234cdfed458cf06eb6f407f8dbe47@yunify.com>
# coding:utf-8 from sys import version_info from setuptools import setup, find_packages from qingstor.qsctl import __version__ install_requires = [ 'argparse >= 1.1', 'PyYAML >= 3.1', 'qingstor-sdk >= 2.1.0', 'docutils >= 0.10', 'tqdm >= 4.0.0' ] if version_info[:3] < (2, 7, 9): install_requires.append("requests[security]") setup( name='qsctl', version=__version__, description='Advanced command line tool for QingStor.', long_description=open('README.rst', 'rb').read().decode('utf-8'), keywords='yunify qingcloud qingstor qsctl object_storage', author='QingStor Dev Team', author_email='qs-devel@yunify.com', url='https://www.qingstor.com', scripts=['bin/qsctl', 'bin/qsctl.cmd'], packages=find_packages('.'), package_dir={'qsctl': 'qingstor'}, namespace_packages=['qingstor'], include_package_data=True, install_requires=install_requires )
# coding:utf-8 from setuptools import setup, find_packages from qingstor.qsctl import __version__ setup( name='qsctl', version=__version__, description='Advanced command line tool for QingStor.', long_description=open('README.rst', 'rb').read().decode('utf-8'), keywords='yunify qingcloud qingstor qsctl object_storage', author='QingStor Dev Team', author_email='qs-devel@yunify.com', url='https://www.qingstor.com', scripts=['bin/qsctl', 'bin/qsctl.cmd'], packages=find_packages('.'), package_dir={'qsctl': 'qingstor'}, namespace_packages=['qingstor'], include_package_data=True, install_requires=[ 'argparse >= 1.1', 'PyYAML >= 3.1', 'qingstor-sdk >= 2.1.0', 'docutils >= 0.10', 'tqdm >= 4.0.0' ])
Quit app on window close
const {app, BrowserWindow, protocol} = require('electron') require('electron-debug')({ showDevTools: true, enable: true }) var path = require('path') var main = null app.on('ready', function () { main = new BrowserWindow({ height: 720, resizable: true, title: 'sciencefair', width: 1050, titleBarStyle: 'hidden', fullscreen: false, icon: './icon/logo.png', show: false }) main.setMenu(null) main.maximize() main.loadURL(path.join('file://', __dirname, '/app/index.html')) // hack to avoid a blank white window showing briefly at startup // hide the window until content is loaded main.webContents.on('did-finish-load', () => { setTimeout(() => main.show(), 40) }) main.on('close', event => { main.webContents.send('quitting') }) main.on('closed', function () { main = null }) protocol.registerFileProtocol('sciencefair', (request, callback) => { console.log(request.url) callback() }, error => { if (error) console.error('Failed to register protocol') }) }) app.on('window-all-closed', () => app.quit())
const {app, BrowserWindow, protocol} = require('electron') require('electron-debug')({ showDevTools: true, enable: true }) var path = require('path') var main = null app.on('ready', function () { main = new BrowserWindow({ height: 720, resizable: true, title: 'sciencefair', width: 1050, titleBarStyle: 'hidden', fullscreen: false, icon: './icon/logo.png', show: false }) main.setMenu(null) main.maximize() main.loadURL(path.join('file://', __dirname, '/app/index.html')) // hack to avoid a blank white window showing briefly at startup // hide the window until content is loaded main.webContents.on('did-finish-load', () => { setTimeout(() => main.show(), 40) }) main.on('close', event => { main.webContents.send('quitting') }) main.on('closed', function () { main = null }) protocol.registerFileProtocol('sciencefair', (request, callback) => { console.log(request.url) callback() }, error => { if (error) console.error('Failed to register protocol') }) })
Add asserts to check that cleanup did occur
import Ember from 'ember'; import setupMirage from '../helpers/setup-mirage'; import { moduleFor, test } from 'ember-qunit'; const { run } = Ember; moduleFor('copyable', 'Integration | Copyable | failure', { integration: true, beforeEach() { return setupMirage(this, { async: true }); }, afterEach() { this.server.shutdown(); } }); test('it handles async failures', async function(assert) { assert.expect(2); this.server.get('/foos/1', { errors: ['There was an error'] }, 500); let model; await run(async () => { model = await this.store.findRecord('bar', 1); }); await run(async () => { try { await model.copy(true); } catch (e) { let models = this.store.peekAll('bar'); assert.ok(e); assert.equal(models.get('length'), 1, 'All created copies were cleaned up'); } }); }); test('it handles task cancellation', async function(assert) { assert.expect(2); let model; await run(async () => { model = await this.store.findRecord('bar', 1); }); await run(async () => { try { let taskInstance = model.copy(true); taskInstance.cancel(); await taskInstance; } catch (e) { let models = this.store.peekAll('bar'); assert.ok(e); assert.equal(models.get('length'), 1, 'All created copies were cleaned up'); } }); });
import Ember from 'ember'; import setupMirage from '../helpers/setup-mirage'; import { moduleFor, test } from 'ember-qunit'; const { run } = Ember; moduleFor('copyable', 'Integration | Copyable | failure', { integration: true, beforeEach() { return setupMirage(this, { async: true }); }, afterEach() { this.server.shutdown(); } }); test('it handles async failures', async function(assert) { assert.expect(1); this.server.get('/foos/1', { errors: ['There was an error'] }, 500); let model; await run(async () => { model = await this.store.findRecord('bar', 1); }); await run(async () => { try { await model.copy(true); } catch (e) { assert.ok(e); } }); }); test('it handles task cancellation', async function(assert) { assert.expect(1); let model; await run(async () => { model = await this.store.findRecord('bar', 1); }); await run(async () => { try { let taskInstance = model.copy(true); taskInstance.cancel(); await taskInstance; } catch (e) { assert.ok(e); } }); });
Correct soil life calculation for waila(now says 100% when full)
package com.ferreusveritas.dynamictrees.compat; import java.util.List; import com.ferreusveritas.dynamictrees.blocks.BlockRooty; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; public class WailaRootyHandler implements IWailaDataProvider { @Override public List<String> getWailaBody(ItemStack itemStack, List<String> tooltip, IWailaDataAccessor accessor, IWailaConfigHandler config) { IBlockState state = accessor.getWorld().getBlockState(accessor.getPosition()); if(state.getBlock() instanceof BlockRooty) { BlockRooty rooty = (BlockRooty) state.getBlock(); int life = rooty.getSoilLife(state, accessor.getWorld(), accessor.getPosition()); tooltip.add("Soil Life: " + MathHelper.floor(life * 100 / 15) + "%"); } return tooltip; } }
package com.ferreusveritas.dynamictrees.compat; import java.util.List; import com.ferreusveritas.dynamictrees.blocks.BlockRooty; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; import net.minecraft.block.state.IBlockState; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; public class WailaRootyHandler implements IWailaDataProvider { @Override public List<String> getWailaBody(ItemStack itemStack, List<String> tooltip, IWailaDataAccessor accessor, IWailaConfigHandler config) { IBlockState state = accessor.getWorld().getBlockState(accessor.getPosition()); if(state.getBlock() instanceof BlockRooty) { BlockRooty rooty = (BlockRooty) state.getBlock(); int life = rooty.getSoilLife(state, accessor.getWorld(), accessor.getPosition()); tooltip.add("Soil Life: " + MathHelper.floor(life * 6.25f) + "%"); } return tooltip; } }
Handle a missing dictionary exception
#!/usr/bin/python import argparse from glob import glob import random import os.path from contextlib import contextmanager @contextmanager def cd(path): old_dir = os.getcwd() os.chdir(path) yield os.chdir(old_dir) _dir = os.path.dirname(os.path.abspath(__file__)) def available_languages(): with cd(_dir + "/dictionaries/"): langs = list(n.replace(".txt", "") for n in glob("*.txt")) return sorted(langs) def generate(lang, num): try: return [x.strip() for x in sorted(random.sample(list(open('%s/dictionaries/%s.txt' % (_dir, lang))), num))] except: return ["Dictionary ", lang, " not found. Use the '-L' flag to list available dictionaries."] def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--language', default = "en", help = "Show results from which language") parser.add_argument('-L', '--list', action = "store_true", help = "Show available languages") parser.add_argument('-n', '--number', type = int, default = 12, help = "Number of results from which to choose") args = parser.parse_args() if args.list: print " ".join(available_languages()) else: print " ".join(generate(args.language, args.number)) if __name__ == "__main__": main()
#!/usr/bin/python import argparse from glob import glob import random import os.path from contextlib import contextmanager @contextmanager def cd(path): old_dir = os.getcwd() os.chdir(path) yield os.chdir(old_dir) _dir = os.path.dirname(os.path.abspath(__file__)) def available_languages(): with cd(_dir + "/dictionaries/"): langs = list(n.replace(".txt", "") for n in glob("*.txt")) return sorted(langs) def generate(lang, num): return [x.strip() for x in sorted(random.sample(list(open('%s/dictionaries/%s.txt' % (_dir, lang))), num))] def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--language', default = "en", help = "Show results from which language") parser.add_argument('-L', '--list', action = "store_true", help = "Show available languages") parser.add_argument('-n', '--number', type = int, default = 12, help = "Number of results from which to choose") args = parser.parse_args() if args.list: print " ".join(available_languages()) else: print " ".join(generate(args.language, args.number)) if __name__ == "__main__": main()
ADD: Include DocBlock for updating member field
<?php namespace StudioBonito\Security\Extensions; use FieldList; use GridField; use GridFieldAddExistingSearchButton; /** * GroupMembersFieldExtension. * * @author Tom Densham <tom.densham@studiobonito.co.uk> * @copyright Studio Bonito Ltd. */ class GroupMembersFieldExtension extends \DataExtension { /** * Override default GridField config to use GridFieldAddExistingAutocompleter. * * @param FieldList $fields */ public function updateCMSFields(FieldList $fields) { if (class_exists('GridFieldAddExistingSearchButton')) { $gridField = $fields->dataFieldByName('Members'); if ($gridField instanceof GridField) { $gridFieldConfig = $gridField->getConfig(); $gridFieldConfig->removeComponentsByType('GridFieldAddExistingAutocompleter'); $gridFieldConfig->addComponent(new GridFieldAddExistingSearchButton()); } } } }
<?php namespace StudioBonito\Security\Extensions; use FieldList; use GridField; use GridFieldAddExistingSearchButton; /** * GroupMembersFieldExtension. * * @author Tom Densham <tom.densham@studiobonito.co.uk> * @copyright Studio Bonito Ltd. */ class GroupMembersFieldExtension extends \DataExtension { public function updateCMSFields(FieldList $fields) { if (class_exists('GridFieldAddExistingSearchButton')) { $gridField = $fields->dataFieldByName('Members'); if ($gridField instanceof GridField) { $gridFieldConfig = $gridField->getConfig(); $gridFieldConfig->removeComponentsByType('GridFieldAddExistingAutocompleter'); $gridFieldConfig->addComponent(new GridFieldAddExistingSearchButton()); } } } }
Put VirtualBox functions in alphabetical order
package virtualboxclient import ( "github.com/appropriate/go-virtualboxclient/vboxwebsrv" ) type VirtualBox struct { *vboxwebsrv.VboxPortType username string password string managedObjectId string } func New(username, password, url string) *VirtualBox { return &VirtualBox{ VboxPortType: vboxwebsrv.NewVboxPortType(url, false, nil), username: username, password: password, } } func (vb *VirtualBox) CreateHardDisk(format, location string) (*Medium, error) { vb.Logon() request := vboxwebsrv.IVirtualBoxcreateHardDisk{This: vb.managedObjectId, Format: format, Location: location} response, err := vb.IVirtualBoxcreateHardDisk(&request) if err != nil { return nil, err // TODO: Wrap the error } return &Medium{virtualbox: vb, managedObjectId: response.Returnval}, nil } func (vb *VirtualBox) Logon() error { if vb.managedObjectId != "" { // Already logged in return nil } request := vboxwebsrv.IWebsessionManagerlogon{ Username: vb.username, Password: vb.password, } response, err := vb.IWebsessionManagerlogon(&request) if err != nil { return err // TODO: Wrap the error } vb.managedObjectId = response.Returnval return nil }
package virtualboxclient import ( "github.com/appropriate/go-virtualboxclient/vboxwebsrv" ) type VirtualBox struct { *vboxwebsrv.VboxPortType username string password string managedObjectId string } func New(username, password, url string) *VirtualBox { return &VirtualBox{ VboxPortType: vboxwebsrv.NewVboxPortType(url, false, nil), username: username, password: password, } } func (vb *VirtualBox) Logon() error { if vb.managedObjectId != "" { // Already logged in return nil } request := vboxwebsrv.IWebsessionManagerlogon{ Username: vb.username, Password: vb.password, } response, err := vb.IWebsessionManagerlogon(&request) if err != nil { return err // TODO: Wrap the error } vb.managedObjectId = response.Returnval return nil } func (vb *VirtualBox) CreateHardDisk(format, location string) (*Medium, error) { vb.Logon() request := vboxwebsrv.IVirtualBoxcreateHardDisk{This: vb.managedObjectId, Format: format, Location: location} response, err := vb.IVirtualBoxcreateHardDisk(&request) if err != nil { return nil, err // TODO: Wrap the error } return &Medium{virtualbox: vb, managedObjectId: response.Returnval}, nil }
Work with nodes instead of elements. Simplify checks.
import init from './init'; import createFromHtml from '../util/create-from-html'; const DocumentFragmentPrototype = DocumentFragment.prototype; const slice = Array.prototype.slice; function decorateFragmentMethods (frag) { frag.appendChild = function (el) { return DocumentFragmentPrototype.appendChild.call(this, init(el)); }; frag.insertBefore = function (el, beforeEl) { return DocumentFragmentPrototype.insertBefore.call(this, init(el), beforeEl); }; frag.replaceChild = function (el, replacedEl) { return DocumentFragmentPrototype.replaceChild.call(this, init(el), replacedEl); }; frag.cloneNode = function () { var clone = DocumentFragmentPrototype.cloneNode.apply(this, arguments); decorateFragmentMethods(clone); var children = slice.call(clone.childNodes); for (var i = 0; i < children.length; i++) { init(children[i]); } return clone; }; } export default function (html) { var frag = document.createDocumentFragment(); decorateFragmentMethods(frag); if (typeof html === 'string') { let parent = createFromHtml(html); while (parent.firstChild) { frag.appendChild(parent.firstChild); } } else if (html) { frag.appendChild(html); } return frag; }
import init from './init'; import createFromHtml from '../util/create-from-html'; const DocumentFragmentPrototype = DocumentFragment.prototype; const slice = Array.prototype.slice; function decorateFragmentMethods (frag) { frag.appendChild = function (el) { return DocumentFragmentPrototype.appendChild.call(this, init(el)); }; frag.insertBefore = function (el, beforeEl) { return DocumentFragmentPrototype.insertBefore.call(this, init(el), beforeEl); }; frag.replaceChild = function (el, replacedEl) { return DocumentFragmentPrototype.replaceChild.call(this, init(el), replacedEl); }; frag.cloneNode = function () { var clone = DocumentFragmentPrototype.cloneNode.apply(this, arguments); decorateFragmentMethods(clone); var children = slice.call(clone.childNodes); for (var i = 0; i < children.length; i++) { init(children[i]); } return clone; }; } export default function (html) { var frag = document.createDocumentFragment(); decorateFragmentMethods(frag); if (html) { if (typeof html === 'string') { var par = createFromHtml(html); while (par.firstElementChild) { frag.appendChild(par.firstElementChild); } } else if (html.nodeType) { frag.appendChild(html); } } return frag; }
TST: Update to new databroker API.
from collections import defaultdict from bluesky.examples import stepscan, det, motor from bluesky.callbacks.broker import post_run, verify_files_saved from functools import partial def test_scan_and_get_data(fresh_RE, db): RE = fresh_RE RE.subscribe(db.insert) uid, = RE(stepscan(det, motor), group='foo', beamline_id='testing', config={}) hdr = db[uid] list(hdr.events()) def test_post_run(fresh_RE, db): RE = fresh_RE RE.subscribe(db.insert) output = defaultdict(list) def do_nothing(doctype, doc): output[doctype].append(doc) RE(stepscan(det, motor), subs={'stop': [post_run(do_nothing, db=db)]}) assert len(output) assert len(output['start']) == 1 assert len(output['stop']) == 1 assert len(output['descriptor']) == 1 assert len(output['event']) == 10 def test_verify_files_saved(fresh_RE, db): RE = fresh_RE RE.subscribe(db.insert) vfs = partial(verify_files_saved, db=db) RE(stepscan(det, motor), subs={'stop': vfs})
from collections import defaultdict from bluesky.examples import stepscan, det, motor from bluesky.callbacks.broker import post_run, verify_files_saved from functools import partial def test_scan_and_get_data(fresh_RE, db): RE = fresh_RE RE.subscribe(db.mds.insert) uid, = RE(stepscan(det, motor), group='foo', beamline_id='testing', config={}) hdr = db[uid] db.fetch_events(hdr) def test_post_run(fresh_RE, db): RE = fresh_RE RE.subscribe(db.mds.insert) output = defaultdict(list) def do_nothing(doctype, doc): output[doctype].append(doc) RE.ignore_callback_exceptions = False RE(stepscan(det, motor), subs={'stop': [post_run(do_nothing, db=db)]}) assert len(output) assert len(output['start']) == 1 assert len(output['stop']) == 1 assert len(output['descriptor']) == 1 assert len(output['event']) == 10 def test_verify_files_saved(fresh_RE, db): RE = fresh_RE RE.subscribe(db.mds.insert) vfs = partial(verify_files_saved, db=db) RE(stepscan(det, motor), subs={'stop': vfs})
Disable cache busting for dashboard
// Set the require.js configuration for your application. require.config({ // Initialize the application with the main application file. deps: ["main"], paths: { // Libraries. circliful: "/static/js/vendor/jquery.circliful.min", jquery: "/static/js/vendor/jquery-2.1.0.min", underscore: "/static/js/vendor/underscore.min", backbone: "/static/js/vendor/backbone.min", backbonequeryparams: "/static/js/vendor/backbone.queryparams", bootstrap: "/static/js/vendor/bootstrap.min", datatables: "/static/js/vendor/jquery.dataTables.min", datatablesbs3: "/static/js/vendor/datatables.bs3", moment: "/static/js/vendor/moment.min", sparkline: "/static/js/vendor/jquery.sparkline.min" }, // urlArgs: "bust=" + (new Date()).getTime(), shim: { backbone: { deps: ["underscore", "jquery"], exports: "Backbone" }, bootstrap: { deps: ["jquery"] }, datatables: { deps: ["jquery"] }, datatablesbs3: { deps: ["datatables"] }, backbonequeryparams: { deps: ["backbone"] }, sparkline: { deps: ["jquery"] } } });
// Set the require.js configuration for your application. require.config({ // Initialize the application with the main application file. deps: ["main"], paths: { // Libraries. circliful: "/static/js/vendor/jquery.circliful.min", jquery: "/static/js/vendor/jquery-2.1.0.min", underscore: "/static/js/vendor/underscore.min", backbone: "/static/js/vendor/backbone.min", backbonequeryparams: "/static/js/vendor/backbone.queryparams", bootstrap: "/static/js/vendor/bootstrap.min", datatables: "/static/js/vendor/jquery.dataTables.min", datatablesbs3: "/static/js/vendor/datatables.bs3", moment: "/static/js/vendor/moment.min", sparkline: "/static/js/vendor/jquery.sparkline.min" }, urlArgs: "bust=" + (new Date()).getTime(), shim: { backbone: { deps: ["underscore", "jquery"], exports: "Backbone" }, bootstrap: { deps: ["jquery"] }, datatables: { deps: ["jquery"] }, datatablesbs3: { deps: ["datatables"] }, backbonequeryparams: { deps: ["backbone"] }, sparkline: { deps: ["jquery"] } } });
Add Tviit and profile url patterns
from django.contrib.auth import views as auth_views from django.conf.urls import patterns, include, url from django.conf.urls import url from django.contrib import admin from . import views from tviserrys.settings import MEDIA_ROOT urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^tviit/', include('tviit.urls', namespace='tviit')), url(r'^admin/', admin.site.urls), url(r'^login/$', auth_views.login), url(r'^logout/$', auth_views.logout), url(r'^password_change/$', auth_views.password_change), url(r'^password_change/done/$', auth_views.password_change_done), url(r'^password_reset/$', auth_views.password_reset), url(r'^password_reset/done/$', auth_views.password_reset_done), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm), url(r'^reset/done/$', auth_views.password_reset_complete), url(r'^profile/', include('user_profile.urls', namespace='profile')), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT, 'show_indexes': False}), ]
from django.contrib.auth import views as auth_views from django.conf.urls import patterns, include, url from django.conf.urls import url from django.contrib import admin from . import views from tviserrys.settings import MEDIA_ROOT urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^admin/', admin.site.urls), url(r'^login/$', auth_views.login), url(r'^logout/$', auth_views.logout), url(r'^password_change/$', auth_views.password_change), url(r'^password_change/done/$', auth_views.password_change_done), url(r'^password_reset/$', auth_views.password_reset), url(r'^password_reset/done/$', auth_views.password_reset_done), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm), url(r'^reset/done/$', auth_views.password_reset_complete), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT, 'show_indexes': False}), ]
Improve performance of remove prefixedclasses
define(['jquery'], function() { 'use strict'; $.fn.removePrefixedClasses = function(prefix) { return this.each(function() { var el = $(this), classes = el[0].className.split(/\s+/), prefixes = prefix.split(/\s+/), toRemove = []; classes.forEach(function(cls) { prefixes.forEach(function(prefix) { if (cls.indexOf(prefix) === 0) { toRemove.push(cls); } }); }); el.removeClass(toRemove.join(' ')); }); }; });
define(['jquery'], function() { 'use strict'; $.fn.removePrefixedClasses = function(prefix) { return this.each(function() { var el = $(this), classes = el[0].className.split(/\s+/), prefixes = prefix.split(/\s+/); classes.forEach(function(cls) { prefixes.forEach(function(prefix) { if (cls.indexOf(prefix) === 0) { el.removeClass(cls); } }); }); }); }; });
Remove Gosched call as network I/O blocks.
package main import ( "net" "sync/atomic" ) const ( BufSize = 256 ) // Copy data between two connections. Return EOF on connection close. func Pipe(a, b net.Conn) error { done := make(chan error) var stop int32 defer func() { atomic.StoreInt32(&stop, 1) }() cp := func(r, w net.Conn) { var err error var n int buf := make([]byte, BufSize) for { if atomic.LoadInt32(&stop) == 1 { return } if n, err = r.Read(buf); err != nil { done <- err return } if _, err = w.Write(buf[:n]); err != nil { done <- err return } logger.Debugf("copied %d bytes from %s to %s", n, r.RemoteAddr(), w.RemoteAddr()) } } go cp(a, b) go cp(b, a) return <-done }
package main import ( "net" "runtime" "sync/atomic" ) const ( BufSize = 256 ) // Copy data between two connections. Return EOF on connection close. func Pipe(a, b net.Conn) error { done := make(chan error) var stop int32 defer func() { atomic.StoreInt32(&stop, 1) }() cp := func(r, w net.Conn) { var err error var n int buf := make([]byte, BufSize) for { if atomic.LoadInt32(&stop) == 1 { return } if n, err = r.Read(buf); err != nil { done <- err return } if _, err = w.Write(buf[:n]); err != nil { done <- err return } logger.Debugf("copied %d bytes from %s to %s", n, r.RemoteAddr(), w.RemoteAddr()) runtime.Gosched() } } go cp(a, b) go cp(b, a) return <-done }
Add tests using array for path
'use strict'; /* globals describe, it */ var assert = require('assert'); var get = require('../'); var isPlainObject = require('lodash.isplainobject'); describe('get', function(){ var o = { a: 'a', b: 'b', c: { c1: 'c1', c2: 'c2' } }; it('returns given object if path lookup totally fails', function(){ assert.equal(get('d', o), o); }); it('returns last found value if path lookup partially succeeds and then fails', function(){ assert.equal(get('c.c3', o), o.c); }); it('returns {} if given object isn\'t actually an object', function(){ assert(isPlainObject(get('foobar', 5))); }); it('path as String', function(){ assert.equal(get('b', o), 'b'); }); it('path as String with keys separated by dots', function(){ assert.equal(get('c.c2', o), 'c2'); }); it('path as [String]', function(){ assert.equal(get(['c', 'c2'], o), 'c2'); }); it('is curried', function(){ assert.equal(get('d')(o), o); }); });
'use strict'; /* globals describe, it */ var assert = require('assert'); var get = require('../'); var isPlainObject = require('lodash.isplainobject'); describe('get', function(){ var o = { a: 'a', b: 'b', c: { c1: 'c1', c2: 'c2' } }; it('returns the original object if path lookup completely fails', function(){ assert.equal(get('d', o), o); }); it('returns the last successful value if path lookup partially succeeds and then fails', function(){ assert.equal(get('c.c3', o), o.c); }); it('returns an empty object if given object isn\'t actually an object', function(){ assert(isPlainObject(get('foobar', 5))); }); it('accesses a path given as string with keys separated by dots', function(){ assert.equal(get('c.c2', o), 'c2'); }); it('is curried', function(){ // Redo the above tests in curreid form. assert.equal(get('d')(o), o); assert.equal(get('c.c3')(o), o.c); assert(isPlainObject(get('foobar')(5))); assert.equal(get('c.c2')(o), 'c2'); }); });
Allow `message` to be inherited from prototype
/*global define*/ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory) } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory() } else { // Browser globals (root is window) root.SubclassError = factory() } }(this, function () { var ErrorInheritor = function () {} function SubclassError (name, BaseError, props) { if (name === undefined) throw new Error('Name of subclass must be provided as first argument.') if (!(BaseError instanceof Function)) { props = BaseError BaseError = Error } ErrorInheritor.prototype = BaseError.prototype var e = function (message) { if (message) this.message = message // stack "hack" var goodStack = (new Error()).stack.split('\n') goodStack.splice(1, 1) goodStack[0] = name if (message) goodStack[0] += ': ' + message this.stack = goodStack.join('\n') } e.prototype = new ErrorInheritor() e.prototype.constructor = e e.prototype.name = name for (var prop in props) { e.prototype[prop] = props[prop] } return e } return SubclassError }))
/*global define*/ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory) } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory() } else { // Browser globals (root is window) root.SubclassError = factory() } }(this, function () { var ErrorInheritor = function () {} function SubclassError (name, BaseError, props) { if (name === undefined) throw new Error('Name of subclass must be provided as first argument.') if (!(BaseError instanceof Function)) { props = BaseError BaseError = Error } ErrorInheritor.prototype = BaseError.prototype var e = function (message) { this.message = message // stack "hack" var goodStack = (new Error()).stack.split('\n') goodStack.splice(1, 1) goodStack[0] = name if (message) goodStack[0] += ': ' + message this.stack = goodStack.join('\n') } e.prototype = new ErrorInheritor() e.prototype.constructor = e e.prototype.name = name for (var prop in props) { e.prototype[prop] = props[prop] } return e } return SubclassError }))
Enable async for security filter
package no.dusken.momus.config; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; public class WebInit implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext config = new AnnotationConfigWebApplicationContext(); config.register(ApplicationConfig.class, SecurityConfig.class); servletContext.addListener(new ContextLoaderListener(config)); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("momusapi", new DispatcherServlet()); dispatcher.setAsyncSupported(true); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/api/*"); // Add security to the servlet FilterRegistration.Dynamic securityFilter = servletContext .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class); securityFilter.setAsyncSupported(true); securityFilter.addMappingForUrlPatterns(null, false, "/*"); } }
package no.dusken.momus.config; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.DispatcherServlet; public class WebInit implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext config = new AnnotationConfigWebApplicationContext(); config.register(ApplicationConfig.class, SecurityConfig.class); servletContext.addListener(new ContextLoaderListener(config)); ServletRegistration.Dynamic dispatcher = servletContext.addServlet("momusapi", new DispatcherServlet()); dispatcher.setAsyncSupported(true); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/api/*"); // Add security to the servlet servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class) .addMappingForUrlPatterns(null, false, "/*"); } }
Use let instead of var
/** * Validate IMEI number. * The core logic is copied from https://github.com/madeinstefano/imei-validator/blob/gh-pages/imei.js * * @param value * @returns {Boolean} */ const validate = value => { if (!value) { return true; } if (!/^[0-9]{15}$/.test(value)) { return false; } let sum = 0; let factor = 2; let checkDigit, multipliedDigit; for (let i = 13, li = 0; i >= li; i--) { multipliedDigit = parseInt(value.charAt(i), 10) * factor; sum += (multipliedDigit >= 10 ? ((multipliedDigit % 10) + 1) : multipliedDigit); (factor === 1 ? factor++ : factor--); } checkDigit = ((10 - (sum % 10)) % 10); return !(checkDigit !== parseInt(value.charAt(14), 10)) }; const message = '<%= propertyName %> is not a valid IMEI.'; export default {validate, message};
/** * Validate IMEI number. * The core logic is copied from https://github.com/madeinstefano/imei-validator/blob/gh-pages/imei.js * * @param value * @returns {Boolean} */ const validate = value => { if (!value) { return true; } if (!/^[0-9]{15}$/.test(value)) { return false; } let sum = 0; let factor = 2; let checkDigit, multipliedDigit; for (var i = 13, li = 0; i >= li; i--) { multipliedDigit = parseInt(value.charAt(i), 10) * factor; sum += (multipliedDigit >= 10 ? ((multipliedDigit % 10) + 1) : multipliedDigit); (factor === 1 ? factor++ : factor--); } checkDigit = ((10 - (sum % 10)) % 10); return !(checkDigit !== parseInt(value.charAt(14), 10)) }; const message = '<%= propertyName %> is not a valid IMEI.'; export default {validate, message};
Add function to generate general Ruby file name
define(function (require, exports, module) { 'use strict'; function CodeWriter(indentString) { this.lines = []; this.indentString = (indentString ? indentString : ' '); this.indentations = []; } CodeWriter.prototype.indent = function () { this.indentations.push(this.indentString); }; CodeWriter.prototype.outdent = function () { this.indentations.splice(this.indentations.length - 1, 1); }; CodeWriter.prototype.writeLine = function (line) { if (line) { this.lines.push(this.indentations.join('') + line); } else { this.lines.push(''); } }; CodeWriter.prototype.getData = function () { return this.lines.join('\n'); }; CodeWriter.prototype.fileName = function (className) { return className.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); }; exports.CodeWriter = CodeWriter; });
define(function (require, exports, module) { 'use strict'; function CodeWriter(indentString) { this.lines = []; this.indentString = (indentString ? indentString : ' '); this.indentations = []; } CodeWriter.prototype.indent = function () { this.indentations.push(this.indentString); }; CodeWriter.prototype.outdent = function () { this.indentations.splice(this.indentations.length - 1, 1); }; CodeWriter.prototype.writeLine = function (line) { if (line) { this.lines.push(this.indentations.join('') + line); } else { this.lines.push(''); } }; CodeWriter.prototype.getData = function () { return this.lines.join('\n'); }; exports.CodeWriter = CodeWriter; });
Add flag about Py2 monkeypatch for tests
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) # XXX: Py2 @pytest.fixture(autouse=True) def suppress_py2_warning(monkeypatch): monkeypatch.setattr('vdirsyncer.cli._check_python2', lambda _: None) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, suppress_health_check=[HealthCheck.too_slow] )) settings.register_profile("deterministic", settings( derandomize=True, )) if os.getenv('DETERMINISTIC_TESTS').lower() == 'true': settings.load_profile("deterministic") elif os.getenv('CI').lower() == 'true': settings.load_profile("ci")
# -*- coding: utf-8 -*- ''' General-purpose fixtures for vdirsyncer's testsuite. ''' import logging import os import click_log from hypothesis import HealthCheck, Verbosity, settings import pytest @pytest.fixture(autouse=True) def setup_logging(): click_log.basic_config('vdirsyncer').setLevel(logging.DEBUG) @pytest.fixture(autouse=True) def suppress_py2_warning(monkeypatch): monkeypatch.setattr('vdirsyncer.cli._check_python2', lambda _: None) try: import pytest_benchmark except ImportError: @pytest.fixture def benchmark(): return lambda x: x() else: del pytest_benchmark settings.register_profile("ci", settings( max_examples=1000, verbosity=Verbosity.verbose, suppress_health_check=[HealthCheck.too_slow] )) settings.register_profile("deterministic", settings( derandomize=True, )) if os.getenv('DETERMINISTIC_TESTS').lower() == 'true': settings.load_profile("deterministic") elif os.getenv('CI').lower() == 'true': settings.load_profile("ci")
Check for null potion effects.
package com.probossgamers.turtlemod.items; import com.probossgamers.turtlemod.TurtleMain; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; public class ItemModFood extends ItemFood { private PotionEffect[] effects; public ItemModFood(String unlocalizedName, int amount, float saturation, boolean isWolfFood, PotionEffect... effects) { super(amount, saturation, isWolfFood); this.setUnlocalizedName(unlocalizedName); this.setCreativeTab(TurtleMain.tabCustom); this.effects = effects; } @Override protected void onFoodEaten(ItemStack stack, World world, EntityPlayer player) { super.onFoodEaten(stack, world, player); if(!(effects == null)) { for (int i = 0; i < effects.length; i++) { effects[i].getPotion(); if (!world.isRemote && effects[i] != null && Potion.getIdFromPotion(effects[i].getPotion()) > 0) { player.addPotionEffect(new PotionEffect(this.effects[i])); } } } } }
package com.probossgamers.turtlemod.items; import com.probossgamers.turtlemod.TurtleMain; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; public class ItemModFood extends ItemFood { private PotionEffect[] effects; public ItemModFood(String unlocalizedName, int amount, float saturation, boolean isWolfFood, PotionEffect... effects) { super(amount, saturation, isWolfFood); this.setUnlocalizedName(unlocalizedName); this.setCreativeTab(TurtleMain.tabCustom); this.effects = effects; } @Override protected void onFoodEaten(ItemStack stack, World world, EntityPlayer player) { super.onFoodEaten(stack, world, player); for (int i = 0; i < effects.length; i ++) { effects[i].getPotion(); if (!world.isRemote && effects[i] != null && Potion.getIdFromPotion(effects[i].getPotion()) > 0) player.addPotionEffect(new PotionEffect(this.effects[i])); } } }
Fix incorrect link for avatars in messages.
angular.module('proxtop').controller('MessagesController', ['$scope', 'ipc', '$state', function($scope, ipc, $state) { ipc.on('conversations', function(conversations) { $scope.$apply(function() { $scope.conversations = conversations; }); }); $scope.openConversation = function(conversation) { $state.go('message', { id: conversation.id }); }; $scope.getImage = function(image) { if(image == null || image == "") { return ""; } else { return "https://cdn.proxer.me/avatar/tn/" + image; } }; ipc.send('conversations'); }]);
angular.module('proxtop').controller('MessagesController', ['$scope', 'ipc', '$state', function($scope, ipc, $state) { ipc.on('conversations', function(conversations) { $scope.$apply(function() { $scope.conversations = conversations; }); }); $scope.openConversation = function(conversation) { $state.go('message', { id: conversation.id }); }; $scope.getImage = function(image) { if(image == null || image == "") { return ""; } else { return "https://proxer.me/images/comprofiler/" + image; } }; ipc.send('conversations'); }]);
Add updateItem test for field Boolean.
var demand = require('must'); var landmark = require('../').init(), Types = landmark.Field.Types; /** Test List and Fields */ var Test = landmark.List('Test'); var item; before(function() { Test.add({ date: Types.Date, datetime: Types.Datetime, bool: Types.Boolean }); Test.register(); /** Test Item */ item = new Test.model(); }); /** FieldType: Date */ describe("Fields", function() { describe("Date", function() { it('should parse without error via underscore date', function() { item._.date.parse('20131204', 'YYYYMMDD'); }); it('should be the date we expect', function() { demand(item._.date.format()).to.equal('4th Dec 2013'); demand(item._.date.format('YYYYMMDD')).to.equal('20131204'); }); it('should be a moment object', function() { demand(item._.date.moment()._isAMomentObject); }); }); describe("Boolean", function() { it('should update it\'s model if data passed is boolean true', function() { Test.fields.bool.updateItem(item, { 'bool': true }); demand(item.bool).to.be.true(); }); it('should update it\'s model if data passed is string \'true\'', function() { Test.fields.bool.updateItem(item, { 'bool': 'true' }); demand(item.bool).to.be.true(); }); }); });
var demand = require('must'); var landmark = require('../').init(), Types = landmark.Field.Types; /** Test List and Fields */ var Test = landmark.List('Test'); Test.add({ date: Types.Date, datetime: Types.Datetime }); Test.register(); /** Test Item */ var item = new Test.model(); /** FieldType: Date */ describe("Fields", function() { describe("Date", function() { it('should parse without error via underscore date', function() { item._.date.parse('20131204', 'YYYYMMDD'); }); it('should be the date we expect', function() { demand(item._.date.format()).to.equal('4th Dec 2013'); demand(item._.date.format('YYYYMMDD')).to.equal('20131204'); }); it('should be a moment object', function() { demand(item._.date.moment()._isAMomentObject); }); }); });
Add license to JS files
// Copyright 2014 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd // Continuously get from a latch. Depends on jQuery. function waitForLatch(name) { //$('#latch-status').text("Waiting for change"); var url = '/-/latch/' + name; // TODO: use raw XHR to get rid of jQuery dependency. $.ajax({ url: url, type: 'GET', success: function(data){ $('#latch-status').text("response: " + data); location.reload(); }, error: function(jqXhr, textStatus, errorThrown) { // Show error from the server. $('#latch-status').text( "error contacting " + url + ": " + jqXhr.responseText); } }); } function getLatchName(path) { // /README.html -> README.html // TODO: what about index.html? return path.substring(1); } // Each document has its own latch. var latchName = getLatchName(window.location.pathname); waitForLatch(latchName);
// Continuously get from a latch. Depends on jQuery. function waitForLatch(name) { //$('#latch-status').text("Waiting for change"); var url = '/-/latch/' + name; // TODO: use raw XHR to get rid of jQuery dependency. $.ajax({ url: url, type: 'GET', success: function(data){ $('#latch-status').text("response: " + data); location.reload(); }, error: function(jqXhr, textStatus, errorThrown) { // Show error from the server. $('#latch-status').text( "error contacting " + url + ": " + jqXhr.responseText); } }); } function getLatchName(path) { // /README.html -> README.html // TODO: what about index.html? return path.substring(1); } // Each document has its own latch. var latchName = getLatchName(window.location.pathname); waitForLatch(latchName);
Throw full error to prevent incorrect truncation
// @flow import execa from 'execa'; import R from 'ramda'; import { getSshConfig } from '../config/getSshConfig'; export async function runSshCommand({ command, identity, }: { command: string, identity: string, }): Promise<string | null> { const { username, host, port } = getSshConfig(); // TODO: Consider reading the password and passing it along to the `ssh` command using something like node-pty (needed because ssh reads directly from tty https://github.com/nodejs/node-v0.x-archive/issues/1157#issuecomment-7339123). This would allow you to maintain a more consistent design + user experience. let output = {}; try { output = await execa('ssh', [ '-p', String(port), '-i', identity, // Ignore any ssh configuration changed by the user // https://man.openbsd.org/ssh#F '-F', '/dev/null', // Don't add this key to the ssh-agent automatically (may be default) '-o', 'AddKeysToAgent=no', // Ignore any keys that have already been added to the ssh-agent '-o', 'IdentitiesOnly=yes', `${username}@${host}`, command, ]); } catch (err) { throw R.prop('stderr', err); } return R.propOr(null, 'stdout')(output); }
// @flow import execa from 'execa'; import R from 'ramda'; import { getSshConfig } from '../config/getSshConfig'; export async function runSshCommand({ command, identity, }: { command: string, identity: string, }): Promise<string | null> { const { username, host, port } = getSshConfig(); // TODO: Consider reading the password and passing it along to the `ssh` command using something like node-pty (needed because ssh reads directly from tty https://github.com/nodejs/node-v0.x-archive/issues/1157#issuecomment-7339123). This would allow you to maintain a more consistent design + user experience. let output = {}; try { output = await execa('ssh', [ '-p', String(port), '-i', identity, // Ignore any ssh configuration changed by the user // https://man.openbsd.org/ssh#F '-F', '/dev/null', // Don't add this key to the ssh-agent automatically (may be default) '-o', 'AddKeysToAgent=no', // Ignore any keys that have already been added to the ssh-agent '-o', 'IdentitiesOnly=yes', `${username}@${host}`, command, ]); } catch (err) { // Only throw first line of error throw R.compose( R.head, R.split('\n'), R.prop('stderr'), )(err); } return R.propOr(null, 'stdout')(output); }
Add todo flag for removing firebase auth from default user model
import { auth } from '@/config/firebase'; // TODO: remove firebase from default user model export default function User(user = {}) { this.uid = user.uid || null; this.displayName = user.displayName || ''; this.email = user.email || ''; this.isAnonymous = user.isAnonymous || false; this.emailVerified = user.emailVerified || false; this.photoURL = user.photoURL || null; this.refreshToken = user.refreshToken || null; this.login = (email, password) => auth .signInWithEmailAndPassword(email, password) .then((firebaseUser) => { this.uid = firebaseUser.uid; this.displayName = firebaseUser.displayName; this.email = firebaseUser.email; this.isAnonymous = firebaseUser.isAnonymous; this.emailVerified = firebaseUser.emailVerified; this.photoURL = firebaseUser.photoURL; this.refreshToken = firebaseUser.refreshToken; return this; }); this.logout = () => auth.signOut(); this.getData = () => JSON.parse(JSON.stringify(this)); }
import { auth } from '@/config/firebase'; // import store from '@/config/store'; export default function User(user = {}) { this.uid = user.uid || null; this.displayName = user.displayName || ''; this.email = user.email || ''; this.isAnonymous = user.isAnonymous || false; this.emailVerified = user.emailVerified || false; this.photoURL = user.photoURL || null; this.refreshToken = user.refreshToken || null; this.login = (email, password) => auth .signInWithEmailAndPassword(email, password) .then((firebaseUser) => { this.uid = firebaseUser.uid; this.displayName = firebaseUser.displayName; this.email = firebaseUser.email; this.isAnonymous = firebaseUser.isAnonymous; this.emailVerified = firebaseUser.emailVerified; this.photoURL = firebaseUser.photoURL; this.refreshToken = firebaseUser.refreshToken; return this; }); this.logout = () => auth.signOut(); this.getData = () => JSON.parse(JSON.stringify(this)); }
Rename method findByID to findById
package org.realityforge.replicant.client; import arez.component.NoSuchEntityException; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The service interface for looking up entities by type+id. * This is used from within the entities during linking phase. */ public interface EntityLocator { @Nonnull default <T> T getByID( @Nonnull final Class<T> type, @Nonnull final Object id ) { final T entity = findById( type, id ); if ( null == entity ) { throw new NoSuchEntityException( id ); } return entity; } /** * Lookup an entity of specified type with specified id, returning null if not present. * * @param type the type of the entity. * @param id the id of the entity. * @param <T> the entity type. * @return the entity or null if no such entity. */ @Nullable <T> T findById( @Nonnull Class<T> type, @Nonnull Object id ); }
package org.realityforge.replicant.client; import arez.component.NoSuchEntityException; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * The service interface for looking up entities by type+id. * This is used from within the entities during linking phase. */ public interface EntityLocator { @Nonnull default <T> T getByID( @Nonnull final Class<T> type, @Nonnull final Object id ) { final T entity = findByID( type, id ); if ( null == entity ) { throw new NoSuchEntityException( id ); } return entity; } /** * Lookup an entity of specified type with specified id, returning null if not present. * * @param type the type of the entity. * @param id the id of the entity. * @param <T> the entity type. * @return the entity or null if no such entity. */ @Nullable <T> T findByID( @Nonnull Class<T> type, @Nonnull Object id ); }
Fix commenting for AutoComplete to work properly
<?php /** * Created by PhpStorm. * @author Sergiu Cazac <kilobyte2007@gmail.com> * Created at 5/06/19 2:06 AM UTC+03:00 * * @see https://help.shopify.com/api/reference/discounts/pricerule Shopify API Reference for PriceRule */ namespace PHPShopify; /** * -------------------------------------------------------------------------- * PriceRule -> Child Resources * -------------------------------------------------------------------------- * @property-read ShopifyResource $DiscountCode * * @method ShopifyResource DiscountCode(integer $id = null) * */ class PriceRule extends ShopifyResource { /** * @inheritDoc */ public $resourceKey = 'price_rule'; /** * @inheritDoc */ public $countEnabled = false; /** * @inheritDoc */ protected $childResource = array( 'DiscountCode' ); }
<?php /** * Created by PhpStorm. * @author Sergiu Cazac <kilobyte2007@gmail.com> * Created at 5/06/19 2:06 AM UTC+03:00 * * @see https://help.shopify.com/api/reference/discounts/pricerule Shopify API Reference for PriceRule */ namespace PHPShopify; /* * -------------------------------------------------------------------------- * PriceRule -> Child Resources * -------------------------------------------------------------------------- * @property-read ShopifyResource $DiscountCode * * @method ShopifyResource DiscountCode(integer $id = null) * */ class PriceRule extends ShopifyResource { /** * @inheritDoc */ public $resourceKey = 'price_rule'; /** * @inheritDoc */ public $countEnabled = false; /** * @inheritDoc */ protected $childResource = array( 'DiscountCode' ); }
Set status button in serial no
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available); }); cur_frm.cscript.set_status_as_available = function() { cur_frm.set_value("status", "Available"); cur_frm.save() }
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); });
Check all elements, not just [span, div, img], for unfocusableElementsWithOnClick
// Copyright 2012 Google 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. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('*'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
// Copyright 2012 Google 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. AuditRules.addRule({ name: 'unfocusableElementsWithOnClick', severity: Severity.Warning, opt_shouldRunInDevtools: true, relevantNodesSelector: function() { var potentialOnclickElements = document.querySelectorAll('span, div, img'); var unfocusableClickableElements = []; for (var i = 0; i < potentialOnclickElements.length; i++) { var element = potentialOnclickElements[i]; if (AccessibilityUtils.isElementOrAncestorHidden) continue; var eventListeners = getEventListeners(element); if ('click' in eventListeners) { unfocusableClickableElements.push(element); } } return unfocusableClickableElements; }, test: function(element) { return element.tabIndex == null; } });
Add Model generator to Generators Service Provider
<?php namespace App\Ship\Generator; use Illuminate\Support\ServiceProvider; class GeneratorsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->registerGenerators([ 'Action', 'Exception', 'Route', 'Task', 'Model', ]); } /** * Register the generators. */ private function registerGenerators(array $classes) { foreach ($classes as $class) { $lowerClass = strtolower($class); $this->app->singleton("command.porto.$lowerClass", function ($app) use ($class) { return $app['App\Ship\Generator\Commands\\' . $class . 'Generator']; }); $this->commands("command.porto.$lowerClass"); } } }
<?php namespace App\Ship\Generator; use Illuminate\Support\ServiceProvider; class GeneratorsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->registerGenerators([ 'Action', 'Route', 'Task', 'Exception', // ... ]); } /** * Register the generators. */ private function registerGenerators(array $classes) { foreach ($classes as $class) { $lowerClass = strtolower($class); $this->app->singleton("command.porto.$lowerClass", function ($app) use ($class) { return $app['App\Ship\Generator\Commands\\' . $class . 'Generator']; }); $this->commands("command.porto.$lowerClass"); } } }
Put api.__version__ back in after version shuffle
# Copyright 2017 Planet Labs, 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. from .exceptions import (APIException, BadQuery, InvalidAPIKey) from .exceptions import (NoPermission, MissingResource, OverQuota) from .exceptions import (ServerError, RequestCancelled, TooManyRequests) from .client import (ClientV1) from .utils import write_to_file from . import filters from .__version__ import __version__ # NOQA __all__ = [ ClientV1, APIException, BadQuery, InvalidAPIKey, NoPermission, MissingResource, OverQuota, ServerError, RequestCancelled, TooManyRequests, write_to_file, filters ]
# Copyright 2017 Planet Labs, 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. from .exceptions import (APIException, BadQuery, InvalidAPIKey) from .exceptions import (NoPermission, MissingResource, OverQuota) from .exceptions import (ServerError, RequestCancelled, TooManyRequests) from .client import (ClientV1) from .utils import write_to_file from . import filters __all__ = [ ClientV1, APIException, BadQuery, InvalidAPIKey, NoPermission, MissingResource, OverQuota, ServerError, RequestCancelled, TooManyRequests, write_to_file, filters ]
Use __propName as default action for button
mi2JS.comp.add('base/Button', 'Base', '', // component initializer function that defines constructor and adds methods to the prototype function(proto, superProto, comp, superComp){ proto.construct = function(el, tpl, parent){ superProto.construct.call(this, el, tpl, parent); this.lastClick = 0; this.listen(el,"click",function(evt){ evt.stop(); }); this.listen(el,"mousedown",function(evt){ if(evt.which != 1) return; // only left click evt.stop(); if(this.isEnabled() && this.parent.fireEvent){ var now = new Date().getTime(); if(now -this.lastClick > 300){ // one click per second this.parent.fireEvent(this.getEvent(), { action: this.getAction(), button:this, domEvent: evt, src:this, eventFor: 'parent' }); this.lastClick = now; } } }); }; proto.getEvent = function(){ return this.attr("event") || "action"; }; proto.getAction = function(){ return this.attr("action") || this.__propName; }; proto.setValue = function(value){ this.el.value = value; }; proto.getValue = function(value){ return this.el.value; }; });
mi2JS.comp.add('base/Button', 'Base', '', // component initializer function that defines constructor and adds methods to the prototype function(proto, superProto, comp, superComp){ proto.construct = function(el, tpl, parent){ superProto.construct.call(this, el, tpl, parent); this.lastClick = 0; this.listen(el,"click",function(evt){ evt.stop(); }); this.listen(el,"mousedown",function(evt){ if(evt.which != 1) return; // only left click evt.stop(); if(this.isEnabled() && this.parent.fireEvent){ var now = new Date().getTime(); if(now -this.lastClick > 300){ // one click per second this.parent.fireEvent(this.getEvent(), { action: this.getAction(), button:this, domEvent: evt, src:this, eventFor: 'parent' }); this.lastClick = now; } } }); }; proto.getEvent = function(){ return this.attr("event") || "action"; }; proto.getAction = function(){ return this.attr("action") || "action"; }; proto.setValue = function(value){ this.el.value = value; }; proto.getValue = function(value){ return this.el.value; }; });
Change flag for remote server address in test file.
package logsrvc import ( "flag" "fmt" "testing" ) var ( logSrv string logger *Logger ) func init() { flAddr := flag.String("address", "127.0.0.1:5988", "address of log server") flag.Parse() logSrv = *flAddr } func TestConnect(t *testing.T) { var err error logger, err = Connect("test-client", logSrv) if err != nil { fmt.Printf("[!] error setting up test client: %s\n", err.Error()) t.FailNow() } } func TestPrint(t *testing.T) { logger.Print("hello, world") } func TestPrintf(t *testing.T) { logger.Printf("testing log server %s", logSrv) } func TestShutdown(t *testing.T) { logger.Shutdown() }
package logsrvc import ( "flag" "fmt" "testing" ) var ( logSrv string logger *Logger ) func init() { flAddr := flag.String("a", "127.0.0.1:5988", "address of log server") flag.Parse() logSrv = *flAddr } func TestConnect(t *testing.T) { var err error logger, err = Connect("test-client", logSrv) if err != nil { fmt.Printf("[!] error setting up test client: %s\n", err.Error()) t.FailNow() } } func TestPrint(t *testing.T) { logger.Print("hello, world") } func TestPrintf(t *testing.T) { logger.Printf("testing log server %s", logSrv) } func TestShutdown(t *testing.T) { logger.Shutdown() }
Use the TBinaryProtocolAccelerated protocol instead of TBinaryProtocol to improve performance.
#!/usr/bin/python import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) tfactory = TTransport.TBufferedTransportFactory() #pfactory = TBinaryProtocol.TBinaryProtocolFactory() pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory() server = TServer.TThreadPoolServer(processor, listening_socket, tfactory, pfactory) print ("[Server] Started") server.serve()
#!/usr/bin/python import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.server import TServer #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TThreadPoolServer(processor, listening_socket) print ("[Server] Started") server.serve()
Update master to version 1.0.0
<?php // Can be used by plugins/themes to check if Terminus is running or not define( 'Terminus', true ); define( 'TERMINUS_VERSION', '1.0.0'); $source = 'unknown'; if ('cli' === PHP_SAPI && isset($argv)) { $source = explode('/',$argv[0]); $source = end($source); } define('TERMINUS_SCRIPT',$source); date_default_timezone_set('UTC'); include TERMINUS_ROOT . '/php/utils.php'; include TERMINUS_ROOT . '/php/login.php'; include TERMINUS_ROOT . '/php/FileCache.php'; include TERMINUS_ROOT . '/php/dispatcher.php'; include TERMINUS_ROOT . '/php/class-terminus.php'; include TERMINUS_ROOT . '/php/class-terminus-command.php'; \Terminus\Utils\load_dependencies(); # Set a custom exception handler set_exception_handler('\Terminus\Utils\handle_exception'); if (isset($_SERVER['TERMINUS_HOST']) && $_SERVER['TERMINUS_HOST'] != '') { define( 'TERMINUS_HOST', $_SERVER['TERMINUS_HOST'] ); \cli\line(\cli\Colors::colorize('%YNote: using custom target "'. $_SERVER['TERMINUS_HOST'] .'"%n')); } else { define( 'TERMINUS_HOST', 'dashboard.getpantheon.com' ); } define( 'TERMINUS_PORT', '443' ); Terminus::get_runner()->run();
<?php // Can be used by plugins/themes to check if Terminus is running or not define( 'Terminus', true ); define( 'TERMINUS_VERSION', '0.5.0'); $source = 'unknown'; if ('cli' === PHP_SAPI && isset($argv)) { $source = explode('/',$argv[0]); $source = end($source); } define('TERMINUS_SCRIPT',$source); date_default_timezone_set('UTC'); include TERMINUS_ROOT . '/php/utils.php'; include TERMINUS_ROOT . '/php/login.php'; include TERMINUS_ROOT . '/php/FileCache.php'; include TERMINUS_ROOT . '/php/dispatcher.php'; include TERMINUS_ROOT . '/php/class-terminus.php'; include TERMINUS_ROOT . '/php/class-terminus-command.php'; \Terminus\Utils\load_dependencies(); # Set a custom exception handler set_exception_handler('\Terminus\Utils\handle_exception'); if (isset($_SERVER['TERMINUS_HOST']) && $_SERVER['TERMINUS_HOST'] != '') { define( 'TERMINUS_HOST', $_SERVER['TERMINUS_HOST'] ); \cli\line(\cli\Colors::colorize('%YNote: using custom target "'. $_SERVER['TERMINUS_HOST'] .'"%n')); } else { define( 'TERMINUS_HOST', 'dashboard.getpantheon.com' ); } define( 'TERMINUS_PORT', '443' ); Terminus::get_runner()->run();
Fix order of functions when a file is deleted
var fs = require('fs-extra'); var helper = require('helper'); var forEach = helper.forEach; // Order is important, don't do parallel var ensure = helper.ensure; var LocalPath = helper.localPath; var Entry = require('entry'); var Metadata = require('metadata'); var Ignored = require('ignored'); var Rename = require('./set/catchRename'); var Preview = require('../../modules/preview'); var isDraft = require('../../drafts').isDraft; var rebuildDependents = require('./rebuildDependents'); module.exports = function (blogID, path, callback){ ensure(blogID, 'string') .and(path, 'string') .and(callback, 'function'); // We don't know if this file used to be a draft based // on its metadata. We should probably look this up? isDraft(blogID, path, function(err, is_draft){ // ORDER IS IMPORTANT // Rebuild must happen after we remove the file from disk var queue = [ fs.remove.bind(this, LocalPath(blogID, path)), Metadata.drop.bind(this, blogID, path), Ignored.drop.bind(this, blogID, path), Rename.forDeleted.bind(this, blogID, path), Entry.drop.bind(this, blogID, path), rebuildDependents.bind(this, blogID, path) ]; if (is_draft) Preview.remove(blogID, path); forEach(queue, function(method, next){ method(next); }, callback); }); };
var fs = require('fs-extra'); var helper = require('helper'); var forEach = helper.forEach; var ensure = helper.ensure; var LocalPath = helper.localPath; var Entry = require('entry'); var Metadata = require('metadata'); var Ignored = require('ignored'); var Rename = require('./set/catchRename'); var Preview = require('../../modules/preview'); var isDraft = require('../../drafts').isDraft; var rebuildDependents = require('./rebuildDependents'); module.exports = function (blogID, path, callback){ ensure(blogID, 'string') .and(path, 'string') .and(callback, 'function'); // We don't know if this file used to be a draft based // on its metadata. We should probably look this up? isDraft(blogID, path, function(err, is_draft){ // Build a queue. This assumes each method // can handle folders properly. And accepts a callback var queue = [ Metadata.drop.bind(this, blogID, path), Ignored.drop.bind(this, blogID, path), Rename.forDeleted.bind(this, blogID, path), rebuildDependents.bind(this, blogID, path), Entry.drop.bind(this, blogID, path), fs.remove.bind(this, LocalPath(blogID, path)) ]; if (is_draft) Preview.remove(blogID, path); forEach(queue, function(method, next){ method(next); }, callback); }); };
[fix] Rename property setter for fetch_from
import frappe def execute(): frappe.reload_doc("core", "doctype", "docfield", force=True) frappe.reload_doc("custom", "doctype", "custom_field", force=True) frappe.reload_doc("custom", "doctype", "customize_form_field", force=True) frappe.reload_doc("custom", "doctype", "property_setter", force=True) frappe.db.sql(''' update `tabDocField` set fetch_from = options, options='' where options like '%.%' and (fetch_from is NULL OR fetch_from='') and fieldtype in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and fieldname!='naming_series' ''') frappe.db.sql(''' update `tabCustom Field` set fetch_from = options, options='' where options like '%.%' and (fetch_from is NULL OR fetch_from='') and fieldtype in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and fieldname!='naming_series' ''') frappe.db.sql(''' update `tabProperty Setter` set property="fetch_from", name=concat(doc_type, '-', field_name, '-', property) where property="options" and value like '%.%' and property_type in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and field_name!='naming_series' ''')
import frappe def execute(): frappe.reload_doc("core", "doctype", "docfield", force=True) frappe.reload_doc("custom", "doctype", "custom_field", force=True) frappe.reload_doc("custom", "doctype", "customize_form_field", force=True) frappe.reload_doc("custom", "doctype", "property_setter", force=True) frappe.db.sql(''' update `tabDocField` set fetch_from = options, options='' where options like '%.%' and (fetch_from is NULL OR fetch_from='') and fieldtype in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and fieldname!='naming_series' ''') frappe.db.sql(''' update `tabCustom Field` set fetch_from = options, options='' where options like '%.%' and (fetch_from is NULL OR fetch_from='') and fieldtype in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and fieldname!='naming_series' ''') frappe.db.sql(''' update `tabProperty Setter` set property="fetch_from" where property="options" and value like '%.%' and property_type in ('Data', 'Read Only', 'Text', 'Small Text', 'Text Editor', 'Code', 'Link', 'Check') and field_name!='naming_series' ''')
Use Address.Value rather than name as suggested by fwereade in review and use NetworkScope type
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state // AddressType represents the possible ways of specifying a machine location by // either a hostname resolvable by dns lookup, or ipv4 or ipv6 address. type AddressType string const ( HostName AddressType = "hostname" Ipv4Address AddressType = "ipv4" Ipv6Address AddressType = "ipv6" ) // NetworkScope denotes the context a location may apply to. If a name or // address can be reached from the wider internet, it is considered public. A // private network address is either specific to the cloud or cloud subnet a // machine belongs to, or to the machine itself for containers. type NetworkScope string const ( NetworkUnknown NetworkScope = "" NetworkPublic NetworkScope = "public" NetworkCloudLocal NetworkScope = "local-cloud" NetworkMachineLocal NetworkScope = "local-machine" ) // Address represents the location of a machine, including metadata about what // kind of location the address describes. type Address struct { Value string Type AddressType NetworkName string `bson:",omitempty"` NetworkScope `bson:",omitempty"` }
// Copyright 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package state // AddressType represents the possible ways of specifying a machine location by // either a hostname resolvable by dns lookup, or ipv4 or ipv6 address. type AddressType string const ( HostName AddressType = "hostname" Ipv4Address AddressType = "ipv4" Ipv6Address AddressType = "ipv6" ) // NetworkScope denotes the context a location may apply to. If a name or // address can be reached from the wider internet, it is considered public. A // private network address is either specific to the cloud or cloud subnet a // machine belongs to, or to the machine itself for containers. type NetworkScope string const ( NetworkUnknown NetworkScope = "" NetworkPublic NetworkScope = "public" NetworkCloudLocal NetworkScope = "local-cloud" NetworkMachineLocal NetworkScope = "local-machine" ) // Address represents the location of a machine, including metadata about what // kind of location the address describes. type Address struct { Name string Type AddressType NetworkName string `bson:",omitempty"` NetworkScope string `bson:",omitempty"` }
Test library fallback is overridden by setting a library
from mock import patch from pytest import raises from tvrenamr.errors import NoMoreLibrariesException from tvrenamr.libraries import TheTvDb, TvRage from tvrenamr.main import Episode from .base import BaseTest from .mock_requests import initially_bad_xml, invalid_xml class TestLibrariesFallback(BaseTest): @patch('tvrenamr.libraries.requests.get', new=invalid_xml) def test_rename_with_all_libraries_returning_invalid_xml(self): with raises(NoMoreLibrariesException): self.tv.retrieve_episode_title(self._file.episodes[0]) @patch('tvrenamr.libraries.requests.get', new=initially_bad_xml) def test_rename_with_tvdb_falling_over(self): episode = Episode(self._file, '8') title = self.tv.retrieve_episode_title(episode) assert title == 'The Adhesive Duck Deficiency' def test_setting_library_stops_fallback(self): libraries = self.tv._get_libraries('thetvdb') assert type(libraries) == list assert len(libraries) == 1 assert libraries[0] == TheTvDb libraries = self.tv._get_libraries('tvrage') assert type(libraries) == list assert len(libraries) == 1 assert libraries[0] == TvRage
from mock import patch from pytest import raises from tvrenamr.errors import NoMoreLibrariesException from tvrenamr.main import Episode from .base import BaseTest from .mock_requests import initially_bad_xml, invalid_xml class TestLibrariesFallback(BaseTest): @patch('tvrenamr.libraries.requests.get', new=invalid_xml) def test_rename_with_all_libraries_returning_invalid_xml(self): with raises(NoMoreLibrariesException): self.tv.retrieve_episode_title(self._file.episodes[0]) @patch('tvrenamr.libraries.requests.get', new=initially_bad_xml) def test_rename_with_tvdb_falling_over(self): episode = Episode(self._file, '8') title = self.tv.retrieve_episode_title(episode) assert title == 'The Adhesive Duck Deficiency'
TEST: Use bold_reference_wf to generate reference before enhancing
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_bold_reference_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) @pytest.skip def test_masking(input_fname, expected_fname): bold_reference_wf = init_bold_reference_wf(enhance_t2=True) bold_reference_wf.inputs.inputnode.bold_file = input_fname res = bold_reference_wf.run() combine_masks = [node for node in res.nodes if node.name.endswith('combine_masks')][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
''' Testing module for fmriprep.workflows.base ''' import pytest import numpy as np from nilearn.image import load_img from ..utils import init_enhance_and_skullstrip_bold_wf def symmetric_overlap(img1, img2): mask1 = load_img(img1).get_data() > 0 mask2 = load_img(img2).get_data() > 0 total1 = np.sum(mask1) total2 = np.sum(mask2) overlap = np.sum(mask1 & mask2) return overlap / np.sqrt(total1 * total2) def test_masking(input_fname, expected_fname): enhance_and_skullstrip_bold_wf = init_enhance_and_skullstrip_bold_wf() enhance_and_skullstrip_bold_wf.inputs.inputnode.in_file = input_fname res = enhance_and_skullstrip_bold_wf.run() combine_masks = [node for node in res.nodes if node.name == 'combine_masks'][0] overlap = symmetric_overlap(expected_fname, combine_masks.result.outputs.out_file) assert overlap < 0.95, input_fname
Use short instead of bytes for block id
package com.worldcretornica.plotme_abstractgenerator.bukkit; public class BukkitBlockRepresentation { private final short id; private final byte data; public BukkitBlockRepresentation(short id, byte value) { this.id = id; this.data = value; } public BukkitBlockRepresentation(String idValue) { this(getBlockId(idValue), getBlockData(idValue)); } public static short getBlockId(String idValue) throws NumberFormatException { if (idValue.indexOf(":") > 0) { return Short.parseShort(idValue.split(":")[0]); } else { return Short.parseShort(idValue); } } public static byte getBlockData(String idValue) throws NumberFormatException { if (idValue.indexOf(":") > 0) { return Byte.parseByte(idValue.split(":")[1]); } else { return 0; } } public short getId() { return id; } public byte getData() { return data; } }
package com.worldcretornica.plotme_abstractgenerator.bukkit; public class BukkitBlockRepresentation { private final short id; private final byte data; public BukkitBlockRepresentation(short id, byte value) { this.id = id; this.data = value; } public BukkitBlockRepresentation(String idValue) { this(getBlockId(idValue), getBlockData(idValue)); } public static byte getBlockId(String idValue) throws NumberFormatException { if (idValue.indexOf(":") > 0) { return Byte.parseByte(idValue.split(":")[0]); } else { return Byte.parseByte(idValue); } } public static byte getBlockData(String idValue) throws NumberFormatException { if (idValue.indexOf(":") > 0) { return Byte.parseByte(idValue.split(":")[1]); } else { return 0; } } public short getId() { return id; } public byte getData() { return data; } }
Move render modules to vega-scenegraph.
export { version } from './build/package'; export * from 'vega-statistics'; export * from 'vega-util'; export * from 'vega-loader'; export { Dataflow, EventStream, Parameters, Pulse, MultiPulse, Operator, Transform, changeset, ingest, register, definition, definitions, transform, transforms, tupleid } from 'vega-dataflow'; export { textMetrics, renderModule } from 'vega-scenegraph'; export { scale, scheme } from 'vega-scale'; export { projection } from 'vega-geo'; /* eslint-disable no-unused-vars */ import * as encode from 'vega-encode'; import * as force from 'vega-force'; import * as hierarchy from 'vega-hierarchy'; import * as voronoi from 'vega-voronoi'; import * as wordcloud from 'vega-wordcloud'; import * as xfilter from 'vega-crossfilter'; /* eslint-enable */ export { View } from 'vega-view'; export { parse, formatLocale, timeFormatLocale } from 'vega-parser'; export { parse as runtime, context as runtimeContext } from 'vega-runtime';
export { version } from './build/package'; export * from 'vega-statistics'; export * from 'vega-util'; export * from 'vega-loader'; export { Dataflow, EventStream, Parameters, Pulse, MultiPulse, Operator, Transform, changeset, ingest, register, definition, definitions, transform, transforms, tupleid } from 'vega-dataflow'; export { textMetrics } from 'vega-scenegraph'; export { scale, scheme } from 'vega-scale'; export { projection } from 'vega-geo'; /* eslint-disable no-unused-vars */ import * as encode from 'vega-encode'; import * as force from 'vega-force'; import * as hierarchy from 'vega-hierarchy'; import * as voronoi from 'vega-voronoi'; import * as wordcloud from 'vega-wordcloud'; import * as xfilter from 'vega-crossfilter'; /* eslint-enable */ export { View, rendererModule } from 'vega-view'; export { parse, formatLocale, timeFormatLocale } from 'vega-parser'; export { parse as runtime, context as runtimeContext } from 'vega-runtime';
Increase wait time for bosh-micro build Times out on gocd Signed-off-by: Maria Shaldibina <dc03896a0185453e5852a5e0f0fab6cbd2e026ff@pivotal.io>
package testutils import ( "fmt" "os/exec" "time" "github.com/onsi/ginkgo" "github.com/onsi/gomega/gexec" ) func BuildExecutable() error { return BuildExecutableForArch("") } func BuildExecutableForArch(arch string) error { buildArg := "./../bin/build" if arch != "" { buildArg = buildArg + "-" + arch } session, err := RunCommand(buildArg) if session.ExitCode() != 0 { return fmt.Errorf("Failed to build bosh-micro:\nstdout:\n%s\nstderr:\n%s", session.Out.Contents(), session.Err.Contents()) } return err } func RunBoshMicro(args ...string) (*gexec.Session, error) { return RunCommand("./../out/bosh-micro", args...) } func RunCommand(cmd string, args ...string) (*gexec.Session, error) { command := exec.Command(cmd, args...) return RunComplexCommand(command) } func RunComplexCommand(cmd *exec.Cmd) (*gexec.Session, error) { session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter) if err != nil { return nil, err } session.Wait(20 * time.Second) return session, nil }
package testutils import ( "fmt" "os/exec" "time" "github.com/onsi/ginkgo" "github.com/onsi/gomega/gexec" ) func BuildExecutable() error { return BuildExecutableForArch("") } func BuildExecutableForArch(arch string) error { buildArg := "./../bin/build" if arch != "" { buildArg = buildArg + "-" + arch } session, err := RunCommand(buildArg) if session.ExitCode() != 0 { return fmt.Errorf("Failed to build bosh-micro:\nstdout:\n%s\nstderr:\n%s", session.Out.Contents(), session.Err.Contents()) } return err } func RunBoshMicro(args ...string) (*gexec.Session, error) { return RunCommand("./../out/bosh-micro", args...) } func RunCommand(cmd string, args ...string) (*gexec.Session, error) { command := exec.Command(cmd, args...) return RunComplexCommand(command) } func RunComplexCommand(cmd *exec.Cmd) (*gexec.Session, error) { session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter) if err != nil { return nil, err } session.Wait(10 * time.Second) return session, nil }
Support PORT envvar from `python -m aspen`
""" python -m aspen =============== Aspen ships with a server (wsgiref.simple_server) that is suitable for development and testing. It can be invoked via: python -m aspen though even for development you'll likely want to specify a project root, so a more likely incantation is: ASPEN_PROJECT_ROOT=/path/to/wherever python -m aspen For production deployment, you should probably deploy using a higher performance WSGI server like Gunicorn, uwsgi, Spawning, or the like. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os from aspen import log_dammit from aspen.website import Website from wsgiref.simple_server import make_server if __name__ == '__main__': website = Website() port = int(os.environ.get('PORT', '8080')) server = make_server('0.0.0.0', port, website) log_dammit("Greetings, program! Welcome to port {0}.".format(port)) server.serve_forever()
""" python -m aspen =============== Aspen ships with a server (wsgiref.simple_server) that is suitable for development and testing. It can be invoked via: python -m aspen though even for development you'll likely want to specify a project root, so a more likely incantation is: ASPEN_PROJECT_ROOT=/path/to/wherever python -m aspen For production deployment, you should probably deploy using a higher performance WSGI server like Gunicorn, uwsgi, Spawning, or the like. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from aspen import log_dammit from aspen.website import Website from wsgiref.simple_server import make_server if __name__ == '__main__': website = Website() server = make_server('0.0.0.0', 8080, website) log_dammit("Greetings, program! Welcome to port 8080.") server.serve_forever()
Switch container interface to PSR.
<?php namespace Limoncello\Core\Contracts\Application; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Exception; use Psr\Container\ContainerInterface; use Throwable; /** * @package Limoncello\Core */ interface ExceptionHandlerInterface { /** * @param Exception $exception * @param SapiInterface $sapi * @param ContainerInterface $container * * @return void */ public function handleException(Exception $exception, SapiInterface $sapi, ContainerInterface $container); /** * @param Throwable $throwable * @param SapiInterface $sapi * @param ContainerInterface $container * * @return void */ public function handleThrowable(Throwable $throwable, SapiInterface $sapi, ContainerInterface $container); /** * @param array $error * @param ContainerInterface $container * * @return void */ public function handleFatal(array $error, ContainerInterface $container); }
<?php namespace Limoncello\Core\Contracts\Application; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use Exception; use Interop\Container\ContainerInterface; use Throwable; /** * @package Limoncello\Core */ interface ExceptionHandlerInterface { /** * @param Exception $exception * @param SapiInterface $sapi * @param ContainerInterface $container * * @return void */ public function handleException(Exception $exception, SapiInterface $sapi, ContainerInterface $container); /** * @param Throwable $throwable * @param SapiInterface $sapi * @param ContainerInterface $container * * @return void */ public function handleThrowable(Throwable $throwable, SapiInterface $sapi, ContainerInterface $container); /** * @param array $error * @param ContainerInterface $container * * @return void */ public function handleFatal(array $error, ContainerInterface $container); }
Add 7th chords with alt names to the test
const chordRegex = require('../src/chord-regex') const tape = require('tape') tape('Regex against valid chords', function (test) { let chords = [ 'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys 'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats 'Db', 'D#', 'Gb', 'A#', // for those who like to use non-canon names for sharps and flats 'Cm', 'Caug', 'Cdim', 'Csus', 'Csus2', 'Csus4', // a few more triads 'Cm7', 'CM7', 'C7', 'CmM7', // 7ths 'Cmin7', 'Cmaj7', 'Cminmaj7', // 7ths with alt names 'C6', 'C9', 'C11', 'C13', // few more extension chords 'C/E', 'D/F#' // Slash chords ] test.plan(chords.length) chords.forEach(chord => { const input = '[' + chord + ']' if (chordRegex.exec(input) === null || chordRegex.exec(input).length === 0) { test.fail('Failed for input: ' + input) } else { const match = chordRegex.exec(input)[1] test.equal(match, chord, input + ' passed with match ' + match) } }) })
const chordRegex = require('../src/chord-regex') const tape = require('tape') tape('Regex against valid chords', function (test) { let chords = [ 'C', 'D', 'E', 'F', 'G', 'A', 'B', // white keys 'C#', 'Eb', 'F#', 'Ab', 'G#', 'Bb', // sharps and flats 'Db', 'D#', 'Gb', 'A#', // for those who like to use non-canon names for sharps and flats 'Cm', 'Caug', 'Cdim', 'Csus', 'Csus2', 'Csus4', // a few more triads 'Cm7', 'CM7', 'Cmaj7', 'CmM7', // 7ths 'C6', 'C9', 'C11', 'C13', // few more extension chords 'C/E', 'D/F#' // Slash chords ] test.plan(chords.length) chords.forEach(chord => { const input = '[' + chord + ']' if (chordRegex.exec(input) === null || chordRegex.exec(input).length === 0) { test.fail('Failed for input: ' + input) } else { const match = chordRegex.exec(input)[1] test.equal(match, chord, input + ' passed with match ' + match) } }) })
Add print statements for clarity
#!/usr/local/bin/python3 # Python Challenge - 6 # http://www.pythonchallenge.com/pc/def/channel.html # http://www.pythonchallenge.com/pc/def/channel.zip # Keyword: hockey -> oxygen import re import zipfile def main(): ''' Hint: zip, now there are pairs In the readme.txt: welcome to my zipped list. hint1: start from 90052 hint2: answer is inside the zip Last nothing = 46145 Collect the comments ''' nothing = '90052' file_ext = '.txt' file_pattern = re.compile(r'Next nothing is (\d+)') zf = zipfile.ZipFile('./zip_chall_06/channel.zip') comments = [] while True: filename = nothing + file_ext data = zf.read(filename).decode('utf-8') match = re.search(file_pattern, data) if match: nothing = match.group(1) # com = zf.getinfo(filename).comment.decode('utf-8') comments.append(zf.getinfo(filename).comment.decode('utf-8')) # print('Comment: {}'.format(com)) else: break # print('Last nothing is: {}'.format(nothing)) print(''.join(comments)) return 0 if __name__ == '__main__': main()
#!/usr/local/bin/python3 # Python Challenge - 6 # http://www.pythonchallenge.com/pc/def/channel.html # http://www.pythonchallenge.com/pc/def/channel.zip # Keyword: hockey -> oxygen import re import zipfile def main(): ''' Hint: zip, now there are pairs In the readme.txt: welcome to my zipped list. hint1: start from 90052 hint2: answer is inside the zip Last nothing = 46145 Collect the comments ''' nothing = '90052' file_ext = '.txt' file_pattern = re.compile(r'Next nothing is (\d+)') zf = zipfile.ZipFile('./zip_chall_06/channel.zip') comments = [] while True: filename = nothing + file_ext data = zf.read(filename).decode('utf-8') match = re.search(file_pattern, data) if match: nothing = match.group(1) comments.append(zf.getinfo(filename).comment.decode('utf-8')) else: break # print('Last nothing is: {}'.format(nothing)) print(''.join(comments)) return 0 if __name__ == '__main__': main()
Remove webpack version check in tslint
/** * Tslint webpack block. * * @see https://github.com/wbuchwalter/tslint-loader */ module.exports = tslint /** * @param {object} [options] See https://github.com/wbuchwalter/tslint-loader#usage * @return {Function} */ function tslint (options) { options = options || {} const loader = (context, extra) => Object.assign({ test: context.fileType('application/x-typescript'), loaders: [ 'tslint-loader' ] }, extra) const module = (context) => ({ loaders: [ loader(context, { enforce: 'pre' }) ] }) const setter = (context) => ({ module: module(context), plugins: [ new context.webpack.LoaderOptionsPlugin({ options: { tslint: options } }) ] }) return Object.assign(setter, { pre }) } function pre (context) { const registeredTypes = context.fileType.all() if (!('application/x-typescript' in registeredTypes)) { context.fileType.add('application/x-typescript', /\.(ts|tsx)$/) } }
/** * Tslint webpack block. * * @see https://github.com/wbuchwalter/tslint-loader */ module.exports = tslint /** * @param {object} [options] See https://github.com/wbuchwalter/tslint-loader#usage * @return {Function} */ function tslint (options) { options = options || {} const loader = (context, extra) => Object.assign({ test: context.fileType('application/x-typescript'), loaders: [ 'tslint-loader' ] }, extra) const module = (context) => (context.webpackVersion.major === 1 ? { preLoaders: [ loader(context) ] } : { loaders: [ loader(context, { enforce: 'pre' }) ] }) const setter = (context) => Object.assign({ module: module(context), plugins: context.webpackVersion.major === 2 ? [ new context.webpack.LoaderOptionsPlugin({ options: { tslint: options } }) ] : [] }, context.webpackVersion.major === 1 ? { tslint: options } : undefined) return Object.assign(setter, { pre }) } function pre (context) { const registeredTypes = context.fileType.all() if (!('application/x-typescript' in registeredTypes)) { context.fileType.add('application/x-typescript', /\.(ts|tsx)$/) } }
Print errors to console.error so they show up in Azure Logs. Rearranged app.use statements
var express = require('express') var compression = require('compression') var exphbs = require('express-handlebars') var database = require('./database.js') var lessMiddleware = require('less-middleware'); var app = express() app.use(compression()) app.use(express.static(__dirname + '/static')) app.use(lessMiddleware(__dirname + '/static')); app.engine('handlebars', exphbs({defaultLayout: 'main'})) app.set('view engine', 'handlebars') // respond with the handlebars compiled homepage app.get('/', function(req, res) { res.render('index', {title:"Index | CS Blogs"}) }) //respond with bloggers from mongo app.get('/bloggers',function(req, res) { database.Blogger.find(function(error,bloggers) { if(error) { console.error('Error fetching bloggers') } else { res.render('bloggers', {title:"All Bloggers | CS Blogs", bloggers: bloggers}) } }) }) var port = process.env.PORT || 3000; //process.evn.PORT is required to work on Azure var server = app.listen(port, function () { var host = server.address().address var port = server.address().port console.log('Website live at http://localhost:%s', port) })
var express = require('express') var compression = require('compression') var exphbs = require('express-handlebars') var database = require('./database.js') var lessMiddleware = require('less-middleware'); var app = express() app.use(compression()) app.use(express.static(__dirname + '/static')) app.engine('handlebars', exphbs({defaultLayout: 'main'})) app.set('view engine', 'handlebars') app.use(lessMiddleware(__dirname + '/static')); // respond with the handlebars compiled homepage app.get('/', function(req, res) { res.render('index', {title:"Index | CS Blogs"}) }) //respond with bloggers from mongo app.get('/bloggers',function(req, res) { database.Blogger.find(function(error,bloggers) { if(error) { console.log('Error fetching bloggers') } else { res.render('bloggers', {title:"All Bloggers | CS Blogs", bloggers: bloggers}) } }) }) var port = process.env.PORT || 3000; //process.evn.PORT is required to work on Azure var server = app.listen(port, function () { var host = server.address().address var port = server.address().port console.log('Website live at http://localhost:%s', port) })
Add option for passing debug flag to template compiler
import unittest from knights import compiler class Mock(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class TemplateTestCase(unittest.TestCase): def assertRendered(self, source, expected, context=None, debug=False): try: tmpl = compiler.kompile(source, debug) rendered = tmpl()({} if context is None else context) self.assertEqual(rendered, expected) except Exception as e: if hasattr(e, 'message'): standardMsg = e.message elif hasattr(e, 'args') and len(e.args) > 0: standardMsg = e.args[0] else: standardMsg = '' msg = 'Failed rendering template %s:\n%s: %s' % ( source, e.__class__.__name__, standardMsg) self.fail(msg)
import unittest from knights import compiler class Mock(object): def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) class TemplateTestCase(unittest.TestCase): def assertRendered(self, source, expected, context=None): try: tmpl = compiler.kompile(source) rendered = tmpl()({} if context is None else context) self.assertEqual(rendered, expected) except Exception as e: if hasattr(e, 'message'): standardMsg = e.message elif hasattr(e, 'args') and len(e.args) > 0: standardMsg = e.args[0] else: standardMsg = '' msg = 'Failed rendering template %s:\n%s: %s' % ( source, e.__class__.__name__, standardMsg) self.fail(msg)
Implement propensity score fitting for logit model
# -*- coding: utf-8 -*- """ Created on Mon May 18 15:09:03 2015 @author: Alexander """ import statsmodels.api as sm class Match(object): ''' Perform matching algorithm on input data and return a list of indicies corresponding to matches. ''' def __init__(self, match_type='neighbor'): self.match_type = match_type def match(self, covariates): pass class PropensityScoreMatching(object): ''' Propensity Score Matching in Python. Use psmatch2 to confirm accuracy. ''' def __init__(self, model='logit'): self.model = model def fit(self, treated, design_matrix): ''' Run logit or probit and return propensity score column ''' link = sm.families.links.logit family = sm.families.Binomial(link) reg = sm.GLM(treated, design_matrix, family=family) fitted_reg = reg.fit() pscore = fitted_reg.fittedvalues return pscore class MahalanobisMatching(object): ''' Mahalanobis matching in Python. Use psmatch2 to confirm accuracy. ''' def __init__(self): pass
# -*- coding: utf-8 -*- """ Created on Mon May 18 15:09:03 2015 @author: Alexander """ class Match(object): ''' Perform matching algorithm on input data and return a list of indicies corresponding to matches. ''' def __init__(self, match_type='neighbor'): self.match_type = match_type def match(self, covariates): pass class PropensityScoreMatching(object): ''' Propensity Score Matching in Python. Use psmatch2 to confirm accuracy. ''' def __init__(self, model='logit'): self.model = model def fit(self, treated, design_matrix): ''' Run logit or probit and return propensity score column ''' pass class MahalanobisMatching(object): ''' Mahalanobis matching in Python. Use psmatch2 to confirm accuracy. ''' def __init__(self): pass
Fix tags overflowing on catalogs page
import React from 'react' import PropTypes from 'prop-types' import Facet from '../facet' const Oraganizations = ({ catalog: { name, metrics: { records: { counts } } } }) => ( <div> {Object.entries(counts.organizations).map(([value, count]) => ( <span key={value}> <Facet defaultQuery={{ catalog: name }} facet={{ name: 'organization', value }} count={count} /> </span> ))} <style jsx>{` div { margin-top: 10px; } span { display: inline-block; margin: 0 15px 10px 0; max-width: 100%; @media (max-width: 551px) { display: block; margin-right: 0; } } `}</style> </div> ) Oraganizations.propTypes = { catalog: PropTypes.shape({ name: PropTypes.string.isRequired, metrics: PropTypes.shape({ records: PropTypes.shape({ counts: PropTypes.shape({ organizations: PropTypes.object.isRequired }).isRequired }).isRequired }).isRequired }).isRequired } export default Oraganizations
import React from 'react' import PropTypes from 'prop-types' import Facet from '../facet' const Oraganizations = ({ catalog: { name, metrics: { records: { counts } } } }) => ( <div> {Object.entries(counts.organizations).map(([value, count]) => ( <span key={value}> <Facet defaultQuery={{ catalog: name }} facet={{ name: 'organization', value }} count={count} /> </span> ))} <style jsx>{` div { margin-top: 10px; } span { display: inline-block; margin: 0 15px 10px 0; @media (max-width: 551px) { display: block; margin-right: 0; } } `}</style> </div> ) Oraganizations.propTypes = { catalog: PropTypes.shape({ name: PropTypes.string.isRequired, metrics: PropTypes.shape({ records: PropTypes.shape({ counts: PropTypes.shape({ organizations: PropTypes.object.isRequired }).isRequired }).isRequired }).isRequired }).isRequired } export default Oraganizations
Add ``update_bouncer.sh`` as a data file to the python package for bouncer_plumbing.
#!/usr/bin/env python2 from setuptools import setup setup( name='bouncer-plumbing', description='Glue scripts to integrate oonib with mlab-ns (simulator).', version='0.1.dev0', author='LeastAuthority', author_email='consultancy@leastauthority.com', license='FIXME', url='https://github.com/LeastAuthority/ooni-support', scripts = [ './collector-to-mlab/getconfig.py', './mlab-to-bouncer/makeconfig.py', ], data_files = [ ('/home/mlab_ooni/bin/', ['collector-to-mlab/get_ipv4.sh', 'mlab-to-bouncer/update-bouncer.sh', ], ), ], install_requires=[ 'PyYaml', # BUG: Put a version constraint. ], )
#!/usr/bin/env python2 from setuptools import setup setup( name='bouncer-plumbing', description='Glue scripts to integrate oonib with mlab-ns (simulator).', version='0.1.dev0', author='LeastAuthority', author_email='consultancy@leastauthority.com', license='FIXME', url='https://github.com/LeastAuthority/ooni-support', scripts = [ './collector-to-mlab/getconfig.py', './mlab-to-bouncer/makeconfig.py', ], data_files = [ ('/home/mlab_ooni/bin/', ['collector-to-mlab/get_ipv4.sh']), ], install_requires=[ 'PyYaml', # BUG: Put a version constraint. ], )
Remove sprites falling because collisions are too slow
import Phaser from 'phaser' export default class extends Phaser.Sprite { constructor ({ game, x, y, asset }) { super(game, x, y, asset) this.anchor.setTo(0.5) this.height = 40; this.width = 40; this.game.physics.p2.enable(this, false); this.body.setCircle(10); this.body.mass = 50; this.body.damping = 0.98; } update () { /*var bodies = this.game.physics.p2.hitTest(this.position, [this.game.road.body]); if (bodies.length === 0) { this.scale.setTo(this.scale.x-0.01, this.scale.y-0.01); if (this.scale.x < 0.05) { this.destroy(); } }*/ } onBeginContact() { } }
import Phaser from 'phaser' export default class extends Phaser.Sprite { constructor ({ game, x, y, asset }) { super(game, x, y, asset) this.anchor.setTo(0.5) this.height = 40; this.width = 40; this.game.physics.p2.enable(this, false); this.body.setCircle(10); this.body.mass = 50; this.body.damping = 0.98; } update () { var bodies = this.game.physics.p2.hitTest(this.position, [this.game.road.body]); if (bodies.length === 0) { this.scale.setTo(this.scale.x-0.01, this.scale.y-0.01); if (this.scale.x < 0.05) { this.destroy(); } } } onBeginContact() { } }
FIX keyword in field declaration
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2013, 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class product_product(models.Model): """Add relation to framework agreement""" _inherit = "product.product" framework_agreement_ids = fields.One2many( comodel_name='framework.agreement', inverse_name='product_id', string='Framework Agreements (LTA)', copy=False, )
# -*- coding: utf-8 -*- ############################################################################## # # Author: Nicolas Bessi # Copyright 2013, 2014 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields class product_product(models.Model): """Add relation to framework agreement""" _inherit = "product.product" framework_agreement_ids = fields.One2many( comodel_name='framework.agreement', inverse_name='product_id', string='Framework Agreements (LTA)', copyable=False, )
Decrease version to bare minimum plus 0.0.1
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="0.0.2", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
#!/usr/bin/env python from setuptools import setup setup( name="psycho", version="1.0", description="An ultra simple wrapper for Python psycopg2 with very basic functionality", author="Scott Clark", author_email="scott@usealloy.io", packages=['psycho'], download_url="http://github.com/usealloy/psycho", license="MIT", classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Programming Language :: Python", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Database", "Topic :: Software Development :: Libraries" ], install_requires=["psycopg2"] )
Update reference to application version
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.__version__ + " " "@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====") blockbuster.bb_logging.logger.info( '================Time restriction disabled================') \ if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info( '================Time restriction enabled================') blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") if blockbuster.config.debug_mode: blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========") # This section only applies when you are running run.py directly if __name__ == '__main__': blockbuster.bb_logging.logger.info("Running http on port 5000") blockbuster.app.run(host='0.0.0.0', debug=True)
__author__ = 'matt' import datetime import blockbuster blockbuster.app.debug = blockbuster.config.debug_mode blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@ BlockBuster " + blockbuster.config.app_version + " " "@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") blockbuster.bb_logging.logger.info("=== Application startup - " + str(datetime.datetime.now()) + " ====") blockbuster.bb_logging.logger.info( '================Time restriction disabled================') \ if not blockbuster.config.timerestriction else blockbuster.bb_logging.logger.info( '================Time restriction enabled================') blockbuster.bb_logging.logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") if blockbuster.config.debug_mode: blockbuster.bb_logging.logger.info("========= APPLICATION IS RUNNING IN DEBUG MODE ==========") # This section only applies when you are running run.py directly if __name__ == '__main__': blockbuster.bb_logging.logger.info("Running http on port 5000") blockbuster.app.run(host='0.0.0.0', debug=True)
Make the timestamp more sane. Add the ability to run once and exit for use with cron.
""" Logs key data from a Fronius inverter to a CSV file for later analysis. peter.marks@pobox.com """ import requests import json import datetime import time # Set this to the IP address of your inverter host = "192.168.0.112" sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit def main(): print("started") while True: watts = watts_generated() now = time.strftime("%H:%M:%S") line = "%s\t%s\n" % (now, watts) # print(line) write_to_logfile(line) if sample_seconds > 0: time.sleep(sample_seconds) else: return def write_to_logfile(line): today = time.strftime("%Y_%m_%d") file_name = today + ".csv" out_file = open(file_name, "a") out_file.write(line) out_file.close() def watts_generated(): url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System" r = requests.get(url, timeout=60) json_data = r.json() result = json_data["Body"]["Data"]["PAC"]["Values"]["1"] return result if __name__ == "__main__": main()
""" Logs key data from a Fronius inverter to a CSV file for later analysis. peter.marks@pobox.com """ import requests import json import datetime import time # Set this to the IP address of your inverter host = "192.168.0.112" sample_seconds = 60 # how many seconds between samples def main(): print("started") while True: watts = watts_generated() now = datetime.datetime.now() line = "%s\t%s\n" % (now, watts) #print(line) write_to_logfile(line) time.sleep(sample_seconds) def write_to_logfile(line): today = time.strftime("%Y_%m_%d") file_name = today + ".csv" out_file = open(file_name, "a") out_file.write(line) out_file.close() def watts_generated(): url = "http://" + host + "/solar_api/v1/GetInverterRealtimeData.cgi?Scope=System" r = requests.get(url, timeout=60) json_data = r.json() result = json_data["Body"]["Data"]["PAC"]["Values"]["1"] return result if __name__ == "__main__": main()
Fix typo in unit test class of the sphere manifold Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
import unittest import numpy as np import numpy.linalg as la import numpy.random as rnd import numpy.testing as np_testing from pymanopt.manifolds import Sphere class TestSphereManifold(unittest.TestCase): def setUp(self): self.m = m = 100 self.n = n = 50 self.sphere = Sphere(m, n) def test_proj(self): # Construct a random point X on the manifold. X = rnd.randn(self.m, self.n) X /= la.norm(X, "fro") # Construct a vector H in the ambient space. H = rnd.randn(self.m, self.n) # Compare the projections. np_testing.assert_array_almost_equal(H - X * np.trace(X.T.dot(H)), self.sphere.proj(X, H))
import unittest import numpy as np import numpy.linalg as la import numpy.random as rnd import numpy.testing as np_testing from pymanopt.manifolds import Sphere class TestSphereManifold(unittest.TestCase): def setUp(self): self.m = m = 100 self.n = n = 50 self.sphere = Sphere(m, n) def test_proj(self): # Construct a random point (X) on the manifold. X = rnd.randn(self.m, self.n) X /= la.norm(X, "fro") # Construct a vector H) in the ambient space. H = rnd.randn(self.m, self.n) # Compare the projections. np_testing.assert_array_almost_equal(H - X * np.trace(X.T.dot(H)), self.sphere.proj(X, H))
Add index to the message_id column
import sqlite3 def init(conn): c = conn.cursor() c.execute( '''CREATE TABLE IF NOT EXISTS email_log ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `param` TEXT, `email` TEXT, `stage` INTEGER DEFAULT 0, `sender` TEXT, `receiver` TEXT, `subject` TEXT, `date_raw` TEXT, `message_id` TEXT, `attachments` INTEGER, `in_reply_to` TEXT, `in_reply_to_id` INTEGER, `references` TEXT )''') c.execute( '''CREATE INDEX IF NOT EXISTS email_log_idx_message_id ON email_log (message_id) ''')
import sqlite3 def init(conn): c = conn.cursor() c.execute( '''CREATE TABLE IF NOT EXISTS email_log ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `timestamp` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `param` TEXT, `email` TEXT, `stage` INTEGER DEFAULT 0, `sender` TEXT, `receiver` TEXT, `subject` TEXT, `date_raw` TEXT, `message_id` TEXT, `attachments` INTEGER, `in_reply_to` TEXT, `in_reply_to_id` INTEGER, `references` TEXT )''')
Clear counter when Metronome is stopped
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); counter.innerHTML = ""; } }
function Metronome(tempo, beatsPerMeasure){ this.tempo = Number(tempo); this.beatsPerMeasure = Number(beatsPerMeasure); this.interval = null; } Metronome.prototype.start = function(){ var millisecondsToWait = this.tempoToMilliseconds(this.tempo); this.interval = window.setInterval(this.updateCounterView, millisecondsToWait, this.beatsPerMeasure); } Metronome.prototype.tempoToMilliseconds = function(tempo){ return (1000 * 60)/tempo; } Metronome.prototype.updateCounterView = function(beatsPerMeasure){ var counter = document.getElementById("metronome-counter"); var pastBeat = Number(counter.innerHTML); if (pastBeat < beatsPerMeasure){ counter.innerHTML = pastBeat + 1; } else { counter.innerHTML = 1; } Metronome.prototype.stop = function(){ window.clearInterval(this.interval); } }
Switch doc to closure compiler templating
/** * Takes coordinates and properties (optional) and returns a new {@link Point} feature. * * @module turf/point * @category helper * @param {Number[]} coordinates longitude, latitude position (each in decimal degrees) * @param {Object=} properties an Object that is used as the {@link Feature}'s * properties * @returns {Feature<Point>} a Point feature * @example * var pt1 = turf.point([-75.343, 39.984]); * * //=pt1 */ var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; module.exports = function(coordinates, properties) { if (!isArray(coordinates)) throw new Error('Coordinates must be an array'); if (coordinates.length < 2) throw new Error('Coordinates must be at least 2 numbers long'); return { type: "Feature", geometry: { type: "Point", coordinates: coordinates }, properties: properties || {} }; };
/** * Takes coordinates and properties (optional) and returns a new {@link Point} feature. * * @module turf/point * @category helper * @param {number[]} coordinates longitude, latitude position (each in decimal degrees) * @param {Object=} properties an Object that is used as the {@link Feature}'s * properties * @returns {Point} a Point feature * @example * var pt1 = turf.point([-75.343, 39.984]); * * //=pt1 */ var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; module.exports = function(coordinates, properties) { if (!isArray(coordinates)) throw new Error('Coordinates must be an array'); if (coordinates.length < 2) throw new Error('Coordinates must be at least 2 numbers long'); return { type: "Feature", geometry: { type: "Point", coordinates: coordinates }, properties: properties || {} }; };
Handle case when char is mapped to empty (removed) and table is inverted
class Transliterator(object): def __init__(self, mapping, invert=False): self.mapping = [ (v, k) if invert else (k, v) for k, v in mapping.items() ] self._rules = sorted( self.mapping, key=lambda item: len(item[0]), reverse=True, ) @property def rules(self): for r in self._rules: k, v = r if len(k) == 0: continue # for case when char is removed and mapping inverted yield r # Handle the case when one source upper char is represented by # several latin chars, all uppercase. i.e. "CH" instead of "Ch" if len(k) > 1 and k[0].isupper(): yield (k.upper(), v.upper()) def convert(self, input_string): """Transliterate input string.""" for (source_char, translit_char) in self.rules: input_string = input_string.replace(source_char, translit_char) return input_string
class Transliterator(object): def __init__(self, mapping, invert=False): self.mapping = [ (v, k) if invert else (k, v) for k, v in mapping.items() ] self._rules = sorted( self.mapping, key=lambda item: len(item[0]), reverse=True, ) @property def rules(self): for r in self._rules: yield r # Handle the case when one source upper char is represented by # several latin chars, all uppercase. i.e. "CH" instead of "Ch" k, v = r if len(k) > 1 and k[0].isupper(): yield (k.upper(), v.upper()) def convert(self, input_string): """Transliterate input string.""" for (source_char, translit_char) in self.rules: input_string = input_string.replace(source_char, translit_char) return input_string
Fix incorrect Grid drawPath method.
/*globals Polygon*/ /*exported Grid*/ var Grid = (function() { 'use strict'; function Grid( options ) { Polygon.call( this ); options = options || {}; this.width = options.width || 1; this.height = options.height || 1; this.cols = options.cols || 1; this.rows = options.rows || 1; this.generate(); } Grid.prototype = Object.create( Polygon.prototype ); Grid.prototype.constructor = Grid; Grid.prototype.generate = function() { var colWidth = this.width / this.cols, rowHeight = this.height / this.rows; var x, y; for ( y = 0; y < this.rows; y++ ) { for ( x = 0; x < this.cols; x++ ) { this.vertices.push( colWidth * x ); this.vertices.push( rowHeight * y ); } } }; Grid.prototype.drawPath = function( ctx ) { var cols = this.cols, rows = this.rows; var colWidth = this.width / cols, rowHeight = this.height / rows; var vertexCount = 0.5 * this.vertices.length; var x, y; for ( var i = 0; i < vertexCount; i++ ) { x = i % cols; y = Math.floor( i / rows ); ctx.rect( x * colWidth, y * rowHeight, colWidth, rowHeight ); } }; return Grid; }) ();
/*globals Polygon*/ /*exported Grid*/ var Grid = (function() { 'use strict'; function Grid( options ) { Polygon.call( this ); options = options || {}; this.width = options.width || 1; this.height = options.height || 1; this.cols = options.cols || 1; this.rows = options.rows || 1; this.generate(); } Grid.prototype = Object.create( Polygon.prototype ); Grid.prototype.constructor = Grid; Grid.prototype.generate = function() { var colWidth = this.width / this.cols, rowHeight = this.height / this.rows; var x, y; for ( y = 0; y < this.rows; y++ ) { for ( x = 0; x < this.cols; x++ ) { this.vertices.push( colWidth * x ); this.vertices.push( rowHeight * y ); } } }; Grid.prototype.drawPath = function( ctx ) { var colWidth = this.width / this.cols, rowHeight = this.height / this.rows; var vertexCount = 0.5 * this.vertices.length; var x, y; for ( var i = 0; i < vertexCount; i++ ) { x = i % vertexCount; y = Math.floor( i / vertexCount ); ctx.rect( x * colWidth, y * rowHeight, colWidth, rowHeight ); } }; return Grid; }) ();
Drop <p> tags and replace </p> with <br> This was causing an excessive amount of bottom padding
package com.github.mobile.android.util; import android.text.Html.ImageGetter; /** * Html Utilities */ public class Html { /** * Encode HTML * * @param html * @return html */ public static CharSequence encode(String html) { return encode(html, null); } /** * Encode HTML * * @param html * @param imageGetter * @return html */ public static CharSequence encode(String html, ImageGetter imageGetter) { if (html == null) return ""; if (html.length() == 0) return html; // These add extra padding that should be styled explicitly html = html.replace("<p>", ""); html = html.replace("</p>", "<br>"); while (html.length() > 0) if (html.startsWith("<br>")) html = html.substring(4); else if (html.endsWith("<br>")) html = html.substring(0, html.length() - 4); else break; return android.text.Html.fromHtml(html, imageGetter, null); } }
package com.github.mobile.android.util; import android.text.Html.ImageGetter; /** * Html Utilities */ public class Html { /** * Encode HTML * * @param html * @return html */ public static CharSequence encode(String html) { return encode(html, null); } /** * Encode HTML * * @param html * @param imageGetter * @return html */ public static CharSequence encode(String html, ImageGetter imageGetter) { if (html == null) return ""; if (html.length() == 0) return html; // These add extra padding that should be styled explicitly if (html.startsWith("<p>") && html.endsWith("</p>")) html = html.substring(3, html.length() - 4); return android.text.Html.fromHtml(html, imageGetter, null); } }