text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
contrib/exporters/allinone: Fix default config file name
/* * Copyright (C) 2019 IBM, 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 ofthe 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 specificlanguage governing permissions and * limitations under the License. * */ package main import ( aws "github.com/skydive-project/skydive/contrib/exporters/awsflowlogs/mod" "github.com/skydive-project/skydive/contrib/exporters/core" sa "github.com/skydive-project/skydive/contrib/exporters/secadvisor/mod" ) func main() { core.Main("/etc/skydive/allinone.yml") } func init() { core.TransformerHandlers.Register("awsflowlogs", aws.NewTransform, false) core.TransformerHandlers.Register("vpclogs", sa.NewTransform, false) }
/* * Copyright (C) 2019 IBM, 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 ofthe 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 specificlanguage governing permissions and * limitations under the License. * */ package main import ( aws "github.com/skydive-project/skydive/contrib/exporters/awsflowlogs/mod" "github.com/skydive-project/skydive/contrib/exporters/core" sa "github.com/skydive-project/skydive/contrib/exporters/secadvisor/mod" ) func main() { core.Main("/etc/skydive/uber.yml") } func init() { core.TransformerHandlers.Register("awsflowlogs", aws.NewTransform, false) core.TransformerHandlers.Register("vpclogs", sa.NewTransform, false) }
Use PHP 8 constructor property promotion
<?php declare(strict_types = 1); /** * /src/Serializer/CollectionNormalizer.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Serializer\Normalizer; use Doctrine\Common\Collections\Collection; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use function is_object; /** * Class CollectionNormalizer * * @package App\Serializer * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class CollectionNormalizer implements NormalizerInterface { public function __construct( private ObjectNormalizer $normalizer, ) { } /** * {@inheritdoc} */ public function normalize($object, ?string $format = null, array $context = []): array { $output = []; foreach ($object as $value) { $output[] = $this->normalizer->normalize($value, $format, $context); } return $output; } /** * {@inheritdoc} */ public function supportsNormalization($data, ?string $format = null): bool { return $format === 'json' && is_object($data) && $data instanceof Collection && is_object($data->first()); } }
<?php declare(strict_types = 1); /** * /src/Serializer/CollectionNormalizer.php * * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ namespace App\Serializer\Normalizer; use Doctrine\Common\Collections\Collection; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use function is_object; /** * Class CollectionNormalizer * * @package App\Serializer * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com> */ class CollectionNormalizer implements NormalizerInterface { private ObjectNormalizer $normalizer; public function __construct(ObjectNormalizer $normalizer) { $this->normalizer = $normalizer; } /** * {@inheritdoc} */ public function normalize($object, ?string $format = null, array $context = []): array { $output = []; foreach ($object as $value) { $output[] = $this->normalizer->normalize($value, $format, $context); } return $output; } /** * {@inheritdoc} */ public function supportsNormalization($data, ?string $format = null): bool { return $format === 'json' && is_object($data) && $data instanceof Collection && is_object($data->first()); } }
Fix for it not detecting the sock_modules folder
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ gitclone: { docs: { options: { directory: "site", repository: "https://github.com/SockDrawer/SockBot.git", branch: "gh-pages" } } }, mkdocs: { dist: { src: '.', options: { clean: true } } }, jsdoc : { dist : { src: ['*.js', 'sock_modules/*.js', 'sock_modules/**/*.js'], options: { destination: 'site/docs' } } }, 'gh-pages': { options: { // The default commit message for the gh-pages branch base: 'site', message: 'push documentation automatically', repo: 'https://' + process.env.GH_TOKEN + '@github.com/SockDrawer/SockBot' }, src: "**" } }); // Load the plugins grunt.loadNpmTasks('grunt-mkdocs'); grunt.loadNpmTasks('grunt-git'); grunt.loadNpmTasks('grunt-jsdoc'); grunt.loadNpmTasks('grunt-gh-pages'); // Default task(s). grunt.registerTask('generate-docs', ['mkdocs', 'jsdoc', 'gh-pages']); grunt.registerTask('default', ['mkdocs', 'jsdoc', 'gh-pages']); };
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ gitclone: { docs: { options: { directory: "site", repository: "https://github.com/SockDrawer/SockBot.git", branch: "gh-pages" } } }, mkdocs: { dist: { src: '.', options: { clean: true } } }, jsdoc : { dist : { src: ['*.js', 'sock-modules/**/*.js'], options: { destination: 'site/docs' } } }, 'gh-pages': { options: { // The default commit message for the gh-pages branch base: 'site', message: 'push documentation automatically', repo: 'https://' + process.env.GH_TOKEN + '@github.com/SockDrawer/SockBot' }, src: "**" } }); // Load the plugins grunt.loadNpmTasks('grunt-mkdocs'); grunt.loadNpmTasks('grunt-git'); grunt.loadNpmTasks('grunt-jsdoc'); grunt.loadNpmTasks('grunt-gh-pages'); // Default task(s). grunt.registerTask('generate-docs', ['mkdocs', 'jsdoc', 'gh-pages']); grunt.registerTask('default', ['mkdocs', 'jsdoc', 'gh-pages']); };
Add a way to dump the header during setup.py runs
import os import re import sys import cffi _directive_re = re.compile(r'^\s*#.*?$(?m)') def make_ffi(module_path, crate_path, cached_header_filename=None): """Creates a FFI instance for the given configuration.""" if cached_header_filename is not None and \ os.path.isfile(cached_header_filename): with open(cached_header_filename, 'rb') as f: header = f.read() else: from .bindgen import generate_header header = generate_header(crate_path) header = _directive_re.sub('', header) if os.environ.get('SNAEK_DEBUG_HEADER') == '1': sys.stderr.write('/* generated header for "%s" */\n' % module_path) sys.stderr.write(header) sys.stderr.write('\n') sys.stderr.flush() ffi = cffi.FFI() ffi.cdef(header) ffi.set_source(module_path, None) return ffi
import os import re import cffi _directive_re = re.compile(r'^\s*#.*?$(?m)') def make_ffi(module_path, crate_path, cached_header_filename=None): """Creates a FFI instance for the given configuration.""" if cached_header_filename is not None and \ os.path.isfile(cached_header_filename): with open(cached_header_filename, 'rb') as f: header = f.read() else: from .bindgen import generate_header header = generate_header(crate_path) header = _directive_re.sub('', header) ffi = cffi.FFI() ffi.cdef(header) ffi.set_source(module_path, None) return ffi
Add test for no validator case
import { moduleForComponent, test } from 'ember-qunit'; import { click, fillIn, find, focus, triggerEvent } from 'ember-native-dom-helpers'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('ember-x-editable', 'Integration | Component | ember x editable', { integration: true }); test('mouseEnter/mouseLeave', async function(assert) { this.set('mouseInsideComponent', false); this.render(hbs`{{x-editable-text mouseInsideComponent=mouseInsideComponent validator=validator value=value}}`); await triggerEvent(find('.x-base'), 'mouseover'); assert.equal(this.get('mouseInsideComponent'), true); await triggerEvent(find('.x-base'), 'mouseout'); assert.equal(this.get('mouseInsideComponent'), false); }); test('Empty value', async function(assert) { this.set('value', 'Empty'); this.render(hbs`{{x-editable-text validator=validator value=value}}`); await focus(find('.x-base div input')); assert.equal(this.get('value'), ''); }); test('No validator passed', async function(assert) { this.set('value', 'foo'); this.render(hbs`{{x-editable-text value=value}}`); await fillIn(find('.x-base div input'), ''); await click('.editable-submit'); assert.equal(this.get('value'), 'Empty'); });
import { moduleForComponent, test } from 'ember-qunit'; import { find, focus, triggerEvent } from 'ember-native-dom-helpers'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('ember-x-editable', 'Integration | Component | ember x editable', { integration: true }); test('mouseEnter/mouseLeave', async function(assert) { this.set('mouseInsideComponent', false); this.render(hbs`{{x-editable-text mouseInsideComponent=mouseInsideComponent validator=validator value=value}}`); await triggerEvent(find('.x-base'), 'mouseover'); assert.equal(this.get('mouseInsideComponent'), true); await triggerEvent(find('.x-base'), 'mouseout'); assert.equal(this.get('mouseInsideComponent'), false); }); test('Empty value', async function(assert) { this.set('value', 'Empty'); this.render(hbs`{{x-editable-text validator=validator value=value}}`); await focus(find('.x-base div input')); assert.equal(this.get('value'), ''); });
Support multiple servers and retries
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import sys from time import time from ntplib import NTPClient from qrl.core import logger ntp_servers = ['pool.ntp.org', 'ntp.ubuntu.com'] NTP_VERSION = 3 NTP_RETRIES = 6 drift = None def get_ntp_response(): for retry in range(NTP_RETRIES): ntp_server = ntp_servers[retry % len(ntp_servers)] try: ntp_client = NTPClient() response = ntp_client.request(ntp_server, version=NTP_VERSION) except Exception as e: logger.warning(e) continue return response # FIXME: Provide some proper clean before exiting logger.fatal("Could not contact NTP servers after %d retries", NTP_RETRIES) sys.exit(-1) def getNTP(): ntp_timestamp = 0 response = get_ntp_response() if response: ntp_timestamp = int(response.tx_time) return ntp_timestamp def setDrift(): global drift response = get_ntp_response() if not response: return response drift = response.offset def getTime(): global drift curr_time = drift + int(time()) return curr_time
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import sys from time import time from ntplib import NTPClient from qrl.core import logger ntp_server = 'pool.ntp.org' version = 3 times = 5 drift = None def get_ntp_response(): try: ntp_client = NTPClient() response = ntp_client.request(ntp_server, version=version) except Exception as e: logger.exception(e) sys.exit(0) return response def getNTP(): ntp_timestamp = 0 response = get_ntp_response() if response: ntp_timestamp = int(response.tx_time) return ntp_timestamp def setDrift(): global drift response = get_ntp_response() if not response: return response drift = response.offset def getTime(): global drift curr_time = drift + int(time()) return curr_time
Check whether the asset url start with a slash
<?php use Silex\Application; use Silex\Provider\TwigServiceProvider; use Silex\Provider\RoutingServiceProvider; use Silex\Provider\ValidatorServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Silex\Provider\HttpFragmentServiceProvider; $app = new Application(); $app->register(new RoutingServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new ServiceControllerServiceProvider()); $app->register(new TwigServiceProvider()); $app->register(new HttpFragmentServiceProvider()); $app['twig'] = $app->extend('twig', function ($twig, $app) { // add custom globals, filters, tags, ... $twig->addFunction(new \Twig_SimpleFunction('asset', function ($asset) use ($app) { return $app['request_stack']->getMasterRequest()->getBasepath().'/'.ltrim($asset, '/'); })); return $twig; }); return $app;
<?php use Silex\Application; use Silex\Provider\TwigServiceProvider; use Silex\Provider\RoutingServiceProvider; use Silex\Provider\ValidatorServiceProvider; use Silex\Provider\ServiceControllerServiceProvider; use Silex\Provider\HttpFragmentServiceProvider; $app = new Application(); $app->register(new RoutingServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new ServiceControllerServiceProvider()); $app->register(new TwigServiceProvider()); $app->register(new HttpFragmentServiceProvider()); $app['twig'] = $app->extend('twig', function ($twig, $app) { // add custom globals, filters, tags, ... $twig->addFunction(new \Twig_SimpleFunction('asset', function ($asset) use ($app) { return $app['request_stack']->getMasterRequest()->getBasepath().'/'.$asset; })); return $twig; }); return $app;
Make rad entity repository concrete This allows us to configure doctrine to use it as default repository (see 759bcc44ca1ec5a13c7dbf8727d8edd587c35e46). The default alias generation method has been rewritten using the doctrine's inflector.
<?php namespace Knp\RadBundle\Doctrine; use Doctrine\ORM\EntityRepository as BaseEntityRepository; use Doctrine\ORM\QueryBuilder; use Doctrine\Common\Util\Inflector; class EntityRepository extends BaseEntityRepository { public function __call($method, $arguments) { if (0 === strpos($method, 'find')) { if (method_exists($this, $builder = 'build'.substr($method, 4))) { $qb = call_user_func_array(array($this, $builder), $arguments); return $qb->getQuery()->getResult(); } } return parent::__call($method, $arguments); } protected function build() { return $this->createQueryBuilder($this->getAlias()); } protected function buildOne($id) { return $this->build()->where($this->getAlias().'.id = '.intval($id)); } protected function buildAll() { return $this->build(); } protected function getAlias() { $name = basename(str_replace('\\', '/', $this->getClassName())); return Inflector::tableize($name); } }
<?php namespace Knp\RadBundle\Doctrine; use Doctrine\ORM\EntityRepository as BaseEntityRepository; use Doctrine\ORM\QueryBuilder; abstract class EntityRepository extends BaseEntityRepository { public function __call($method, $arguments) { if (0 === strpos($method, 'find')) { if (method_exists($this, $builder = 'build'.substr($method, 4))) { $qb = call_user_func_array(array($this, $builder), $arguments); return $qb->getQuery()->getResult(); } } return parent::__call($method, $arguments); } protected function build() { return $this->createQueryBuilder($this->getAlias()); } protected function buildOne($id) { return $this->build()->where($this->getAlias().'.id = '.intval($id)); } protected function buildAll() { return $this->build(); } protected function getAlias() { $reflection = new \ReflectionObject($this); return strtolower( preg_replace(array('/Repository$/', '/[a-z0-9]/'), '', $reflection->getShortName()) ); } }
Create required known_hosts file if it does not exists
import os import logging from ...subprocess import check_output def _get_known_hosts_path(): ssh_dir = os.path.expanduser('~root/.ssh') if not os.path.isdir(ssh_dir): os.makedirs(ssh_dir) return os.path.join(ssh_dir, 'known_hosts') def ensure_known_hosts(hosts): known_hosts_path = _get_known_hosts_path() if not os.path.exists(known_hosts_path): open(known_hosts_path, 'a+').close() modified = False with open(known_hosts_path, 'r+') as f: contents = f.read() if not contents.endswith('\n'): contents += '\n' for host in hosts: if host not in contents: logging.info('Adding {} ssh key to roots ssh known_hosts file'.format(host)) command = ['sh', '-c', 'ssh-keyscan -t rsa {}'.format(host)] result = check_output(command, demote=False) contents += result modified = True if modified: f.seek(0) f.write(contents)
import os import logging from ...subprocess import check_output def _get_known_hosts_path(): ssh_dir = os.path.expanduser('~root/.ssh') if not os.path.isdir(ssh_dir): os.makedirs(ssh_dir) return os.path.join(ssh_dir, 'known_hosts') def ensure_known_hosts(hosts): known_hosts_path = _get_known_hosts_path() modified = False with open(known_hosts_path, 'r+') as f: contents = f.read() if not contents.endswith('\n'): contents += '\n' for host in hosts: if host not in contents: logging.info('Adding {} ssh key to roots ssh known_hosts file'.format(host)) command = ['sh', '-c', 'ssh-keyscan -t rsa {}'.format(host)] result = check_output(command, demote=False) contents += result modified = True if modified: f.seek(0) f.write(contents)
Fix SCSS engine error message
'use strict'; var Engine = require('./engine'); var herit = require('herit'); var path = require('path'); module.exports = herit(Engine, { defaults: function () { return { paths: [], indentedSyntax: false }; }, run: function (asset, cb) { try { var sass = require('node-sass'); sass.render({ data: asset.source, indentedSyntax: this.options.indentedSyntax, includePaths: this.options.paths.concat(path.dirname(asset.abs)), success: function (res) { asset.source = res.css; if (!asset.ext()) asset.exts.push('css'); cb(); }, error: function (er) { cb(new Error('Line ' + er.line + ': ' + er.message)); } }); } catch (er) { cb(er); } } });
'use strict'; var Engine = require('./engine'); var herit = require('herit'); var path = require('path'); module.exports = herit(Engine, { defaults: function () { return { paths: [], indentedSyntax: false }; }, run: function (asset, cb) { try { var sass = require('node-sass'); sass.render({ data: asset.source, indentedSyntax: this.options.indentedSyntax, includePaths: this.options.paths.concat(path.dirname(asset.abs)), success: function (res) { asset.source = res.css; if (!asset.ext()) asset.exts.push('css'); cb(); }, error: function (er) { cb(new Error(er)); } }); } catch (er) { cb(er); } } });
Fix empty servername problem when initially adding server.
package org.muteswan.client.data; import org.json.JSONException; import org.json.JSONObject; import org.muteswan.client.MuteLog; public class MuteswanServer { private String hostname; private ServerInfo serverInfo; public class ServerInfo { public String Name = ""; public void setName(String arg) { this.Name = arg; } public String getName() { return Name; } } public ServerInfo getServerInfo() { return serverInfo; } public String getHostname() { return hostname; } public String toString() { if (serverInfo.getName() != null && !serverInfo.getName().equals("") && !serverInfo.getName().equals("defaultname")) { return serverInfo.getName(); } else { return serverInfo.getName() + " (" + getHostname() + ")"; } } public void init(String server, JSONObject jsonObj) { this.hostname = server; serverInfo = new ServerInfo(); try { serverInfo.setName(jsonObj.getString("Name")); } catch (JSONException e) { e.printStackTrace(); return; } } }
package org.muteswan.client.data; import org.json.JSONException; import org.json.JSONObject; public class MuteswanServer { private String hostname; private ServerInfo serverInfo; public class ServerInfo { public String Name = ""; public void setName(String arg) { this.Name = arg; } public String getName() { return Name; } } public ServerInfo getServerInfo() { return serverInfo; } public String getHostname() { return hostname; } public String toString() { if (serverInfo.getName() != null && serverInfo.getName() != "" && !serverInfo.getName().equals("defaultname")) { return serverInfo.getName(); } else { return serverInfo.getName() + " (" + getHostname() + ")"; } } public void init(String server, JSONObject jsonObj) { this.hostname = server; serverInfo = new ServerInfo(); try { serverInfo.setName(jsonObj.getString("Name")); } catch (JSONException e) { e.printStackTrace(); return; } } }
Enable tunnel only through environment variable
module.exports = { // Minimal configuration needed 'SLACK_CLIENT_ID': process.env.SLACK_CLIENT_ID || 'YOUR_SLACK_CLIENT_ID', 'SLACK_SECRET': process.env.SLACK_SECRET || 'YOUR_SLACK_SECRET', 'VERIFICATION_TOKEN': process.env.VERIFICATION_TOKEN || 'YOUR_VERIFICATION_TOKEN', 'API_KEY': process.env.API_KEY || 'YOUR_TRUSTPILOT_API_KEY', 'API_SECRET': process.env.API_SECRET || 'YOUR_TRUSTPILOT_API_SECRET', 'BUSINESS_USER_NAME': process.env.BUSINESS_USER_NAME || 'YOUR_TRUSTPILOT_BUSINESS_USER_NAME', 'BUSINESS_USER_PASS': process.env.BUSINESS_USER_PASS || 'YOUR_TRUSTPILOT_BUSINESS_USER_PASS', 'BUSINESS_UNIT_ID': process.env.BUSINESS_UNIT_ID || 'YOUR_TRUSTPILOT_BUSINESS_UNIT_ID', // Extra configuration (storage etc.) 'BOTKIT_STORAGE_TYPE': process.env.BOTKIT_STORAGE_TYPE || 'file', 'PORT': process.env.PORT || '7142', 'API_HOST': process.env.API_HOST || 'https://api.trustpilot.com', 'ENABLE_LOCAL_TUNNEL': process.env.ENABLE_LOCAL_TUNNEL, };
module.exports = { // Minimal configuration needed 'SLACK_CLIENT_ID': process.env.SLACK_CLIENT_ID || 'YOUR_SLACK_CLIENT_ID', 'SLACK_SECRET': process.env.SLACK_SECRET || 'YOUR_SLACK_SECRET', 'VERIFICATION_TOKEN': process.env.VERIFICATION_TOKEN || 'YOUR_VERIFICATION_TOKEN', 'API_KEY': process.env.API_KEY || 'YOUR_TRUSTPILOT_API_KEY', 'API_SECRET': process.env.API_SECRET || 'YOUR_TRUSTPILOT_API_SECRET', 'BUSINESS_USER_NAME': process.env.BUSINESS_USER_NAME || 'YOUR_TRUSTPILOT_BUSINESS_USER_NAME', 'BUSINESS_USER_PASS': process.env.BUSINESS_USER_PASS || 'YOUR_TRUSTPILOT_BUSINESS_USER_PASS', 'BUSINESS_UNIT_ID': process.env.BUSINESS_UNIT_ID || 'YOUR_TRUSTPILOT_BUSINESS_UNIT_ID', // Extra configuration (storage etc.) 'BOTKIT_STORAGE_TYPE': process.env.BOTKIT_STORAGE_TYPE || 'file', 'PORT': process.env.PORT || '7142', 'API_HOST': process.env.API_HOST || 'https://api.trustpilot.com', 'ENABLE_LOCAL_TUNNEL': process.env.ENABLE_LOCAL_TUNNEL || 'false', };
Patch parts of `FloorDivideOp` in source order.
import BinaryOpPatcher from './BinaryOpPatcher.js'; export default class FloorDivideOpPatcher extends BinaryOpPatcher { /** * LEFT '//' RIGHT */ patchAsExpression() { let operator = this.getOperatorToken(); // `a // b` → `Math.floor(a // b` // ^^^^^^^^^^^ this.insert(this.contentStart, 'Math.floor('); this.left.patch(); // `Math.floor(a // b)` → `Math.floor(a / b)` // ^^ ^ this.overwrite(operator.start, operator.end, '/'); this.right.patch(); // `Math.floor(a // b` → `Math.floor(a // b)` // ^ this.insert(this.contentEnd, ')'); } }
import BinaryOpPatcher from './BinaryOpPatcher.js'; export default class FloorDivideOpPatcher extends BinaryOpPatcher { /** * LEFT '//' RIGHT */ patchAsExpression() { let operator = this.getOperatorToken(); // `a // b` → `Math.floor(a // b` // ^^^^^^^^^^^ this.insert(this.contentStart, 'Math.floor('); // Patch LEFT and RIGHT. super.patchAsExpression(); // `Math.floor(a // b` → `Math.floor(a // b)` // ^ this.insert(this.contentEnd, ')'); // `Math.floor(a // b)` → `Math.floor(a / b)` // ^^ ^ this.overwrite(operator.start, operator.end, '/'); } }
Use correct MIT license classifier. `LICENSE` contains the MIT/Expat license but `setup.py` uses the LGPLv3 classifier. I assume the later is an oversight.
from setuptools import setup setup( name='pytest-flakes', description='pytest plugin to check source code with pyflakes', long_description=open("README.rst").read(), license="MIT license", version='1.0.1', author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt', author_email='florian.schulze@gmx.net', url='https://github.com/fschulze/pytest-flakes', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Testing', ], py_modules=['pytest_flakes'], entry_points={'pytest11': ['flakes = pytest_flakes']}, install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])
from setuptools import setup setup( name='pytest-flakes', description='pytest plugin to check source code with pyflakes', long_description=open("README.rst").read(), license="MIT license", version='1.0.1', author='Florian Schulze, Holger Krekel and Ronny Pfannschmidt', author_email='florian.schulze@gmx.net', url='https://github.com/fschulze/pytest-flakes', classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Testing', ], py_modules=['pytest_flakes'], entry_points={'pytest11': ['flakes = pytest_flakes']}, install_requires=['pytest-cache', 'pytest>=2.3.dev14', 'pyflakes'])
Use singleton method instead of share method on service provider registration for Laravel 5.4 support
<?php namespace Thomaswelton\LaravelGravatar; use Illuminate\Support\ServiceProvider; class LaravelGravatarServiceProvider extends ServiceProvider { /** * Boot the service provider. */ public function boot() { $this->setupConfig(); } /** * Setup the config. */ protected function setupConfig() { $source = realpath(__DIR__.'/../config/gravatar.php'); $this->publishes([$source => config_path('gravatar.php')]); $this->mergeConfigFrom($source, 'gravatar'); } /** * Register the service provider. */ public function register() { $this->app->singleton('gravatar', function ($app) { return new Gravatar($this->app['config']); }); } }
<?php namespace Thomaswelton\LaravelGravatar; use Illuminate\Support\ServiceProvider; class LaravelGravatarServiceProvider extends ServiceProvider { /** * Boot the service provider. */ public function boot() { $this->setupConfig(); } /** * Setup the config. */ protected function setupConfig() { $source = realpath(__DIR__.'/../config/gravatar.php'); $this->publishes([$source => config_path('gravatar.php')]); $this->mergeConfigFrom($source, 'gravatar'); } /** * Register the service provider. */ public function register() { $this->app['gravatar'] = $this->app->share(function ($app) { return new Gravatar($this->app['config']); }); } }
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Fix failed tempest tests with KeystoneV2 Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4 Signed-off-by: Ruslan Aliev <f0566964e0d23c2ac49e399e34dbe87edb487aa1@mirantis.com>
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None): super(Manager, self).__init__(credentials) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
# (C) Copyright 2016 Hewlett Packard Enterprise Development Company LP # # 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 tempest import clients from freezer_api.tests.freezer_api_tempest_plugin.services import\ freezer_api_client class Manager(clients.Manager): def __init__(self, credentials=None, service=None): super(Manager, self).__init__(credentials, service) self.freezer_api_client = freezer_api_client.FreezerApiClient( self.auth_provider)
Set max width and height for inventory items
'use strict'; const React = require('react'); const {string} = React.PropTypes; const InventoryDetail = React.createClass({ displayName: 'InventoryDetail', propTypes: { // state name: string.isRequired, type: string.isRequired, image: string.isRequired }, render() { return ( <div style={styles.container}> <img title={this.props.name} src={this.props.image} style={styles.image} /> </div> ); } }); const styles = { container: { textAlign: 'center', float: 'none' }, image: { maxWidth: '27vw', maxHeight: '80vh', marginTop: '10%', marginRight: '10%' } }; module.exports = InventoryDetail;
'use strict'; const React = require('react'); const {string} = React.PropTypes; const InventoryDetail = React.createClass({ displayName: 'InventoryDetail', propTypes: { // state name: string.isRequired, type: string.isRequired, image: string.isRequired }, render() { return ( <div style={styles.container}> <img title={this.props.name} src={this.props.image} style={styles.image} /> </div> ); } }); const styles = { container: { textAlign: 'center', float: 'none' }, image: { height: '80vh', marginTop: '10%', marginRight: '10%' } }; module.exports = InventoryDetail;
JCR-2357: Duplicate entries in the index - javadoc git-svn-id: 02b679d096242155780e1604e997947d154ee04a@828343 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.jackrabbit.core.observation; import javax.jcr.observation.EventIterator; import javax.jcr.observation.EventListener; /** * Defines a marker interface for {@link javax.jcr.observation.EventListener} * implementations that wish a synchronous notification of changes to the * workspace. That is, a <code>SynchronousEventListener</code> is called before * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular * {@link javax.jcr.observation.EventListener} might be called after * <code>save()</code> returns. * <p/> * <b>Important note</b>: an implementation of {@link SynchronousEventListener} * <b>must not</b> modify content with the thread that calls {@link * #onEvent(EventIterator)} otherwise inconsistencies may occur. */ public interface SynchronousEventListener extends EventListener { }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.jackrabbit.core.observation; import javax.jcr.observation.EventListener; /** * Defines a marker interface for {@link javax.jcr.observation.EventListener} * implementations that wish a synchronous notification of changes to the * workspace. That is, a <code>SynchronousEventListener</code> is called before * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular * {@link javax.jcr.observation.EventListener} might be called after * <code>save()</code> returns. */ public interface SynchronousEventListener extends EventListener { }
Use a separate method to get all peers of a torrent
import urllib from random import randint from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} def __init__(self): self.peer_id = urllib.quote("-AZ2470-" + "".join([str(randint(0, 9)) for i in xrange(12)])) @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def _get_peers(self, torrent): peers = {} for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent, self.peer_id) peers.update({ip: port for ip, port in tracker.peers}) return peers def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] peers = self._get_peers(torrent) print peers
from urlparse import urlparse from torrent import Torrent from trackers.udp import UDPTracker class Client(object): __TORRENTS = {} @property def torrents(self): return self.__TORRENTS @torrents.setter def torrents(self, new_torrent): self.__TORRENTS[new_torrent] = Torrent(new_torrent) def download(self, torrent): if not torrent in self.__TORRENTS: raise ValueError('%s not here' % torrent) torrent = self.__TORRENTS[torrent] for url in torrent.urls: parsed = urlparse(url) if parsed.scheme == 'udp': _, url, port = url.split(":") tracker = UDPTracker(url[2:], int(port), torrent) print tracker.peers
Add title to main frame
package viewer; import maze.Maze; import javax.swing.*; import java.awt.*; /** * @author Nick Hirakawa */ public class MazeViewer extends JFrame { private JPanel panel; public MazeViewer(Maze maze, int cellSize){ this(maze, cellSize, cellSize / 4); } public MazeViewer(Maze maze, int cellSize, int gapSize){ setTitle("jMaze"); this.panel = new MazePanel(maze, cellSize, gapSize); setContentPane(this.panel); int width = (maze.getWidth() + 1) * (cellSize + gapSize) + gapSize; int height = (maze.getHeight() + 1) * (cellSize + gapSize) + gapSize; this.setPreferredSize(new Dimension(width, height)); this.pack(); this.setVisible(true); } }
package viewer; import maze.Maze; import javax.swing.*; import java.awt.*; /** * @author Nick Hirakawa */ public class MazeViewer extends JFrame { private JPanel panel; public MazeViewer(Maze maze, int cellSize){ this(maze, cellSize, cellSize / 4); } public MazeViewer(Maze maze, int cellSize, int gapSize){ this.panel = new MazePanel(maze, cellSize, gapSize); setContentPane(this.panel); int width = (maze.getWidth() + 1) * (cellSize + gapSize) + gapSize; int height = (maze.getHeight() + 1) * (cellSize + gapSize) + gapSize; this.setPreferredSize(new Dimension(width, height)); this.pack(); this.setVisible(true); } }
Update bluprint to install latest telling-stories-dashboard
/*jshint node:true*/ var existsSync = require('exists-sync'); module.exports = { description: 'Install telling-stories dependencies', normalizeEntityName: function() {}, afterInstall: function() { // Register shutdown animation to the end of every acceptance test if (existsSync('tests/helpers/module-for-acceptance.js')) { this.insertIntoFile('tests/helpers/module-for-acceptance.js', " afterEach = window.require('telling-stories').shutdown(afterEach);", { after: "let afterEach = options.afterEach && options.afterEach.apply(this, arguments);\n" }); } return this.addAddonsToProject({ packages: [ { name: 'ember-cli-page-object', version: '^1.6.0' }, { name: 'telling-stories-dashboard', version: '1.0.0-alpha.3' } ] }); } };
/*jshint node:true*/ var existsSync = require('exists-sync'); module.exports = { description: 'Install telling-stories dependencies', normalizeEntityName: function() {}, afterInstall: function() { // Register shutdown animation to the end of every acceptance test if (existsSync('tests/helpers/module-for-acceptance.js')) { this.insertIntoFile('tests/helpers/module-for-acceptance.js', " afterEach = window.require('telling-stories').shutdown(afterEach);", { after: "let afterEach = options.afterEach && options.afterEach.apply(this, arguments);\n" }); } return this.addAddonsToProject({ packages: [ { name: 'ember-cli-page-object', version: '^1.6.0' }, { name: 'telling-stories-dashboard', version: '1.0.0-alpha.2' } ] }); } };
Update selectors following update from master.
( function( $ ) { 'use strict'; var api = wp.customize; // Nav bar text color. api( 'amp_navbar_color', function( value ) { value.bind( function( to ) { $( 'nav.amp-wp-title-bar a' ).css( 'color', to ); $( 'nav.amp-wp-title-bar div' ).css( 'color', to ); } ); } ); // Nav bar background color. api( 'amp_navbar_background', function( value ) { value.bind( function( to ) { $( 'nav.amp-wp-title-bar' ).css( 'background', to ); } ); } ); // Nav bar site icon. api( 'site_icon', function( value ) { value.bind( function( to ) { var ampSiteIcon = $( '.site-icon' ), siteIcon = $( '.site-icon > img' ); if ( '' === to ) { ampSiteIcon.addClass( 'hidden' ); } else { var request = wp.ajax.post( 'get-attachment', { id: to } ).done( function( response ) { ampSiteIcon.removeClass( 'hidden' ); ampSiteIcon.removeClass( '-amp-notbuilt' ); ampSiteIcon.attr( 'src', response.url ); siteIcon.attr( 'src', response.url ); } ); } } ); } ); } )( jQuery );
( function( $ ) { 'use strict'; var api = wp.customize; // Nav bar text color. api( 'amp_navbar_color', function( value ) { value.bind( function( to ) { $( 'nav.title-bar a' ).css( 'color', to ); $( 'nav.title-bar div' ).css( 'color', to ); } ); } ); // Nav bar background color. api( 'amp_navbar_background', function( value ) { value.bind( function( to ) { $( 'nav.title-bar' ).css( 'background', to ); } ); } ); // Nav bar site icon. api( 'site_icon', function( value ) { value.bind( function( to ) { var ampSiteIcon = $( '.site-icon' ), siteIcon = $( '.site-icon > img' ); if ( '' === to ) { ampSiteIcon.addClass( 'hidden' ); } else { var request = wp.ajax.post( 'get-attachment', { id: to } ).done( function( response ) { ampSiteIcon.removeClass( 'hidden' ); ampSiteIcon.removeClass( '-amp-notbuilt' ); ampSiteIcon.attr( 'src', response.url ); siteIcon.attr( 'src', response.url ); } ); } } ); } ); } )( jQuery );
Use a much simpler (and faster) output building step. This implementation is much easeir to read, and is a lot clearer about what's going on. It turns out that it's about 3 times faster in python too!
import random import time def counting_sort(array): k = max(array) counts = [0]*(k+1) for x in array: counts[x] += 1 output = [] for x in xrange(k+1): output += [x]*counts[x] return output if __name__ == "__main__": assert counting_sort([5,3,2,1]) == [1,2,3,5] x = [] for i in range(0, 1000): x.append(random.randint(0, 20)) assert counting_sort(x) == sorted(x) for i in range(0, 10000000): x.append(random.randint(0, 4000)) start = time.time() counting_sort(x) end = time.time() print "counting sort took: ", end-start start = time.time() sorted(x) end = time.time() print "timsort took: ", end-start
import random import time def counting_sort(array): k = max(array) counts = [0]*(k+1) for x in array: counts[x] += 1 total = 0 for i in range(0,k+1): c = counts[i] counts[i] = total total = total + c output = [0]*len(array) for x in array: output[counts[x]] = x counts[x] = counts[x] + 1 return output if __name__ == "__main__": assert counting_sort([5,3,2,1]) == [1,2,3,5] x = [] for i in range(0, 1000): x.append(random.randint(0, 20)) assert counting_sort(x) == sorted(x) for i in range(0, 10000000): x.append(random.randint(0, 4000)) start = time.time() counting_sort(x) end = time.time() print "counting sort took: ", end-start start = time.time() sorted(x) end = time.time() print "timsort took: ", end-start
Fix mailchimp test which depends on how many people are on our mailchimp testing list
<?php require_once('tests/php/base.php'); class CashSeedTests extends UnitTestCase { function testS3Seed(){ $settings = new S3Seed(1,1); $this->assertIsa($settings, 'S3Seed'); } function testTwitterSeed(){ $user_id = 1; $settings_id = 1; $twitter = new TwitterSeed($user_id,$settings_id); $this->assertIsa($twitter, 'TwitterSeed'); } function testMailchimpSeed(){ $api_key = getenv("MAILCHIMP_API_KEY"); if($api_key) { $mc = new MailchimpSeed($api_key); $this->assertIsa($mc, 'MailchimpSeed'); $this->assertTrue($mc->url); $this->assertTrue($mc->lists()); // an already-created list for testing $test_id = "b607c6d911"; $webhooks = $mc->listWebhooks($test_id); $this->assertTrue(isset($webhooks)); $members = $mc->listMembers($test_id); $this->assertTrue($members); $this->assertTrue($members['total']); $this->assertTrue($members['data'][0]['email'] == 'duke@leto.net'); } else { fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n"); return; } } } ?>
<?php require_once('tests/php/base.php'); class CashSeedTests extends UnitTestCase { function testS3Seed(){ $settings = new S3Seed(1,1); $this->assertIsa($settings, 'S3Seed'); } function testTwitterSeed(){ $user_id = 1; $settings_id = 1; $twitter = new TwitterSeed($user_id,$settings_id); $this->assertIsa($twitter, 'TwitterSeed'); } function testMailchimpSeed(){ $api_key = getenv("MAILCHIMP_API_KEY"); if($api_key) { $mc = new MailchimpSeed($api_key); $this->assertIsa($mc, 'MailchimpSeed'); $this->assertTrue($mc->url); $this->assertTrue($mc->lists()); // an already-created list for testing $test_id = "b607c6d911"; $webhooks = $mc->listWebhooks($test_id); $this->assertTrue(isset($webhooks)); $members = $mc->listMembers($test_id); $this->assertTrue($members); $this->assertTrue($members['total'] == 1 ); $this->assertTrue($members['data'][0]['email'] == 'duke@leto.net'); } else { fwrite(STDERR,"Mailchimp api key not found, skipping mailchimp tests\n"); return; } } } ?>
Add 'force' option to core autoload & activate artisan command calls
<?php declare(strict_types=1); namespace Cortex\Foundation\Console\Commands; use Illuminate\Console\Command; class CoreInstallCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'cortex:install {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}'; /** * The console command description. * * @var string */ protected $description = 'Install Cortex Project.'; /** * Execute the console command. * * @return void */ public function handle(): void { $this->alert($this->description); $this->call('cortex:publish', ['--force' => $this->option('force'), '--resource' => $this->option('resource') ?: ['config']]); $this->call('cortex:migrate', ['--force' => $this->option('force')]); $this->call('cortex:seed'); $this->call('cortex:autoload', ['--force' => $this->option('force')]); $this->call('cortex:activate', ['--force' => $this->option('force')]); } }
<?php declare(strict_types=1); namespace Cortex\Foundation\Console\Commands; use Illuminate\Console\Command; class CoreInstallCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'cortex:install {--f|force : Force the operation to run when in production.} {--r|resource=* : Specify which resources to publish.}'; /** * The console command description. * * @var string */ protected $description = 'Install Cortex Project.'; /** * Execute the console command. * * @return void */ public function handle(): void { $this->alert($this->description); $this->call('cortex:publish', ['--force' => $this->option('force'), '--resource' => $this->option('resource') ?: ['config']]); $this->call('cortex:migrate', ['--force' => $this->option('force')]); $this->call('cortex:seed'); $this->call('cortex:autoload'); $this->call('cortex:activate'); } }
[chore] Move `sanity/typescript` before prettier extensions
module.exports = { root: true, parser: '@typescript-eslint/parser', globals: { __DEV__: true, }, env: { node: true, browser: true, }, settings: { react: {version: '16.9.0'}, }, extends: [ 'sanity', 'sanity/react', 'sanity/import', 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended', 'sanity/typescript', 'prettier/@typescript-eslint', 'prettier', 'prettier/react', ], rules: { 'import/no-extraneous-dependencies': 'off', // because of parts 'import/no-unresolved': ['error', {ignore: ['.*:.*']}], // because of parts 'prettier/prettier': 'error', 'sort-imports': 'off', // prefer import/order }, plugins: ['import', '@typescript-eslint', 'prettier', 'react'], }
module.exports = { root: true, parser: '@typescript-eslint/parser', globals: { __DEV__: true, }, env: { node: true, browser: true, }, settings: { react: {version: '16.9.0'}, }, extends: [ 'sanity', 'sanity/react', 'sanity/import', 'plugin:@typescript-eslint/recommended', 'plugin:react-hooks/recommended', 'prettier/@typescript-eslint', 'prettier', 'prettier/react', 'sanity/typescript', ], rules: { 'import/no-extraneous-dependencies': 'off', // because of parts 'import/no-unresolved': ['error', {ignore: ['.*:.*']}], // because of parts 'prettier/prettier': 'error', 'sort-imports': 'off', // prefer import/order }, plugins: ['import', '@typescript-eslint', 'prettier', 'react'], }
Fix test that wasn't running
import mock import unittest from cumulusci.core.config import ServiceConfig from cumulusci.core.config import TaskConfig from cumulusci.tasks.github import PullRequests from cumulusci.tests.util import create_project_config class TestPullRequests(unittest.TestCase): def test_run_task(self): project_config = create_project_config() project_config.keychain.set_service( "github", ServiceConfig( { "username": "TestUser", "password": "TestPass", "email": "testuser@testdomain.com", } ), ) task_config = TaskConfig() task = PullRequests(project_config, task_config) repo = mock.Mock() repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")] task.get_repo = mock.Mock(return_value=repo) task.logger = mock.Mock() task() task.logger.info.assert_called_with("#1: Test PR")
import mock import unittest from cumulusci.core.config import ServiceConfig from cumulusci.core.config import TaskConfig from cumulusci.tasks.github import PullRequests from cumulusci.tests.util import create_project_config @mock.patch("cumulusci.tasks.github.base.get_github_api_for_user", mock.Mock()) class TestPullRequests(unittest.TestCase): project_config = create_project_config() project_config.keychain.set_service( "github", ServiceConfig( { "username": "TestUser", "password": "TestPass", "email": "testuser@testdomain.com", } ), ) task_config = TaskConfig() task = PullRequests(project_config, task_config) repo = mock.Mock() repo.pull_requests.return_value = [mock.Mock(number=1, title="Test PR")] task.get_repo = mock.Mock(return_value=repo) task.logger = mock.Mock() task() task.logger.info.assert_called_with("#1: Test PR")
Add pre-commit as a test dependency
#!/usr/bin/env python import sys from setuptools import setup from shortuuid import __version__ assert sys.version >= "2.5", "Requires Python v2.5 or above." classifiers = [ "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Software Development :: Libraries :: Python Modules", ] setup( name="shortuuid", version=__version__, author="Stochastic Technologies", author_email="info@stochastictechnologies.com", url="https://github.com/stochastic-technologies/shortuuid/", description="A generator library for concise, " "unambiguous and URL-safe UUIDs.", long_description="A library that generates short, pretty, " "unambiguous unique IDs " "by using an extensive, case-sensitive alphabet and omitting " "similar-looking letters and numbers.", license="BSD", classifiers=classifiers, packages=["shortuuid"], test_suite="shortuuid.tests", tests_require=["pre-commit"], )
#!/usr/bin/env python import sys from setuptools import setup from shortuuid import __version__ assert sys.version >= "2.5", "Requires Python v2.5 or above." classifiers = [ "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Software Development :: Libraries :: Python Modules", ] setup( name="shortuuid", version=__version__, author="Stochastic Technologies", author_email="info@stochastictechnologies.com", url="https://github.com/stochastic-technologies/shortuuid/", description="A generator library for concise, " "unambiguous and URL-safe UUIDs.", long_description="A library that generates short, pretty, " "unambiguous unique IDs " "by using an extensive, case-sensitive alphabet and omitting " "similar-looking letters and numbers.", license="BSD", classifiers=classifiers, packages=["shortuuid"], test_suite="shortuuid.tests", tests_require=[], )
Enhance `expectPromise` helper to first check existence of `then`.
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise).to.have.a.property('then').that.is.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, }; module.exports = testUtils;
/*! resol-vbus | Copyright (c) 2013-2014, Daniel Wippermann | MIT license */ 'use strict'; var _ = require('lodash'); var Q = require('q'); var testUtils = { performAsyncTest: function(done, callback) { return Q.fcall(callback).then(function() { done(); }).fail(function(reason) { done(reason); }); }, expectPromise: function(promise) { expect(promise).to.be.an('object'); expect(promise.then).to.be.a('function'); return promise; }, expectRanges: function(ranges) { expect(ranges).a('array'); var comparableRanges = _.map(ranges, function(range) { return { minTimestamp: range.minTimestamp.toISOString(), maxTimestamp: range.maxTimestamp.toISOString(), }; }); return expect(comparableRanges); }, }; module.exports = testUtils;
IMCMS-233: Apply new UI to the admin panel and editors: - Versioned content no more stealing it's version's id.
package com.imcode.imcms.mapping.jpa.doc.content; import com.imcode.imcms.mapping.jpa.doc.Version; import javax.persistence.*; import javax.validation.constraints.NotNull; @MappedSuperclass public abstract class VersionedContent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "doc_id", unique = true, nullable = false, insertable = false, updatable = false) private Integer documentId; @NotNull @ManyToOne @JoinColumns({ @JoinColumn(name = "doc_id", referencedColumnName = "doc_id"), @JoinColumn(name = "doc_version_no", referencedColumnName = "no") }) private Version version; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Version getVersion() { return version; } public void setVersion(Version contentVersion) { this.version = contentVersion; this.documentId = contentVersion.getDocId(); } public Integer getDocumentId() { return documentId; } }
package com.imcode.imcms.mapping.jpa.doc.content; import com.imcode.imcms.mapping.jpa.doc.Version; import javax.persistence.*; import javax.validation.constraints.NotNull; @MappedSuperclass public abstract class VersionedContent { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "doc_id", unique = true, nullable = false, insertable = false, updatable = false) private Integer documentId; @NotNull @ManyToOne @JoinColumns({ @JoinColumn(name = "doc_id", referencedColumnName = "doc_id"), @JoinColumn(name = "doc_version_no", referencedColumnName = "no") }) private Version version; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Version getVersion() { return version; } public void setVersion(Version contentVersion) { this.version = contentVersion; this.documentId = contentVersion.getDocId(); this.id = contentVersion.getId(); } public Integer getDocumentId() { return documentId; } }
Add buster.assert hook when it's available
function testCase(name, tests) { var testCase = TestCase(name); for (var test in tests) { if (test != "setUp" && test != "tearDown") { testCase.prototype["test " + test] = tests[test]; } else { testCase.prototype[test] = tests[test]; } } return testCase; } var assert = this; (function () { var mappedAssertions = { ok: "True", doesNotThrow: "NoException", throws: "Exception", equal: "Equals" }; for (var assertion in mappedAssertions) { assert[assertion] = assert["assert" + mappedAssertions[assertion]]; } }()); if (buster.assert && buster.format) { buster.assert.format = buster.format.ascii; buster.assert.fail = fail; }
function testCase(name, tests) { var testCase = TestCase(name); for (var test in tests) { if (test != "setUp" && test != "tearDown") { testCase.prototype["test " + test] = tests[test]; } else { testCase.prototype[test] = tests[test]; } } return testCase; } var assert = this; (function () { var mappedAssertions = { ok: "True", doesNotThrow: "NoException", throws: "Exception", equal: "Equals" }; for (var assertion in mappedAssertions) { assert[assertion] = assert["assert" + mappedAssertions[assertion]]; } }());
Set memory_limit to be unlimited for tests
<?php require_once realpath(__DIR__ . '/../core/slir.class.php'); abstract class SLIRTestCase extends PHPUnit_Framework_TestCase { /** * @var SLIR */ protected $slir; /** * @return void */ protected function setUp() { $this->slir = new SLIR(); SLIRConfig::$defaultImagePath = null; SLIRConfig::$forceQueryString = false; SLIRConfig::$enableErrorImages = false; SLIRConfig::$defaultCropper = SLIR::CROP_CLASS_CENTERED; SLIRConfig::$copyEXIF = false; SLIRConfig::$maxMemoryToAllocate = -1; // Try to fix documentRoot for CLI SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../'); } /** * @return void */ protected function tearDown() { unset($this->slir); } }
<?php require_once realpath(__DIR__ . '/../core/slir.class.php'); abstract class SLIRTestCase extends PHPUnit_Framework_TestCase { /** * @var SLIR */ protected $slir; /** * @return void */ protected function setUp() { $this->slir = new SLIR(); SLIRConfig::$defaultImagePath = null; SLIRConfig::$forceQueryString = false; SLIRConfig::$enableErrorImages = false; SLIRConfig::$defaultCropper = SLIR::CROP_CLASS_CENTERED; SLIRConfig::$copyEXIF = false; // Try to fix documentRoot for CLI SLIRConfig::$documentRoot = realpath(__DIR__ . '/../../'); } /** * @return void */ protected function tearDown() { unset($this->slir); } }
Store partner credentials as config.
<?php abstract class ShippingEasy { public static $apiKey; public static $apiSecret; public static $partnerApiKey; public static $partnerApiSecret; public static $apiBase = 'https://app.shippingeasy.com'; public static $apiVersion = null; const VERSION = '0.4.0'; public static function getApiKey() { return self::$apiKey; } public static function setApiKey($apiKey) { self::$apiKey = $apiKey; } public static function getPartnerApiKey() { return self::$partnerApiKey; } public static function setPartnerApiKey($partnerApiKey) { self::$partnerApiKey = $partnerApiKey; } public static function setApiSecret($apiSecret) { self::$apiSecret = $apiSecret; } public static function setPartnerApiSecret($partnerApiSecret) { self::$partnerApiSecret = $partnerApiSecret; } public static function getApiVersion() { return self::$apiVersion; } public static function setApiVersion($apiVersion) { self::$apiVersion = $apiVersion; } public static function setApiBase($apiBase) { self::$apiBase = $apiBase; } }
<?php abstract class ShippingEasy { public static $apiKey; public static $apiSecret; public static $apiBase = 'https://app.shippingeasy.com'; public static $apiVersion = null; const VERSION = '0.4.0'; public static function getApiKey() { return self::$apiKey; } public static function setApiKey($apiKey) { self::$apiKey = $apiKey; } public static function setApiSecret($apiSecret) { self::$apiSecret = $apiSecret; } public static function getApiVersion() { return self::$apiVersion; } public static function setApiVersion($apiVersion) { self::$apiVersion = $apiVersion; } public static function setApiBase($apiBase) { self::$apiBase = $apiBase; } }
Improve error message when Component is not found in Cache
package com.axellience.vuegwt.client.definitions; import com.axellience.vuegwt.client.VueComponent; import java.util.HashMap; import java.util.Map; /** * A Cache for generated VueComponentDefinitions. * Using static initializer block, VueComponentDefinitions register an instance of themselves in * this Cache. * VueGWT then use this cache to get definitions for VueComponents. * @author Adrien Baron */ public class VueComponentDefinitionCache { private static Map<Class<? extends VueComponent>, VueComponentDefinition> componentDefinitionsCache = new HashMap<>(); public static void registerComponent(Class<? extends VueComponent> vueComponentClass, VueComponentDefinition componentDefinition) { componentDefinitionsCache.put(vueComponentClass, componentDefinition); } public static VueComponentDefinition getComponentDefinitionForClass( Class<? extends VueComponent> vueComponentClass) { VueComponentDefinition componentDefinition = componentDefinitionsCache.get(vueComponentClass); if (componentDefinition != null) return componentDefinition; throw new RuntimeException("Couldn't find the given Component " + vueComponentClass.getCanonicalName() + ". Make sure your annotations are being processed, and that you added the -generateJsInteropExports flag to GWT."); } }
package com.axellience.vuegwt.client.definitions; import com.axellience.vuegwt.client.VueComponent; import java.util.HashMap; import java.util.Map; /** * A Cache for generated VueComponentDefinitions. * Using static initializer block, VueComponentDefinitions register an instance of themselves in * this Cache. * VueGWT then use this cache to get definitions for VueComponents. * @author Adrien Baron */ public class VueComponentDefinitionCache { private static Map<Class<? extends VueComponent>, VueComponentDefinition> componentDefinitionsCache = new HashMap<>(); public static void registerComponent(Class<? extends VueComponent> vueComponentClass, VueComponentDefinition componentDefinition) { componentDefinitionsCache.put(vueComponentClass, componentDefinition); } public static VueComponentDefinition getComponentDefinitionForClass( Class<? extends VueComponent> vueComponentClass) { VueComponentDefinition componentDefinition = componentDefinitionsCache.get(vueComponentClass); if (componentDefinition != null) return componentDefinition; throw new RuntimeException( "Couldn't find the given Component " + vueComponentClass.getCanonicalName() + ". Are you sure annotations are being processed?"); } }
Set controller for register view
"use strict"; var app = angular.module("VinculacionApp", ['ui.router', 'ngAnimate']); app.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('landing', { url: '/', templateUrl: '../templates/landing.html' }) .state('registro', { url: '/registro', templateUrl: '../templates/registro.html', controller: 'RegistroCtrl as registro' }) .state('home', { url: '/home', templateUrl: '../templates/dashboard.html' }) .state('home.proyectos', { url: '/proyectos', templateUrl: '../templates/proyectos.html' }) .state('home.proyecto', { url: '/proyecto', templateUrl: '../templates/proyecto.html' }) .state('home.horas', { url: '/horas', templateUrl: '../templates/horas.html' }) .state('home.solicitudes', { url: '/solicitudes', templateUrl: '../templates/solicitudes.html' }) .state('home.solicitud', { url: '/solicitud', templateUrl: '../templates/solicitud.html' }); }]);
"use strict"; var app = angular.module("VinculacionApp", ['ui.router', 'ngAnimate']); app.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('landing', { url: '/', templateUrl: '../templates/landing.html' }) .state('registro', { url: '/registro', templateUrl: '../templates/registro.html' }) .state('home', { url: '/home', templateUrl: '../templates/dashboard.html' }) .state('home.proyectos', { url: '/proyectos', templateUrl: '../templates/proyectos.html' }) .state('home.proyecto', { url: '/proyecto', templateUrl: '../templates/proyecto.html' }) .state('home.horas', { url: '/horas', templateUrl: '../templates/horas.html' }) .state('home.solicitudes', { url: '/solicitudes', templateUrl: '../templates/solicitudes.html' }) .state('home.solicitud', { url: '/solicitud', templateUrl: '../templates/solicitud.html' }); }]);
SAML2: Support metadata overrides of SingleLogoutService for IdP initiated SLO.
<?php require_once('../../../www/_include.php'); $config = SimpleSAML_Configuration::getInstance(); $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler(); $session = SimpleSAML_Session::getInstance(); SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout'); if (!$config->getValue('enable.saml20-idp', false)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS'); } if (!isset($_GET['RelayState'])) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE'); } $returnTo = $_GET['RelayState']; $slo = $metadata->getGenerated('SingleLogoutService', 'saml20-idp-hosted'); /* We turn processing over to the SingleLogoutService script. */ SimpleSAML_Utilities::redirect($slo, array('ReturnTo' => $returnTo)); ?>
<?php require_once('../../../www/_include.php'); $config = SimpleSAML_Configuration::getInstance(); $session = SimpleSAML_Session::getInstance(); SimpleSAML_Logger::info('SAML2.0 - IdP.initSLO: Accessing SAML 2.0 IdP endpoint init Single Logout'); if (!$config->getValue('enable.saml20-idp', false)) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NOACCESS'); } if (!isset($_GET['RelayState'])) { SimpleSAML_Utilities::fatalError($session->getTrackID(), 'NORELAYSTATE'); } $returnTo = $_GET['RelayState']; /* We turn processing over to the SingleLogoutService script. */ SimpleSAML_Utilities::redirect('/' . $config->getBaseURL() . 'saml2/idp/SingleLogoutService.php', array('ReturnTo' => $returnTo)); ?>
Update declared Python version to 3.6
from __future__ import absolute_import #from distutils.core import setup from setuptools import setup descr = """ microscopium: unsupervised sample clustering and dataset exploration for high content screens. """ DISTNAME = 'microscopium' DESCRIPTION = 'Clustering of High Content Screen Images' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/microscopium/microscopium' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/microscopium/microscopium' VERSION = '0.1-dev' PYTHON_VERSION = (3, 6) INST_DEPENDENCIES = [] if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['microscopium', 'microscopium.screens'], install_requires=INST_DEPENDENCIES, scripts=["bin/mic"] )
from __future__ import absolute_import #from distutils.core import setup from setuptools import setup descr = """ microscopium: unsupervised sample clustering and dataset exploration for high content screens. """ DISTNAME = 'microscopium' DESCRIPTION = 'Clustering of High Content Screen Images' LONG_DESCRIPTION = descr MAINTAINER = 'Juan Nunez-Iglesias' MAINTAINER_EMAIL = 'juan.n@unimelb.edu.au' URL = 'https://github.com/microscopium/microscopium' LICENSE = 'BSD 3-clause' DOWNLOAD_URL = 'https://github.com/microscopium/microscopium' VERSION = '0.1-dev' PYTHON_VERSION = (2, 7) INST_DEPENDENCIES = [] if __name__ == '__main__': setup(name=DISTNAME, version=VERSION, url=URL, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author=MAINTAINER, author_email=MAINTAINER_EMAIL, license=LICENSE, packages=['microscopium', 'microscopium.screens'], install_requires=INST_DEPENDENCIES, scripts=["bin/mic"] )
Fix ENONET error found by galusben
//load zip csv into memory into a format we can easily iterate over //executed when gps2zip is required var fs = require('fs'); var zips = []; try { var data = fs.readFileSync(__dirname + '/zips.json', 'ascii'); //zips is a global defined up top zips = JSON.parse(data); } catch (err) { console.error("There was an error opening the zip code file:"); console.log(err); } exports.gps2zip = function(lat, lon){ var min_distance = -1; var min_distance_index = -1; for(var i = 0; i < zips.length; i++){ //compute euclidean distance //assumes earth is flat. var distance = Math.sqrt(Math.pow(lat - zips[i].latitude, 2) + Math.pow(lon - zips[i].longitude, 2)); //console.log(distance); if(distance < min_distance || min_distance === -1){ min_distance = distance; min_distance_index = i; } } if(min_distance_index != -1){ zips[min_distance_index].distance = min_distance; return zips[min_distance_index]; } else{ return {error: "Could not find a valid zip code."} } return zips[5]; }
//load zip csv into memory into a format we can easily iterate over //executed when gps2zip is required var fs = require('fs'); var zips = []; try { var data = fs.readFileSync('zips.json', 'ascii'); //zips is a global defined up top zips = JSON.parse(data); } catch (err) { console.error("There was an error opening the zip code file:"); console.log(err); } exports.gps2zip = function(lat, lon){ var min_distance = -1; var min_distance_index = -1; for(var i = 0; i < zips.length; i++){ //compute euclidean distance //assumes earth is flat. var distance = Math.sqrt(Math.pow(lat - zips[i].latitude, 2) + Math.pow(lon - zips[i].longitude, 2)); //console.log(distance); if(distance < min_distance || min_distance === -1){ min_distance = distance; min_distance_index = i; } } if(min_distance_index != -1){ zips[min_distance_index].distance = min_distance; return zips[min_distance_index]; } else{ return {error: "Could not find a valid zip code."} } return zips[5]; }
DERBY-6945: Remove a spurious character from a method signature; commit derby-6945-35-aa-removeSpuriousCharacter.diff. git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@1831487 13f79535-47bb-0310-9956-ffa450edef68
/* Derby - Class org.apache.derby.loc.client.clientmessagesProviderImpl Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 org.apache.derby.loc.client; import java.util.Locale; import java.util.ResourceBundle; import org.apache.derby.loc.client.spi.clientmessagesProvider; public class clientmessagesProviderImpl implements clientmessagesProvider { public ResourceBundle getBundle(String baseName, Locale locale) { ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale); return bundle; } }
/* Derby - Class org.apache.derby.loc.client.clientmessagesProviderImpl Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 org.apache.derby.loc.client; import java.util.Locale; import java.util.ResourceBundle; import org.apache.derby.loc.client.spi.clientmessagesProvider; public class clientmessagesProviderImpl implements clientmessagesProvider { public ResourceBundle getBundle​(String baseName, Locale locale) { ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale); return bundle; } }
Use type.name to determine component type. displayName is only for debug
import React, { Component, Children } from 'react'; import PropTypes from 'prop-types'; export default class Switch extends Component { componentDidMount() {} render() { const children = Children.toArray(this.props.children); const caseToRender = children.filter( child => child.type.name === 'Case' && child.props.cond )[0]; const defaultChild = children.filter(child => child.type.name === 'Default'); if ( defaultChild.length !== 1 || !defaultChild[0] ) { throw new Error('There has to be exact one Default component'); } const childToRender = caseToRender || defaultChild[0]; return ( <div className=""> {childToRender} </div> ); } } Switch.propTypes = { children: PropTypes.arrayOf(function (props, propName, componentName) { let error; const prop = props[propName]; React.Children.forEach(prop, function (child) { if ( !child || !child.type || !(child.type.name === 'Case' || child.type.name === 'Default') ) { error = new Error(`${componentName} only accepts children of type Case or Default.`); } }); return error; }).isRequired, };
import React, { Component, Children } from 'react'; import PropTypes from 'prop-types'; export default class Switch extends Component { componentDidMount() {} render() { const children = Children.toArray(this.props.children); const caseToRender = children.filter( child => child.type.displayName === 'Case' && child.props.cond )[0]; const defaultChild = children.filter(child => child.type.displayName === 'Default'); if ( defaultChild.length !== 1 || !defaultChild[0] ) { throw new Error('There has to be exact one Default component'); } const childToRender = caseToRender || defaultChild; return ( <div className=""> {childToRender} </div> ); } } Switch.propTypes = { children: PropTypes.arrayOf(function (props, propName, componentName) { let error; const prop = props[propName]; React.Children.forEach(prop, function (child) { if ( !child || !child.type || !(child.type.displayName === 'Case' || child.type.displayName === 'Default') ) { error = new Error(`${componentName} only accepts children of type Case or Default.`); } }); return error; }).isRequired, };
Allow the ingester to work without a report key
import boto.sns import simplejson as json import logging from memoized_property import memoized_property import os class SNSReporter(object): '''report ingestion events to SNS''' def __init__(self, report_key): self.report_key = report_key self.logger = logging.getLogger(self._log_name) @classmethod def from_config(cls): report_key = os.environ.get('DATALAKE_REPORT_KEY') if report_key is None: return None return cls(report_key) @property def _log_name(self): return self.report_key.split(':')[-1] @memoized_property def _connection(self): region = os.environ.get('AWS_REGION') if region: return boto.sns.connect_to_region(region) else: return boto.connect_sns() def report(self, ingestion_report): message = json.dumps(ingestion_report) self.logger.info('REPORTING: %s', message) self._connection.publish(topic=self.report_key, message=message)
import boto.sns import simplejson as json import logging from memoized_property import memoized_property import os from datalake_common.errors import InsufficientConfiguration class SNSReporter(object): '''report ingestion events to SNS''' def __init__(self, report_key): self.report_key = report_key self.logger = logging.getLogger(self._log_name) @classmethod def from_config(cls): report_key = os.environ.get('DATALAKE_REPORT_KEY') if report_key is None: raise InsufficientConfiguration('Please configure a report_key') return cls(report_key) @property def _log_name(self): return self.report_key.split(':')[-1] @memoized_property def _connection(self): region = os.environ.get('AWS_REGION') if region: return boto.sns.connect_to_region(region) else: return boto.connect_sns() def report(self, ingestion_report): message = json.dumps(ingestion_report) self.logger.info('REPORTING: %s', message) self._connection.publish(topic=self.report_key, message=message)
Enable searching in task list by label.
# -*- coding: utf-8 -*- import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) query |= Q(label__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
# -*- coding: utf-8 -*- import django.forms as forms from django.db.models import Q class TaskSearchForm(forms.Form): search = forms.CharField(required=False) my = forms.BooleanField(required=False) def get_query(self, request): self.is_valid() search = self.cleaned_data["search"] my = self.cleaned_data["my"] query = Q() if search: query |= Q(method__icontains=search) query |= Q(owner__username__icontains=search) if my and request.user.is_authenticated(): query &= Q(owner=request.user) return query
Add PHP version to debug info.
@if (config('app.debug')) <p id="debuginfo"> <?php // Git HEAD if (function_exists('exec')) { $githead = exec('git rev-parse --short=7 HEAD'); echo "<span><strong>Git HEAD: </strong> <em>$githead</em> </span>"; } // Script execution time $executiontime = round(microtime(true) - SCRIPT_START, 4); echo "<span><strong>Generated in: </strong> <em>{$executiontime}s</em> </span>"; // PHP version $phpversion = PHP_VERSION; echo "<span><strong>PHP Version: </strong> <em>$phpversion</em></span>"; ?> </p> @endif
@if (config('app.debug')) <p id="debuginfo"> <?php // Git HEAD if (function_exists('exec')) { $githead = exec('git rev-parse --short=7 HEAD'); echo "<span><strong>Git HEAD: </strong> <em>$githead</em> </span>"; } // Script execution time $executiontime = round(microtime(true) - SCRIPT_START, 4); echo "<span><strong>Generated in: </strong> <em>{$executiontime}s</em> </span>"; ?> </p> @endif
Add color for error message.
MSG_INFO = 0x01 MSG_WARNING = 0x02 MSG_ERROR = 0x04 MSG_VERBOSE = 0x08 MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE def logi(msg): print("[INFO] " + msg) def logv(msg): print("[VERBOSE] " + msg) def logw(msg): print("[WARNING] " + msg) def loge(msg): print("\033[1;31m[ERROR] " + msg + "\033[m") class Logger(object): def __init__(self): self.logger_level = MSG_ALL def info(self, msg): if self.logger_level & MSG_INFO: logi(msg) def warning(self, msg): if self.logger_level & MSG_WARNING: logw(msg) def error(self, msg): if self.logger_level & MSG_ERROR: loge(msg) def verbose(self, msg): if self.logger_level & MSG_VERBOSE: logv(msg)
MSG_INFO = 0x01 MSG_WARNING = 0x02 MSG_ERROR = 0x04 MSG_VERBOSE = 0x08 MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE def logi(msg): print("[INFO] " + msg) def logv(msg): print("[VERBOSE] " + msg) def logw(msg): print("[WARNING] " + msg) def loge(msg): print("[ERROR] " + msg) class Logger(object): def __init__(self): self.logger_level = MSG_ALL def info(self, msg): if self.logger_level & MSG_INFO: logi(msg) def warning(self, msg): if self.logger_level & MSG_WARNING: logw(msg) def error(self, msg): if self.logger_level & MSG_ERROR: loge(msg) def verbose(self, msg): if self.logger_level & MSG_VERBOSE: logv(msg)
Revert "Increase JVM heap for logserver-container"
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } @Override public void getConfig(QrStartConfig.Builder builder) { super.getConfig(builder); builder.jvm.heapsize(384); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.admin; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.container.handler.ThreadpoolConfig; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.component.Handler; /** * @author hmusum */ public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> { public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) { super(parent, name, name, deployState); addDefaultHandlersWithVip(); addLogHandler(); } @Override protected void doPrepare(DeployState deployState) { } @Override public void getConfig(ThreadpoolConfig.Builder builder) { builder.maxthreads(10); } @Override public void getConfig(QrStartConfig.Builder builder) { super.getConfig(builder); builder.jvm.heapsize(512); } protected boolean messageBusEnabled() { return false; } private void addLogHandler() { Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS); logHandler.addServerBindings("http://*/logs"); addComponent(logHandler); } }
Use default connection for DB repository
<?php namespace Krucas\Counter\Integration\Laravel; use Illuminate\Support\ServiceProvider; use Krucas\Counter\Counter; class CounterServiceProvider extends ServiceProvider { /** * Bootstrap service provider. * * @return void */ public function boot() { $this->publishes(array( __DIR__ . '/../../../../config/counter.php' => config_path('counter.php'), ), 'config'); } /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/../../../../config/counter.php', 'counter'); $this->app->singleton('Krucas\Counter\Integration\Laravel\DatabaseRepository', function ($app) { return new DatabaseRepository($app['db']->connection(), $app['config']->get('counter.table')); }); $this->app->singleton('counter', function ($app) { $repositoryClass = $app['config']->get('counter.repository'); return new Counter($app->make($repositoryClass)); }); $this->app->alias('counter', 'Krucas\Counter\Counter'); } }
<?php namespace Krucas\Counter\Integration\Laravel; use Illuminate\Support\ServiceProvider; use Krucas\Counter\Counter; class CounterServiceProvider extends ServiceProvider { /** * Bootstrap service provider. * * @return void */ public function boot() { $this->publishes(array( __DIR__ . '/../../../../config/counter.php' => config_path('counter.php'), ), 'config'); } /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__ . '/../../../../config/counter.php', 'counter'); $this->app->singleton('Krucas\Counter\Integration\Laravel\DatabaseRepository', function ($app) { return new DatabaseRepository($app['db'], $app['config']->get('counter.table')); }); $this->app->singleton('counter', function ($app) { $repositoryClass = $app['config']->get('counter.repository'); return new Counter($app->make($repositoryClass)); }); $this->app->alias('counter', 'Krucas\Counter\Counter'); } }
Change variance of type parameter
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Annotation; import com.redhat.ceylon.compiler.java.metadata.Annotations; import com.redhat.ceylon.compiler.java.metadata.CaseTypes; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; import com.redhat.ceylon.compiler.java.metadata.Variance; @Ceylon(major = 2) @TypeParameters(@TypeParameter(value = "Other", variance = Variance.NONE, satisfies="ceylon.language.Ordinal<Other>")) @CaseTypes(of = "Other") public interface Ordinal<Other extends Ordinal<? extends Other>> { @Annotations(@Annotation("formal")) public Other getSuccessor(); @Annotations(@Annotation("formal")) public Other getPredecessor(); @Annotations(@Annotation("formal")) @TypeInfo("ceylon.language.Integer") public long distanceFrom(@Name("other") @TypeInfo("Other") Other other); }
package ceylon.language; import com.redhat.ceylon.compiler.java.metadata.Annotation; import com.redhat.ceylon.compiler.java.metadata.Annotations; import com.redhat.ceylon.compiler.java.metadata.CaseTypes; import com.redhat.ceylon.compiler.java.metadata.Ceylon; import com.redhat.ceylon.compiler.java.metadata.Name; import com.redhat.ceylon.compiler.java.metadata.TypeInfo; import com.redhat.ceylon.compiler.java.metadata.TypeParameter; import com.redhat.ceylon.compiler.java.metadata.TypeParameters; import com.redhat.ceylon.compiler.java.metadata.Variance; @Ceylon(major = 2) @TypeParameters(@TypeParameter(value = "Other", variance = Variance.OUT, satisfies="ceylon.language.Ordinal<Other>")) @CaseTypes(of = "Other") public interface Ordinal<Other extends Ordinal<? extends Other>> { @Annotations(@Annotation("formal")) public Other getSuccessor(); @Annotations(@Annotation("formal")) public Other getPredecessor(); @Annotations(@Annotation("formal")) @TypeInfo("ceylon.language.Integer") public long distanceFrom(@Name("other") @TypeInfo("Other") Other other); }
Add solution to problem 68
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pedrovgs.problem68; /** * Given a positive int passed as parameter, can you write a method to return true if the number is * even or false if the number is odd? The only constraint you have is: you can't use this * operator: %. * * @author Pedro Vicente Gómez Sánchez. */ public class IsEven { /** * Easy algorithm based on "and" binary operator and the simplest mask you are going to see, the * number 1. In this method we are going to apply one mask with just one one inside and if the * result is different of 1 we will return true. This algorithm is possible because every binary * number with one one in the position zero is going to be odd. Review how to calculate an * integer * from a binary number if you don't understand how it works. */ public boolean check(int n) { return (n & 1) != 1; } }
/* * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pedrovgs.problem68; /** * Given a positive int passed as parameter, can you write a method to return true if the number is * even or false if the number is odd? The only constraint you have is: you can't use this * operator: %. * * @author Pedro Vicente Gómez Sánchez. */ public class IsEven { }
Update to use dynamic ports
/** * Firefox proxy settings implementation * TODO(salomegeo): rewrite it in typescript */ var prefsvc = require("sdk/preferences/service"); var proxyConfig = function() { this.running_ = false; }; proxyConfig.startUsingProxy = function(endpoint) { if (!this.running_) { this.running_ = true; // Store initial proxy state. this.socks_server_ = prefsvc.get("network.proxy.socks"); this.socks_port_ = prefsvc.get("network.proxy.socks_port"); this.proxy_type_ = prefsvc.get("network.proxy.type"); prefsvc.set("network.proxy.socks", endpoint.address); prefsvc.set("network.proxy.http_port", endpoint.port); prefsvc.set("network.proxy.type", 1); } }; proxyConfig.stopUsingProxy = function(askUser) { if (this.running_) { this.running_ = false; // Restore initial proxy state. prefsvc.set("network.proxy.socks", this.socks_server_); prefsvc.set("network.proxy.http_port", this.socks_port_); prefsvc.set("network.proxy.type", this.proxy_type); } }; exports.proxyConfig = proxyConfig
/** * Firefox proxy settings implementation * TODO(salomegeo): rewrite it in typescript */ var prefsvc = require("sdk/preferences/service"); var proxyConfig = function() { this.running_ = false; }; proxyConfig.startUsingProxy = function(endpoint) { if (!this.running_) { this.running_ = true; this.socks_server_ = prefsvc.get("network.proxy.socks"); this.socks_port_ = prefsvc.get("network.proxy.socks_port"); this.proxy_type_ = prefsvc.get("network.proxy.type"); prefsvc.set("network.proxy.socks", '127.0.0.1'); prefsvc.set("network.proxy.http_port", 9999); prefsvc.set("network.proxy.type", 1); } }; proxyConfig.stopUsingProxy = function(askUser) { if (this.running_) { this.running_ = false; prefsvc.set("network.proxy.socks", this.socks_server_); prefsvc.set("network.proxy.http_port", this.socks_port_); prefsvc.set("network.proxy.type", this.proxy_type); } }; exports.proxyConfig = proxyConfig
Convert tabs to spaces per PEP 8.
from __future__ import print_function from timeit import default_timer as timer import json import datetime print('Loading function') def eratosthenes(n): sieve = [ True for i in range(n+1) ] def markOff(pv): for i in range(pv+pv, n+1, pv): sieve[i] = False markOff(2) for i in range(3, n+1): if sieve[i]: markOff(i) return [ i for i in range(1, n+1) if sieve[i] ] def lambda_handler(event, context): start = timer() #print("Received event: " + json.dumps(event, indent=2)) maxPrime = int(event['queryStringParameters']['max']) numLoops = int(event['queryStringParameters']['loops']) print("looping " + str(numLoops) + " time(s)") for loop in range (0, numLoops): primes = eratosthenes(maxPrime) print("Highest 3 primes: " + str(primes.pop()) + ", " + str(primes.pop()) + ", " + str(primes.pop())) durationSeconds = timer() - start return {"statusCode": 200, \ "headers": {"Content-Type": "application/json"}, \ "body": "{\"durationSeconds\": " + str(durationSeconds) + \ ", \"max\": " + str(maxPrime) + ", \"loops\": " + str(numLoops) + "}"}
from __future__ import print_function from timeit import default_timer as timer import json import datetime print('Loading function') def eratosthenes(n): sieve = [ True for i in range(n+1) ] def markOff(pv): for i in range(pv+pv, n+1, pv): sieve[i] = False markOff(2) for i in range(3, n+1): if sieve[i]: markOff(i) return [ i for i in range(1, n+1) if sieve[i] ] def lambda_handler(event, context): start = timer() #print("Received event: " + json.dumps(event, indent=2)) maxPrime = int(event['queryStringParameters']['max']) numLoops = int(event['queryStringParameters']['loops']) print("looping " + str(numLoops) + " time(s)") for loop in range (0, numLoops): primes = eratosthenes(maxPrime) print("Highest 3 primes: " + str(primes.pop()) + ", " + str(primes.pop()) + ", " + str(primes.pop())) durationSeconds = timer() - start return {"statusCode": 200, \ "headers": {"Content-Type": "application/json"}, \ "body": "{\"durationSeconds\": " + str(durationSeconds) + \ ", \"max\": " + str(maxPrime) + ", \"loops\": " + str(numLoops) + "}"}
Add pre and post run functions (needs cleanup).
var path = require('path') , fs = require('fs') , TOML = require('toml') , bundles = require('./bundles') , useIfAvailable = require('./utils/useifavailable'); function main(pre, post) { var IoC = require('electrolyte'); var dirname = path.dirname(require.main.filename); // TODO: Make this more generic/configurable, use CLI args -C. var data = fs.readFileSync(path.join(dirname, 'manifest.toml'), 'utf8'); var config = TOML.parse(data); IoC.resolver(require('./resolvers/auto')(IoC)); useIfAvailable(bundles.CORE, IoC); useIfAvailable(bundles.WWW, 'www', IoC); pre && pre(IoC); IoC.use(IoC.fs(path.join(dirname, 'app'))); IoC.use(require('./loaders/config')(config)); //IoC.use(require('bixby-common')); var app = IoC.create('app'); if (typeof app == 'function') { app(function() { post && post(IoC); }); } else { throw new Error('Unsupported type of application: ' + typeof app); } } exports.main = main;
var path = require('path') , fs = require('fs') , TOML = require('toml') , bundles = require('./bundles') , useIfAvailable = require('./utils/useifavailable'); function main() { var IoC = require('electrolyte'); var dirname = path.dirname(require.main.filename); // TODO: Make this more generic/configurable, use CLI args -C. var data = fs.readFileSync(path.join(dirname, 'manifest.toml'), 'utf8'); var config = TOML.parse(data); IoC.resolver(require('./resolvers/auto')(IoC)); useIfAvailable(bundles.CORE, IoC); useIfAvailable(bundles.WWW, 'www', IoC); IoC.use(IoC.fs(path.join(dirname, 'app'))); IoC.use(require('./loaders/config')(config)); //IoC.use(require('bixby-common')); var app = IoC.create('app'); if (typeof app == 'function') { app(); } else { throw new Error('Unsupported type of application: ' + typeof app); } } exports.main = main;
Fix assert_raises for catching parents of exceptions.
from __future__ import unicode_literals """ Patch courtesy of: https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/ """ # code for monkey-patching import nose.tools # let's fix nose.tools.assert_raises (which is really unittest.assertRaises) # so that it always supports context management # in order for these changes to be available to other modules, you'll need # to guarantee this module is imported by your fixture before either nose or # unittest are imported try: nose.tools.assert_raises(Exception) except TypeError: # this version of assert_raises doesn't support the 1-arg version class AssertRaisesContext(object): def __init__(self, expected): self.expected = expected def __enter__(self): return self def __exit__(self, exc_type, exc_val, tb): self.exception = exc_val if issubclass(exc_type, self.expected): return True nose.tools.assert_equal(exc_type, self.expected) # if you get to this line, the last assertion must have passed # suppress the propagation of this exception return True def assert_raises_context(exc_type): return AssertRaisesContext(exc_type) nose.tools.assert_raises = assert_raises_context
from __future__ import unicode_literals """ Patch courtesy of: https://marmida.com/blog/index.php/2012/08/08/monkey-patching-assert_raises/ """ # code for monkey-patching import nose.tools # let's fix nose.tools.assert_raises (which is really unittest.assertRaises) # so that it always supports context management # in order for these changes to be available to other modules, you'll need # to guarantee this module is imported by your fixture before either nose or # unittest are imported try: nose.tools.assert_raises(Exception) except TypeError: # this version of assert_raises doesn't support the 1-arg version class AssertRaisesContext(object): def __init__(self, expected): self.expected = expected def __enter__(self): return self def __exit__(self, exc_type, exc_val, tb): self.exception = exc_val nose.tools.assert_equal(exc_type, self.expected) # if you get to this line, the last assertion must have passed # suppress the propagation of this exception return True def assert_raises_context(exc_type): return AssertRaisesContext(exc_type) nose.tools.assert_raises = assert_raises_context
emoji: Add type annotations to selectors. This fully covers this (small) file with types.
/* @flow */ import { createSelector } from 'reselect'; import type { Selector, RealmEmojiState } from '../types'; import { getRawRealmEmoji } from '../directSelectors'; import { getAuth } from '../account/accountSelectors'; import { getFullUrl } from '../utils/url'; export const getAllRealmEmojiById: Selector<RealmEmojiState> = createSelector( getAuth, getRawRealmEmoji, (auth, emojis) => Object.keys(emojis).reduce((result, id) => { result[id] = { ...emojis[id], source_url: getFullUrl(emojis[id].source_url, auth.realm) }; return result; }, {}), ); export const getActiveRealmEmojiById: Selector<RealmEmojiState> = createSelector( getAllRealmEmojiById, emojis => Object.keys(emojis) .filter(id => !emojis[id].deactivated) .reduce((result, id) => { result[id] = emojis[id]; return result; }, {}), );
/* @flow */ import { createSelector } from 'reselect'; import { getRawRealmEmoji } from '../directSelectors'; import { getAuth } from '../account/accountSelectors'; import { getFullUrl } from '../utils/url'; export const getAllRealmEmojiById = createSelector(getAuth, getRawRealmEmoji, (auth, emojis) => Object.keys(emojis).reduce((result, id) => { result[id] = { ...emojis[id], source_url: getFullUrl(emojis[id].source_url, auth.realm) }; return result; }, {}), ); export const getActiveRealmEmojiById = createSelector(getAllRealmEmojiById, emojis => Object.keys(emojis) .filter(id => !emojis[id].deactivated) .reduce((result, id) => { result[id] = emojis[id]; return result; }, {}), );
Make sure class is not finalized
package org.realityforge.ssf; import java.io.Serializable; import javax.annotation.Nonnull; public class SimpleSessionInfo implements SessionInfo, Serializable { private final String _sessionID; private final String _username; private long _createdAt; private long _lastAccessedAt; public SimpleSessionInfo( @Nonnull final String sessionID, @Nonnull final String username ) { _sessionID = sessionID; _username = username; _createdAt = _lastAccessedAt = System.currentTimeMillis(); } @Nonnull public String getSessionID() { return _sessionID; } @Nonnull public String getUsername() { return _username; } public long getCreatedAt() { return _createdAt; } public long getLastAccessedAt() { return _lastAccessedAt; } public void updateAccessTime() { _lastAccessedAt = System.currentTimeMillis(); } }
package org.realityforge.ssf; import java.io.Serializable; import javax.annotation.Nonnull; public final class SimpleSessionInfo implements SessionInfo, Serializable { private final String _sessionID; private final String _username; private long _createdAt; private long _lastAccessedAt; public SimpleSessionInfo( @Nonnull final String sessionID, @Nonnull final String username ) { _sessionID = sessionID; _username = username; _createdAt = _lastAccessedAt = System.currentTimeMillis(); } @Nonnull public String getSessionID() { return _sessionID; } @Nonnull public String getUsername() { return _username; } public long getCreatedAt() { return _createdAt; } public long getLastAccessedAt() { return _lastAccessedAt; } public void updateAccessTime() { _lastAccessedAt = System.currentTimeMillis(); } }
Change qt5reactor-fork dependency to qt5reactor. The author of qt5reactor has now changed the name.
from setuptools import setup, find_packages try: from pyqt_distutils.build_ui import build_ui cmdclass={'build_ui': build_ui} except ImportError: cmdclass={} setup( name='gauges', version='0.1', description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo', url='http://github.com/estan/gauges', author='Elvis Stansvik', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Communications', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], packages=find_packages(), install_requires=[ 'autobahn', 'twisted', 'pyOpenSSL', 'service_identity', 'qt5reactor', ], entry_points={ 'gui_scripts': [ 'gauges-qt=gauges.gauges_qt:main' ], }, cmdclass=cmdclass )
from setuptools import setup, find_packages try: from pyqt_distutils.build_ui import build_ui cmdclass={'build_ui': build_ui} except ImportError: cmdclass={} setup( name='gauges', version='0.1', description='PyQt5 + Autobahn/Twisted version of Gauges Crossbar demo', url='http://github.com/estan/gauges', author='Elvis Stansvik', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Communications', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ], packages=find_packages(), install_requires=[ 'autobahn', 'twisted', 'pyOpenSSL', 'service_identity', 'qt5reactor-fork', ], entry_points={ 'gui_scripts': [ 'gauges-qt=gauges.gauges_qt:main' ], }, cmdclass=cmdclass )
Refactor findById to use angular filter.
(function() { angular.module('notely.notes.service', []) .service('notes', notesService); notesService['$inject'] = ['$http', '$filter']; function notesService($http, $filter) { var notes = []; var nevernoteBasePath = 'https://nevernote-1150.herokuapp.com/api/v1/'; var user = { apiKey: '$2a$10$3UAODMts8D3bK8uqwe2mF.F39vZD3/CypYXLUk1yvhpedfbMiBaFW' } this.all = function() { return notes; } this.findById = function(noteId) { return ($filter('filter')(notes, { id: parseInt(noteId) }, true)[0] || {}); } this.fetchNotes = function(callback) { $http.get(nevernoteBasePath + 'notes?api_key=' + user.apiKey) .success(function(notesData) { notes = notesData; if (callback) { callback(notes); } }); }; } })();
(function() { angular.module('notely.notes.service', []) .service('notes', notesService); notesService['$inject'] = ['$http']; function notesService($http) { var notes = []; var nevernoteBasePath = 'https://nevernote-1150.herokuapp.com/api/v1/'; var user = { apiKey: '$2a$10$3UAODMts8D3bK8uqwe2mF.F39vZD3/CypYXLUk1yvhpedfbMiBaFW' } this.all = function() { return notes; } this.findById = function(noteId) { for (var i = 0; i < notes.length; i++) { if (notes[i].id.toString() === noteId) { return notes[i]; } } return {}; } this.fetchNotes = function(callback) { $http.get(nevernoteBasePath + 'notes?api_key=' + user.apiKey) .success(function(notesData) { notes = notesData; if (callback) { callback(notes); } }); }; } })();
Add import for other python versions
from __future__ import absolute_import from operator import itemgetter mapping = { 'has_header': True, 'currency': 'EUR', 'delimiter': ';', 'bank': 'GLS Bank', 'account': itemgetter('Kontonummer'), # Chop up the dotted German date format and put it in ridiculous M/D/Y order 'date': lambda r: r['Buchungstag'][3:5] + '/' + r['Buchungstag'][:2] + '/' + r['Buchungstag'][-4:], # locale.atof does not actually know how to deal with German separators. # So we do it the crude way 'amount': lambda r: r['Betrag'].replace('.', '').replace(',', '.'), 'desc': itemgetter('Buchungstext'), 'payee': itemgetter('Auftraggeber/Empfänger'), }
from operator import itemgetter mapping = { 'has_header': True, 'currency': 'EUR', 'delimiter': ';', 'bank': 'GLS Bank', 'account': itemgetter('Kontonummer'), # Chop up the dotted German date format and put it in ridiculous M/D/Y order 'date': lambda r: r['Buchungstag'][3:5] + '/' + r['Buchungstag'][:2] + '/' + r['Buchungstag'][-4:], # locale.atof does not actually know how to deal with German separators. # So we do it the crude way 'amount': lambda r: r['Betrag'].replace('.', '').replace(',', '.'), 'desc': itemgetter('Buchungstext'), 'payee': itemgetter('Auftraggeber/Empfänger'), }
fix(replacement): Fix file extension added when redirect didn't have one
import resolveNode from "../helpers/resolveNode"; import match from "../helpers/matchRedirect"; import {relative, dirname, extname} from "path"; export default function (t, originalPath, {opts: {root, extensions}, file: {opts: {filename}}}, regexps) { const requiredFilename = resolveNode(dirname(filename), originalPath.node.value, extensions); console.log("requiredFilename:", requiredFilename); // console.log("Options:", {regexps, root}); const {redirect, redirected} = match(requiredFilename, regexps, root, extensions); console.log("CALCULATED REDIRECT:", redirected); // args[0] = t.stringLiteral("PPAth"); // path has a corresponing redirect if(redirected !== null) { // console.log("from:", dirname(filename)); // console.log("rel:", relative(dirname(filename), redirected)); // args[0] = t.stringLiteral(redirected); if(redirected.includes("/node_modules/")) { if(resolveNode(dirname(filename), redirect, extensions)) { console.log("FINAL -- MODULE", redirect); originalPath.replaceWith(t.stringLiteral(redirect)); return; } } let relativeRedirect = relative(dirname(filename), redirected); if(!relativeRedirect.startsWith(".")) relativeRedirect = "./" + relativeRedirect; if(!extname(redirect)) { const ext = extname(relativeRedirect); if(ext) relativeRedirect = relativeRedirect.slice(0, -ext.length); } originalPath.replaceWith(t.stringLiteral(relativeRedirect)); } }
import resolveNode from "../helpers/resolveNode"; import match from "../helpers/matchRedirect"; import {relative, dirname} from "path"; export default function (t, originalPath, {opts: {root, extensions}, file: {opts: {filename}}}, regexps) { const requiredFilename = resolveNode(dirname(filename), originalPath.node.value, extensions); console.log("requiredFilename:", requiredFilename); // console.log("Options:", {regexps, root}); const {redirect, redirected} = match(requiredFilename, regexps, root, extensions); console.log("CALCULATED REDIRECT:", redirected); // args[0] = t.stringLiteral("PPAth"); // path has a corresponing redirect if(redirected !== null) { // console.log("from:", dirname(filename)); // console.log("rel:", relative(dirname(filename), redirected)); // args[0] = t.stringLiteral(redirected); if(redirected.includes("/node_modules/")) { if(resolveNode(dirname(filename), redirect, extensions)) { console.log("FINAL -- MODULE", redirect); originalPath.replaceWith(t.stringLiteral(redirect)); return; } } let relativeRedirect = relative(dirname(filename), redirected); if(!relativeRedirect.startsWith(".")) relativeRedirect = "./" + relativeRedirect; originalPath.replaceWith(t.stringLiteral(relativeRedirect)); } }
Change it to output the result to console,not file
var fs = require('fs'); var log4js = require('log4js'); var logger = log4js.getLogger('Converter'); var inputFile = process.argv[2]; if(!inputFile){ printUsage(); } /** * * If user have not input the path of text file, * It will show the correct usage of script. * */ function printUsage(){ var out = "Usgae: " + process.argv[1] + " [input file]"; logger.info(out); process.exit(1); } /** * * Convert a text file which have query to json format. * */ convertQuery(); function convertQuery(){ var readQueryList = fs.readFileSync(inputFile,'utf8'); var splitedQuerys = readQueryList.split('\n'); var outputQuerys = []; for(i = 0; i< splitedQuerys.length; i++){ var query = splitedQuerys[i]; //If there are any space, skip it if(query == ''){ continue; } //Else, reaplce double quote with single quote var correctQuery = query.replace(/["]/g, "'"); outputQuerys.push(correctQuery); } var outputJson = JSON.stringify({query:outputQuerys}); logger.info(outputJson); }
var fs = require('fs'); var inputFile = process.argv[2]; var outputFile = process.argv[3]; if(!inputFile || !outputFile){ printUsage(); } /** * * If user have not input the path of text file(for input) or json file(for output), * It will show the correct usage of script. * */ function printUsage(){ var out = "Usgae: " + process.argv[1] + " [input file]" + " [output file]"; console.log(out); process.exit(1); } /** * * Convert a text file which have query to json format. * */ function convertQuery(){ var readQueryList = fs.readFileSync(inputFile,'utf8'); var splitedQuerys = readQueryList.split('\n'); var outputQuerys = []; for(i = 0; i< splitedQuerys.length; i++){ var query = splitedQuerys[i]; //If there are any space, skip it if(query == ''){ continue; } //Else, reaplce double quote with single quote var correctQuery = query.replace(/["]/g, "'"); outputQuerys.push(correctQuery); } var outputJson = JSON.stringify({query:outputQuerys}); fs.writeFileSync(outputFile,outputJson); }
Remove database details from acceptance test
import shelve from whatsmyrank.players import START_RANK from whatsmyrank.players import PlayerRepository def test_shows_player_rating(browser, test_server, database_url): player_repo = PlayerRepository(database_url, START_RANK) player_repo.create('p1') app = ScoringApp(browser, test_server) app.visit('/') app.shows('P1 1000') def test_user_adding(browser, test_server): app = ScoringApp(browser, test_server) app.visit('/players') app.add_player('test') app.is_in_page('/players/test') app.shows('TEST 1000') class ScoringApp(object): def __init__(self, browser, get_url): self._browser = browser self._get_url = get_url def visit(self, url): self._browser.visit(self._get_url(url)) def shows(self, text): assert self._browser.is_text_present(text) def add_player(self, name): self._browser.fill('player-name', name) self._browser.find_by_id('submit').click() def is_in_page(self, url): assert self._browser.url == self._get_url(url)
import shelve def test_shows_player_rating(browser, test_server, database_url): with shelve.open(database_url) as db: db.clear() db['p1'] = 1000 app = ScoringApp(browser, test_server) app.visit('/') app.shows('P1 1000') def test_user_adding(browser, test_server): app = ScoringApp(browser, test_server) app.visit('/players') app.add_player('test') app.is_in_page('/players/test') app.shows('TEST 1000') class ScoringApp(object): def __init__(self, browser, get_url): self._browser = browser self._get_url = get_url def visit(self, url): self._browser.visit(self._get_url(url)) def shows(self, text): assert self._browser.is_text_present(text) def add_player(self, name): self._browser.fill('player-name', name) self._browser.find_by_id('submit').click() def is_in_page(self, url): assert self._browser.url == self._get_url(url)
Read iceServers from the querystring
var qs = require('querystring'); var defaults = require('cog/defaults'); var quickconnect = require('rtc-quickconnect'); var getUserMedia = require('getusermedia'); var params = defaults(qs.parse(location.search.slice(1)), { signaller: 'http://switchboard.rtc.io/', iceServers: [] }); var qc; function connect(stream) { // create a quickconnect instance qc = require('rtc-quickconnect')(params.signaller, { room: params.room, iceServers: params.iceServers }); (params.channels || []).forEach(function(channel) { qc.createDataChannel(channel); }); if (stream) { qc.addStream(stream); } console.log('connecting to signaller'); qc.on('call:started', function(id, pc) { console.log('call started with peer: ' + id); console.log('remote stream count: ' + pc.getRemoteStreams().length); }); qc.on('call:ended', function(id) { console.log('call ended with peer: ' + id); }); } if (params.video) { getUserMedia({ audio: true, video: true }, function(err, stream) { if (err) { // TODO: report error return; } connect(stream); }); } else { connect(); }
var qs = require('querystring'); var defaults = require('cog/defaults'); var quickconnect = require('rtc-quickconnect'); var getUserMedia = require('getusermedia'); var params = defaults(qs.parse(location.search.slice(1)), { signaller: 'http://switchboard.rtc.io/' }); var qc; function connect(stream) { // create a quickconnect instance qc = require('rtc-quickconnect')(params.signaller, { room: params.room }); (params.channels || []).forEach(function(channel) { qc.createDataChannel(channel); }); if (stream) { qc.addStream(stream); } console.log('connecting to signaller'); qc.on('call:started', function(id, pc) { console.log('call started with peer: ' + id); console.log('remote stream count: ' + pc.getRemoteStreams().length); }); qc.on('call:ended', function(id) { console.log('call ended with peer: ' + id); }); } if (params.video) { getUserMedia({ audio: true, video: true }, function(err, stream) { if (err) { // TODO: report error return; } connect(stream); }); } else { connect(); }
Refresh the JWT token on page load
import { User } from './ActionTypes'; import { post } from '../http'; import { replaceWith } from 'redux-react-router'; function putInLocalStorage(key) { return (payload) => { window.localStorage.setItem(key, JSON.stringify(payload)); return payload; }; } function clearLocalStorage(key) { window.localStorage.removeItem(key); } function performLogin(username, password) { return post('/token-auth/', { username, password }) .then(putInLocalStorage('user')); } export function refreshToken(token) { return post('/token-auth/refresh/', { token }) .then(putInLocalStorage('user')) .catch(err => { clearLocalStorage('user'); throw err; }); } export function login(username, password) { return { type: User.LOGIN, promise: performLogin(username, password) }; } export function logout() { return (dispatch) => { window.localStorage.removeItem('user'); dispatch({ type: User.LOGOUT }); dispatch(replaceWith('/')); }; } export function loginWithExistingToken(token) { return { type: User.LOGIN, promise: refreshToken(token) }; } /** * Dispatch a login success if a token exists in local storage. */ export function loginAutomaticallyIfPossible() { return (dispatch) => { const { token } = JSON.parse(window.localStorage.getItem('user')) || {}; if (token) { dispatch(loginWithExistingToken(token)); } }; }
import { User } from './ActionTypes'; import { post } from '../http'; import { replaceWith } from 'redux-react-router'; function putInLocalStorage(key) { return (payload) => { window.localStorage.setItem(key, JSON.stringify(payload)); return payload; }; } function performLogin(username, password) { return post('/login', { username, password }) .then(data => ({ username, token: data.authToken })) .then(putInLocalStorage('user')); } export function login(username, password) { return { type: User.LOGIN, promise: performLogin(username, password) }; } export function logout() { return (dispatch) => { window.localStorage.removeItem('user'); dispatch({ type: User.LOGOUT }); dispatch(replaceWith('/')); }; } export function loginWithExistingToken(username, token) { return { type: User.LOGIN_SUCCESS, payload: { username, token } }; } /** * Dispatch a login success if a token exists in local storage. */ export function loginAutomaticallyIfPossible() { return (dispatch) => { const { username, token } = JSON.parse(window.localStorage.getItem('user')) || {}; if (username && token) { dispatch(loginWithExistingToken(username, token)); } }; }
Make importlib dependency only take place if you need it
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: install_requires.append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'importlib', 'autoresponse>=0.2', ], ) if __name__ == '__main__': from setuptools import setup setup(**setup_params)
Adjust logging level while removing Backups module
package monoxide.forgebackup.coremod.asm; import java.util.Map; import monoxide.forgebackup.BackupLog; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodNode; import com.google.common.collect.Maps; public class EssentialsBackupTransformer extends AsmTransformer { public EssentialsBackupTransformer() { Map<String, String> tmp; // MCP/obfuscated version. Nothing needs to change in a live MC instance. tmp = Maps.newHashMap(); mappings.put("com.ForgeEssentials.backup.ModuleBackup", tmp); } @Override protected void doTransform(ClassNode classNode, Map<String, String> mapping) { BackupLog.info("Mangling ForgeEssentials for its own good. Their Backups module was not actually loaded."); classNode.fields.clear(); for (int i = 0; i < classNode.methods.size();) { MethodNode node = (MethodNode)classNode.methods.get(i); BackupLog.fine("Inspecting method: %s", node.name); if (!node.name.equals("<init>")) { classNode.methods.remove(i); } else { i++; } } } }
package monoxide.forgebackup.coremod.asm; import java.util.Map; import monoxide.forgebackup.BackupLog; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodNode; import com.google.common.collect.Maps; public class EssentialsBackupTransformer extends AsmTransformer { public EssentialsBackupTransformer() { Map<String, String> tmp; // MCP/obfuscated version. Nothing needs to change in a live MC instance. tmp = Maps.newHashMap(); mappings.put("com.ForgeEssentials.backup.ModuleBackup", tmp); } @Override protected void doTransform(ClassNode classNode, Map<String, String> mapping) { BackupLog.info("Mangling ForgeEssentials for its own good. Their Backups module was not actually loaded."); classNode.fields.clear(); for (int i = 0; i < classNode.methods.size();) { MethodNode node = (MethodNode)classNode.methods.get(i); BackupLog.info("Inspecting method: %s", node.name); if (!node.name.equals("<init>")) { classNode.methods.remove(i); } else { i++; } } } }
Remove the exception lists from the API which judges whether a ReportItemHandle binds to a Linked Data Set
package org.eclipse.birt.report.data.adapter.api; import java.lang.reflect.Method; import org.eclipse.birt.report.model.api.ReportItemHandle; public class LinkedDataSetUtil { private static String GET_LINKED_DATA_MODEL_METHOD = "getLinkedDataModel"; public static boolean bindToLinkedDataSet( ReportItemHandle reportItemHandle ) { Method[] methods = reportItemHandle.getClass( ).getMethods( ); for ( int i = 0; i < methods.length; i++ ) { String name = methods[i].getName( ); if ( name.equals( GET_LINKED_DATA_MODEL_METHOD ) ) { Object result = null ; try { result = methods[i].invoke( reportItemHandle ); } catch ( Exception e ) { return false; } if ( result != null ) return true; } } return false; } }
package org.eclipse.birt.report.data.adapter.api; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.eclipse.birt.report.model.api.ReportItemHandle; public class LinkedDataSetUtil { private static String GET_LINKED_DATA_MODEL_METHOD = "getLinkedDataModel"; public static boolean bindToLinkedDataSet( ReportItemHandle reportItemHandle ) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method[] methods = reportItemHandle.getClass( ).getMethods( ); for ( int i = 0; i < methods.length; i++ ) { String name = methods[i].getName( ); if ( name.equals( GET_LINKED_DATA_MODEL_METHOD ) ) { Object result = methods[i].invoke( reportItemHandle ); if ( result != null ) return true; } } return false; } }
Fix logic error in schedule filter
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) elif self.value() == 'out': return queryset.filter(scheduleitem__isnull=True) return queryset class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from wafer.talks.models import TalkType, Talk, TalkUrl class ScheduleListFilter(admin.SimpleListFilter): title = _('in schedule') parameter_name = 'schedule' def lookups(self, request, model_admin): return ( ('in', _('Allocated to schedule')), ('out', _('Not allocated')), ) def queryset(self, request, queryset): if self.value() == 'in': return queryset.filter(scheduleitem__isnull=False) return queryset.filter(scheduleitem__isnull=True) class TalkUrlInline(admin.TabularInline): model = TalkUrl class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'get_author_name', 'get_author_contact', 'talk_type', 'get_in_schedule', 'status') list_editable = ('status',) list_filter = ('status', 'talk_type', ScheduleListFilter) inlines = [ TalkUrlInline, ] admin.site.register(Talk, TalkAdmin) admin.site.register(TalkType) admin.site.register(TalkUrl)
Use 100 images in list Again, a bit more real-world-ish stress testing here.
package com.wrapp.android.webimageexample; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public class WebImageListAdapter extends BaseAdapter { private static final boolean USE_AWESOME_IMAGES = true; private static final int NUM_IMAGES = 100; private static final int IMAGE_SIZE = 100; public int getCount() { return NUM_IMAGES; } private String getImageUrl(int i) { if(USE_AWESOME_IMAGES) { // Unicorns! return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE; } else { // Boring identicons return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon"; } } public Object getItem(int i) { return getImageUrl(i); } public long getItemId(int i) { return i; } public View getView(int i, View convertView, ViewGroup parentViewGroup) { WebImageContainerView containerView; if(convertView != null) { containerView = (WebImageContainerView)convertView; } else { containerView = new WebImageContainerView(parentViewGroup.getContext()); } containerView.setImageUrl(getImageUrl(i)); return containerView; } }
package com.wrapp.android.webimageexample; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public class WebImageListAdapter extends BaseAdapter { private static final boolean USE_AWESOME_IMAGES = true; private static final int NUM_IMAGES = 50; private static final int IMAGE_SIZE = 100; public int getCount() { return NUM_IMAGES; } private String getImageUrl(int i) { if(USE_AWESOME_IMAGES) { // Unicorns! return "http://unicornify.appspot.com/avatar/" + i + "?s=" + IMAGE_SIZE; } else { // Boring identicons return "http://www.gravatar.com/avatar/" + i + "?s=" + IMAGE_SIZE + "&d=identicon"; } } public Object getItem(int i) { return getImageUrl(i); } public long getItemId(int i) { return i; } public View getView(int i, View convertView, ViewGroup parentViewGroup) { WebImageContainerView containerView; if(convertView != null) { containerView = (WebImageContainerView)convertView; } else { containerView = new WebImageContainerView(parentViewGroup.getContext()); } containerView.setImageUrl(getImageUrl(i)); return containerView; } }
Fix rule number parameter check A parameter validation of rule number must be effective in preventing OS command execution.
(function() { var num = parseInt(request.param.num, 10).toString(10); var rule = data.rules[num] || null; if (rule === null) return response.error(404); switch (request.method) { case 'GET': response.head(200); response.end(JSON.stringify(rule, null, ' ')); return; case 'PUT': if (request.headers['content-type'].match(/^application\/json/)) { var newRule = request.query; if (newRule.isEnabled === false) { newRule.isDisabled = true; } delete newRule.isEnabled; data.rules.splice(data.rules.indexOf(rule), 1, newRule); fs.writeFileSync(define.RULES_FILE, JSON.stringify(data.rules, null, ' ')); response.head(200); response.end(JSON.stringify(newRule)); } else { response.error(400); } return; case 'DELETE': child_process.exec('node app-cli.js -mode rule --remove -n ' + num, function(err, stdout, stderr) { if (err) return response.error(500); response.head(200); response.end('{}'); }); return; } })();
(function() { var rule = data.rules[parseInt(request.param.num, 10)] || null; if (rule === null) return response.error(404); switch (request.method) { case 'GET': response.head(200); response.end(JSON.stringify(rule, null, ' ')); return; case 'PUT': if (request.headers['content-type'].match(/^application\/json/)) { var newRule = request.query; if (newRule.isEnabled === false) { newRule.isDisabled = true; } delete newRule.isEnabled; data.rules.splice(data.rules.indexOf(rule), 1, newRule); fs.writeFileSync(define.RULES_FILE, JSON.stringify(data.rules, null, ' ')); response.head(200); response.end(JSON.stringify(newRule)); } else { response.error(400); } return; case 'DELETE': child_process.exec('node app-cli.js -mode rule --remove -n ' + request.param.num, function(err, stdout, stderr) { if (err) return response.error(500); response.head(200); response.end('{}'); }); return; } })();
Rewrite EvangengelistStatus.php for better performance
<?php /** * This package fetches the data of requested individual using the Github API and ranks the Individual into * categories based on the number of public repositories the individual possesses. *@package Open Source Evangelist Agnostic Package *@author Surajudeen AKANDE <surajudeen.akande@andela.com> *@license MIT <https://opensource.org/licenses/MIT> *@link http://www.github.com/andela-sakande **/ namespace Sirolad\Evangelist; use Sirolad\Evangelist\EvangelistRanker; /* EvangelistStatus is the main class that finally outputs the rank of a requested repository. */ class EvangelistStatus { /** * @var string username of the requested Github account. */ public $username; /** * Constructor. * * @param string $username of the request. the ID of this action */ public function __construct($username) { $this->username = $username; } /** * Returns the status of the request. * * @return string the ranked output of the requested account. */ public function getStatus() { $evangelist = new EvangelistRanker(); return $output = $evangelist->rankEvangelist($this->username); } }
<?php /** * This package fetches the data of requested individual using the Github API and ranks the Individual into * categories based on the number of public repositories the individual possesses. *@package Open Source Evangelist Agnostic Package *@author Surajudeen AKANDE <surajudeen.akande@andela.com> *@license MIT <https://opensource.org/licenses/MIT> *@link http://www.github.com/andela-sakande **/ namespace Sirolad\Evangelist; use Sirolad\Evangelist\EvangelistRanker; /* EvangelistStatus is the main class that finally outputs the rank of a requested repository. */ class EvangelistStatus { /** * @var string username of the requested Github account. */ public $username; /** * Constructor. * * @param string $username of the request. the ID of this action */ public function __construct($username) { $this->username = $username; } /** * Returns the status of the request. * * @return string the ranked output of the requested account. */ public function getStatus() { $evangelist = new EvangelistRanker(); $output = $evangelist->rankEvangelist($this->username); return $output; } }
Use normal string to encapsulate the default tpl
package template import ( "errors" "io/ioutil" "text/template" ) const defaultTemplate = "{{ range . }}{{ . }}\n\n{{ end }}" // ------------------------------------------------------- // Parser. // ------------------------------------------------------- // Parse a template (and select the appropriate engine based on the file's extension). func Parse(templateFilename string) (*template.Template, error) { // If not available, use the default template. if templateFilename == "" { return useDefaultTemplate(), nil } content, err := ioutil.ReadFile(templateFilename) if err != nil { return nil, errors.New("cannot read the template") } return useTextTemplate(string(content)) } func useTextTemplate(content string) (*template.Template, error) { t, err := template.New("").Parse(content) if err != nil { return nil, errors.New("invalid Text/Markdown template file") } return t, nil } func useDefaultTemplate() *template.Template { return template.Must( template.New("").Parse(defaultTemplate), ) }
package template import ( "errors" "io/ioutil" "text/template" ) const defaultTemplate = `{{ range . }} {{ . }} {{ end }} ` // ------------------------------------------------------- // Parser. // ------------------------------------------------------- // Parse a template (and select the appropriate engine based on the file's extension). func Parse(templateFilename string) (*template.Template, error) { // If not available, use the default template. if templateFilename == "" { return useDefaultTemplate(), nil } content, err := ioutil.ReadFile(templateFilename) if err != nil { return nil, errors.New("cannot read the template") } return useTextTemplate(string(content)) } func useTextTemplate(content string) (*template.Template, error) { t, err := template.New("").Parse(content) if err != nil { return nil, errors.New("invalid Text/Markdown template file") } return t, nil } func useDefaultTemplate() *template.Template { return template.Must( template.New("").Parse(defaultTemplate), ) }
Add example to start using commander.js
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:false, indent:4, maxerr:50 */ /*global require, console, process*/ (function () { 'use strict'; var program = require('commander'), packageJSON = require('./../package.json'); // TODO: It needs paramns definition program .version(packageJSON.version) .option('-n, --new [name]', 'Run something randon'); // new event program.on('new', function (a) { console.log('Run --new> Param %s', a); }); // Reference https://github.com/visionmedia/commander.js/blob/master/examples/custom-help program.parse(process.argv); if (process.argv.length === 2) { program.help(); } }());
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:false, indent:4, maxerr:50 */ /*global require, console, process*/ // TODO: It needs paramns definition var cliHelp = require('commander'); cliHelp .version('0.0.1') .option('-p, --peppers', 'Add peppers') .option('-P, --pineapple', 'Add pineapple') .option('-b, --bbq', 'Add bbq sauce') .option('-c, --cheese <type>', 'Add the specified type of cheese [marble]') .option('-C, --no-cheese', 'You do not want any cheese') .parse(process.argv); console.log('you ordered a pizza with:'); if (cliHelp.peppers) { console.log(' - peppers'); } if (cliHelp.pineapple) { console.log(' - pineapple'); } if (cliHelp.bbq) { console.log(' - bbq'); } var cheese = true === cliHelp.cheese ? 'marble' : cliHelp.cheese || 'no'; console.log(' - %s cheese', cheese); console.log(cliHelp.args);
Change Bleed effect to use a material rather than a mysterious color id
package de.slikey.effectlib.effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.RandomUtils; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Entity; public class BleedEffect extends de.slikey.effectlib.Effect { /** * Play the Hurt Effect for the Player */ public boolean hurt = true; /** * Height of the blood spurt */ public double height = 1.75; /** * Color of blood. Default is red (152) */ public Material material = Material.REDSTONE_BLOCK; public BleedEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 4; iterations = 25; } @Override public void onRun() { // Location to spawn the blood-item. Location location = getLocation(); location.add(0, RandomUtils.random.nextFloat() * height, 0); location.getWorld().playEffect(location, Effect.STEP_SOUND, material); Entity entity = getEntity(); if (hurt && entity != null) { entity.playEffect(org.bukkit.EntityEffect.HURT); } } }
package de.slikey.effectlib.effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.RandomUtils; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Entity; public class BleedEffect extends de.slikey.effectlib.Effect { /** * Play the Hurt Effect for the Player */ public boolean hurt = true; /** * Height of the blood spurt */ public double height = 1.75; /** * Color of blood. Default is red (152) */ public int color = 152; public BleedEffect(EffectManager effectManager) { super(effectManager); type = EffectType.REPEATING; period = 4; iterations = 25; } @Override public void onRun() { // Location to spawn the blood-item. Location location = getLocation(); location.add(0, RandomUtils.random.nextFloat() * height, 0); location.getWorld().playEffect(location, Effect.STEP_SOUND, color); Entity entity = getEntity(); if (hurt && entity != null) { entity.playEffect(org.bukkit.EntityEffect.HURT); } } }
Add explicit setup for Django 1.7
#!/usr/bin/env python import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'constants', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', ) # For Django 1.7. try: import django django.setup() except AttributeError: pass from django.test.utils import get_runner def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(['constants', ]) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'constants', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', ) from django.test.utils import get_runner def runtests(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True, failfast=False) failures = test_runner.run_tests(['constants', ]) sys.exit(failures) if __name__ == '__main__': runtests()
Update the API to make it more semantic.
""" Database Emulator for the teammetrics project Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats """ import urllib2 import logging def extractMetrics(team, metric): """ Parses the data available at the url into a data structure. """ url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt" lines = urllib2.urlopen(url).readlines() ll = len(lines) names = lines[0].split('\t') results = list() for i in range(1,ll): data = lines[i].split('\t') ld = len(data) for j in range (1,ld): if(i==1): results.append(dict()) results[j-1]["user"]=names[j].strip(); results[j-1]["userdata"]=list() results[j-1]["userdata"].append(dict()) results[j-1]["userdata"][i-1]["year"]=data[0].strip() results[j-1]["userdata"][i-1]["data"]=data[j].strip() metricresult = dict() metricresult["metric"]=metric metricresult["data"]=results; return metricresult
""" Database Emulator for the teammetrics project Temporarily the data is generated by accessing data available at http://blend.debian.org/liststats """ import urllib2 import logging def extractMetrics(team, metric): """ Parses the data available at the url into a data structure. """ url = "http://blends.debian.net/liststats/"+metric+"_"+team+"_year.txt" lines = urllib2.urlopen(url).readlines() ll = len(lines) names = lines[0].split('\t') results = list() for i in range (1,ll): data = lines[i].split('\t') year = data[0] results.append(dict()); results[len(results)-1]["year"]=year; results[len(results)-1]["userdata"]=list(); lw = len(data) yeardata=dict() for j in range(1,lw): results[len(results)-1]["userdata"].append(dict()) results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["user"]=names[j] results[len(results)-1]["userdata"][len(results[len(results)-1]["userdata"])-1]["data"]=data[j] metricresult = dict() metricresult["metric"]=metric metricresult["data"]=results; return metricresult
Return pointer from NewTimingPipe function
package pipeline import ( "time" ) // TimingPipe invokes a custom callback function with the amount of time required to run a specific Pipe type TimingPipe struct { timedPipe Pipe callback func(begin time.Time, duration time.Duration) } // NewTimingPipe creates a new timing pipe func NewTimingPipe(timedPipe Pipe, callback func(begin time.Time, duration time.Duration)) *TimingPipe { return &TimingPipe{ timedPipe: timedPipe, callback: callback, } } func (t *TimingPipe) Process(in chan Data) chan Data { out := make(chan Data) go func() { defer close(out) for request := range in { begin := time.Now() innerPipeline := NewPipeline(t.timedPipe) go func() { innerPipeline.Enqueue(request) innerPipeline.Close() }() innerPipeline.Dequeue(func(response Data) { out <- response }) t.callback(begin, time.Since(begin)) } }() return out }
package pipeline import ( "time" ) // TimingPipe invokes a custom callback function with the amount of time required to run a specific Pipe type TimingPipe struct { timedPipe Pipe callback func(begin time.Time, duration time.Duration) } // NewTimingPipe creates a new timing pipe func NewTimingPipe(timedPipe Pipe, callback func(begin time.Time, duration time.Duration)) Pipe { return &TimingPipe{ timedPipe: timedPipe, callback: callback, } } func (t TimingPipe) Process(in chan Data) chan Data { out := make(chan Data) go func() { defer close(out) for request := range in { begin := time.Now() innerPipeline := NewPipeline(t.timedPipe) go func() { innerPipeline.Enqueue(request) innerPipeline.Close() }() innerPipeline.Dequeue(func(response Data) { out <- response }) t.callback(begin, time.Since(begin)) } }() return out }
Fix - TaxedProductMixin is abstract model
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the tax.")) rate_name = models.CharField(_("name of the rate"), max_length=30, help_text=_("Name of the rate which will be" " displayed to the user.")) def __unicode__(self): return self.name class TaxedProductMixin(models.Model): tax_group = models.ForeignKey(TaxGroup, related_name='products', null=True) class Meta: abstract = True
from django.db import models from django.utils.translation import ugettext_lazy as _ class TaxGroup(models.Model): name = models.CharField(_("group name"), max_length=100) rate = models.DecimalField(_("rate"), max_digits=4, decimal_places=2, help_text=_("Percentile rate of the tax.")) rate_name = models.CharField(_("name of the rate"), max_length=30, help_text=_("Name of the rate which will be" " displayed to the user.")) def __unicode__(self): return self.name class TaxedProductMixin(models.Model): tax_group = models.ForeignKey(TaxGroup, related_name='products', null=True)
Add short flags for version and verbose to match 'python' command
import logging import pkgutil import pi import pi.commands commands = {} for imp_importer, name, ispkg in pkgutil.iter_modules(pi.commands.__path__): fullname = pi.commands.__name__ + '.' + name # if fullname not in sys.modules: imp_loader = imp_importer.find_module(fullname) module = imp_loader.load_module(fullname) commands[name] = module def main(): import argparse parser = argparse.ArgumentParser(description='Python package manipulation', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('command', choices=commands, help='Command to run') parser.add_argument('-V', '--version', action='version', version=pi.__version__) parser.add_argument('-v', '--verbose', action='store_true', help='Print extra information') opts, _ = parser.parse_known_args() loglevel = logging.DEBUG if opts.verbose else logging.INFO # logging.basicConfig(format='%(levelname)s: %(message)s', level=loglevel) logging.basicConfig(level=loglevel) commands[opts.command].cli(parser) if __name__ == '__main__': main()
import logging import pkgutil import pi import pi.commands commands = {} for imp_importer, name, ispkg in pkgutil.iter_modules(pi.commands.__path__): fullname = pi.commands.__name__ + '.' + name # if fullname not in sys.modules: imp_loader = imp_importer.find_module(fullname) module = imp_loader.load_module(fullname) commands[name] = module def main(): import argparse parser = argparse.ArgumentParser(description='Python package manipulation', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('command', choices=commands, help='Command to run') parser.add_argument('--version', action='version', version=pi.__version__) parser.add_argument('--verbose', action='store_true', help='Print extra information') opts, _ = parser.parse_known_args() loglevel = logging.DEBUG if opts.verbose else logging.INFO # logging.basicConfig(format='%(levelname)s: %(message)s', level=loglevel) logging.basicConfig(level=loglevel) commands[opts.command].cli(parser) if __name__ == '__main__': main()
Add toString method to basic resource key. git-svn-id: ddbd9cf08712f046fd96251fb76032477531c99f@83 2c5795a3-9673-4752-9eb2-864809377e00
/* * Altimos JUtil * * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de> * * 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. * * See the NOTICE file distributed along with this work for further * information. */ package de.altimos.util.res.basic; import de.altimos.util.res.ResourceKey; /** * A basic ResourceKey implementation using a string as name. * * @author Jan Graichen */ public class BasicResourceKey implements ResourceKey { private String name; /** * Creates new BasicResourceKey with given name. * * @param name of resource this key identifies. */ public BasicResourceKey(String name) { this.name = name; } @Override public String getName() { return name; } @Override public String toString() { return getClass().getSimpleName() + "[" + name + "]"; } }
/* * Altimos JUtil * * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de> * * 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. * * See the NOTICE file distributed along with this work for further * information. */ package de.altimos.util.res.basic; import de.altimos.util.res.ResourceKey; /** * A basic ResourceKey implementation using a string as name. * * @author Jan Graichen */ public class BasicResourceKey implements ResourceKey { private String name; /** * Creates new BasicResourceKey with given name. * * @param name of resource this key identifies. */ public BasicResourceKey(String name) { this.name = name; } @Override public String getName() { return name; } }
Add pixel diff to list of recognized tasks BUG=skia:6778 Change-Id: I61a9562930516f88e1f6308d9a36eda4978f129a Reviewed-on: https://skia-review.googlesource.com/20600 Reviewed-by: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com> Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
/* List of all task types. */ package task_types import ( "go.skia.org/infra/ct/go/ctfe/admin_tasks" "go.skia.org/infra/ct/go/ctfe/capture_skps" "go.skia.org/infra/ct/go/ctfe/chromium_analysis" "go.skia.org/infra/ct/go/ctfe/chromium_builds" "go.skia.org/infra/ct/go/ctfe/chromium_perf" "go.skia.org/infra/ct/go/ctfe/lua_scripts" "go.skia.org/infra/ct/go/ctfe/pixel_diff" "go.skia.org/infra/ct/go/ctfe/task_common" ) // Slice of all tasks supported by CTFE. func Prototypes() []task_common.Task { return []task_common.Task{ &chromium_analysis.DBTask{}, &chromium_perf.DBTask{}, &pixel_diff.DBTask{}, &capture_skps.DBTask{}, &lua_scripts.DBTask{}, &chromium_builds.DBTask{}, &admin_tasks.RecreatePageSetsDBTask{}, &admin_tasks.RecreateWebpageArchivesDBTask{}, } }
/* List of all task types. */ package task_types import ( "go.skia.org/infra/ct/go/ctfe/admin_tasks" "go.skia.org/infra/ct/go/ctfe/capture_skps" "go.skia.org/infra/ct/go/ctfe/chromium_analysis" "go.skia.org/infra/ct/go/ctfe/chromium_builds" "go.skia.org/infra/ct/go/ctfe/chromium_perf" "go.skia.org/infra/ct/go/ctfe/lua_scripts" "go.skia.org/infra/ct/go/ctfe/task_common" ) // Slice of all tasks supported by CTFE. func Prototypes() []task_common.Task { return []task_common.Task{ &chromium_analysis.DBTask{}, &chromium_perf.DBTask{}, &capture_skps.DBTask{}, &lua_scripts.DBTask{}, &chromium_builds.DBTask{}, &admin_tasks.RecreatePageSetsDBTask{}, &admin_tasks.RecreateWebpageArchivesDBTask{}, } }
Watch task not re-symlinking template indexes The watch task does that now.
'use strict'; (() => { const debounce = (func, wait, immediate) => { let timeout; return () => { const context = this; const args = arguments; const later = () => { timeout = null; if (!immediate) func.apply(context, args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }; module.exports = (gulp, plugins, config) => { return () => { gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']); gulp.watch(['./templates/**/*.pug'], ['views', 'link-templates']); gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']); gulp.watch(config.buildPath + '/**/*.html') .on('change', plugins.browserSync.reload); gulp.watch(config.buildPath + '/**/*.js') .on('change', plugins.browserSync.reload); global.isWatching = true; return true; } }; })();
'use strict'; (() => { const debounce = (func, wait, immediate) => { let timeout; return () => { const context = this; const args = arguments; const later = () => { timeout = null; if (!immediate) func.apply(context, args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; }; module.exports = (gulp, plugins, config) => { return () => { gulp.watch(['./rocketbelt/**/*.scss', './templates/scss/**/*.scss'], ['styles']); gulp.watch(['./templates/**/*.pug'], ['views']); gulp.watch(['./rocketbelt/**/*.js'], ['copy-js', 'uglify']); gulp.watch(config.buildPath + '/**/*.html') .on('change', plugins.browserSync.reload); gulp.watch(config.buildPath + '/**/*.js') .on('change', plugins.browserSync.reload); global.isWatching = true; return true; } }; })();
Update basic auth realm from festapp-server to conference-server
var FESTAPP_REALM = 'Basic realm="conference-server"'; function validateBasicAuth(accounts, req, res, next) { if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) { if (accounts.indexOf(new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString()) !== -1) { next(); } else { res.header('WWW-Authenticate', FESTAPP_REALM); res.send('Wrong username or password', 401); } } else { res.header('WWW-Authenticate', FESTAPP_REALM); res.send(401); } } module.exports = { authAPI: function(accounts, apiVersion) { // Only allow GET, OPTIONS and HEAD-requests to /api-calls without // HTTP Basic authentication return function accessFilter(req, res, next) { var matchStar = new RegExp(apiVersion+'/events/\\w+/star.*').test(req.path); if (req.method === 'GET' || req.method === 'OPTIONS' || req.method === 'HEAD' || matchStar) { next(); } else { validateBasicAuth(accounts, req, res, next); } }; }, authAdminUI: function(accounts) { return function(req, res, next) { validateBasicAuth(accounts, req, res, next); }; } };
var FESTAPP_REALM = 'Basic realm="festapp-server"'; function validateBasicAuth(accounts, req, res, next) { if (req.headers.authorization && req.headers.authorization.search('Basic ') === 0) { if (accounts.indexOf(new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString()) !== -1) { next(); } else { res.header('WWW-Authenticate', FESTAPP_REALM); res.send('Wrong username or password', 401); } } else { res.header('WWW-Authenticate', FESTAPP_REALM); res.send(401); } } module.exports = { authAPI: function(accounts, apiVersion) { // Only allow GET, OPTIONS and HEAD-requests to /api-calls without // HTTP Basic authentication return function accessFilter(req, res, next) { var matchStar = new RegExp(apiVersion+'/events/\\w+/star.*').test(req.path); if (req.method === 'GET' || req.method === 'OPTIONS' || req.method === 'HEAD' || matchStar) { next(); } else { validateBasicAuth(accounts, req, res, next); } }; }, authAdminUI: function(accounts) { return function(req, res, next) { validateBasicAuth(accounts, req, res, next); }; } };
Fix encoding issue PHP 5.4
<?php namespace Koara\Io; class FileReader implements Reader { private $fileName; private $index; public function __construct($fileName) { $this->fileName = $fileName; } public function read(&$buffer, $offset, $length) { $filecontent = @file_get_contents($this->fileName, false, null, $this->index, $length * 4); if ($filecontent !== false && mb_strlen($filecontent) > 0) { $charactersRead=0; for($i=0; $i < $length; $i++) { $c = mb_substr($filecontent, $i, 1, 'utf-8'); if($c != NULL) { $buffer[$offset + $i] = $c; $this->index += strlen($c); $charactersRead++; } } return $charactersRead; } return -1; } }
<?php namespace Koara\Io; class FileReader implements Reader { private $fileName; private $index; public function __construct($fileName) { $this->fileName = $fileName; } public function read(&$buffer, $offset, $length) { $filecontent = @file_get_contents($this->fileName, false, null, $this->index, $length * 4); if ($filecontent !== false && mb_strlen($filecontent) > 0) { $charactersRead=0; for($i=0; $i < $length; $i++) { $c = mb_substr($filecontent, $i, 1); if($c != NULL) { $buffer[$offset + $i] = $c; $this->index += strlen($c); $charactersRead++; } } return $charactersRead; } return -1; } }
Allow zeros for recurring interval
from ckan.lib.navl.validators import ignore_empty, not_empty from ckan.logic.validators import ( name_validator, boolean_validator, natural_number_validator, isodate, group_id_exists) def default_inventory_entry_schema(): schema = { 'id': [unicode, ignore_empty], 'title': [unicode, not_empty], 'group_id': [group_id_exists], 'is_recurring': [boolean_validator], 'recurring_interval': [natural_number_validator], 'last_added_dataset_timestamp': [isodate], } return schema def default_inventory_entry_schema_create(): schema = { 'title': [unicode, not_empty], 'recurring_interval': [natural_number_validator], } return schema
from ckan.lib.navl.validators import ignore_empty, not_empty from ckan.logic.validators import ( name_validator, boolean_validator, is_positive_integer, isodate, group_id_exists) def default_inventory_entry_schema(): schema = { 'id': [unicode, ignore_empty], 'title': [unicode, not_empty], 'group_id': [group_id_exists], 'is_recurring': [boolean_validator], 'recurring_interval': [is_positive_integer], 'last_added_dataset_timestamp': [isodate], } return schema def default_inventory_entry_schema_create(): schema = { 'title': [unicode, not_empty], 'recurring_interval': [is_positive_integer], } return schema
Fix build with Sphinx 4. `add_stylesheet` was deprecated in 1.8 and removed in 4.0 [1]. The replacement, `add_css_file` was added in 1.0, which is older than any version required by `breathe`. [1] https://www.sphinx-doc.org/en/master/extdev/deprecated.html?highlight=add_stylesheet
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: subprocess.call('cd ..; doxygen', shell=True) import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] def setup(app): app.add_css_file("main_stylesheet.css") extensions = ['breathe'] breathe_projects = { 'xtl': '../xml' } templates_path = ['_templates'] html_static_path = ['_static'] source_suffix = '.rst' master_doc = 'index' project = 'xtl' copyright = '2017, Johan Mabille and Sylvain Corlay' author = 'Johan Mabille and Sylvain Corlay' html_logo = 'quantstack-white.svg' exclude_patterns = [] highlight_language = 'c++' pygments_style = 'sphinx' todo_include_todos = False htmlhelp_basename = 'xtldoc'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: subprocess.call('cd ..; doxygen', shell=True) import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] def setup(app): app.add_stylesheet("main_stylesheet.css") extensions = ['breathe'] breathe_projects = { 'xtl': '../xml' } templates_path = ['_templates'] html_static_path = ['_static'] source_suffix = '.rst' master_doc = 'index' project = 'xtl' copyright = '2017, Johan Mabille and Sylvain Corlay' author = 'Johan Mabille and Sylvain Corlay' html_logo = 'quantstack-white.svg' exclude_patterns = [] highlight_language = 'c++' pygments_style = 'sphinx' todo_include_todos = False htmlhelp_basename = 'xtldoc'
Remove all html from divider and use papi_html_tag
<?php // Exit if accessed directly defined( 'ABSPATH' ) || exit; /** * Papi Property Divider class. * * @package Papi */ class Papi_Property_Divider extends Papi_Property { /** * Display property html. */ public function html() { $options = $this->get_options(); papi_render_html_tag( 'div', [ 'class' => 'papi-property-divider', 'data-papi-rule' => $this->html_name(), sprintf( '<h3><span>%s</span></h3>', $options->title ) ] ); if ( ! papi_is_empty( $options->description ) ) { echo sprintf( '<p>%s</p>', $options->description ); } } /** * Render the final html that is displayed in the table. */ public function render_row_html() { if ( $this->get_option( 'raw' ) ) { parent::render_row_html(); } else { papi_render_html_tag( 'tr', [ 'class' => $this->display ? '' : 'papi-hide', papi_html_tag( 'td', [ 'colspan' => 2, $this->render_property_html() ] ) ] ); } } }
<?php // Exit if accessed directly defined( 'ABSPATH' ) || exit; /** * Papi Property Divider class. * * @package Papi */ class Papi_Property_Divider extends Papi_Property { /** * Display property html. */ public function html() { $options = $this->get_options(); ?> <div class="papi-property-divider" data-papi-rule="<?php echo $this->html_name(); ?>"> <h3> <span><?php echo $options->title; ?></span> </h3> <?php if ( ! papi_is_empty( $options->description ) ): ?> <p><?php echo $options->description; ?></p> <?php endif; ?> </div> <?php } /** * Render the final html that is displayed in the table. */ public function render_row_html() { if ( ! $this->get_option( 'raw' ) ): ?> <tr class="<?php echo $this->display ? '' : 'papi-hide'; ?>"> <td colspan="2"> <?php $this->html(); ?> </td> </tr> <?php else: parent::render_row_html(); endif; } }
Fix script to extract changelog for Python 3
#!/usr/bin/python import sys if len(sys.argv) < 2: print("Usage: %s <changelog> [<version>]" % (sys.argv[0],)) sys.exit(1) changelog = open(sys.argv[1]).readlines() version = "latest" if len(sys.argv) > 2: version = sys.argv[2] start = 0 end = -1 for i, line in enumerate(changelog): if line.startswith("## "): if start == 0 and (version == "latest" or line.startswith("## [%s]" % (version,))): start = i elif start != 0: end = i break if start != 0: print(''.join(changelog[start+1:end]).strip())
#!/usr/bin/python import sys if len(sys.argv) < 2: print("Usage: %s <changelog> [<version>]" % (sys.argv[0],)) sys.exit(1) changelog = open(sys.argv[1]).readlines() version = "latest" if len(sys.argv) > 2: version = sys.argv[2] start = 0 end = -1 for i, line in enumerate(changelog): if line.startswith("## "): if start == 0 and (version == "latest" or line.startswith("## [%s]" % (version,))): start = i elif start != 0: end = i break if start != 0: print ''.join(changelog[start+1:end]).strip()
Add JSONParser.js to ViewlessModels - working in node again
/** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * 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. */ var files = [ 'stdlib', 'io', 'writer', 'socket', 'hash', 'base64', 'encodings', 'utf8', 'parse', 'event', 'JSONUtil', 'XMLUtil', 'context', 'FOAM', 'JSONParser', 'TemplateUtil', 'AbstractPrototype', 'ModelProto', 'mm1Model', 'mm2Property', 'mm3Types', 'mm4Method', 'mm5Misc', 'mm6Protobuf', 'mlang', 'QueryParser', 'search', 'async', 'visitor', 'dao', 'ClientDAO', 'diff', 'SplitDAO', 'index', 'experimental/protobufparser', 'experimental/protobuf', 'models', 'oauth' ];
/** * @license * Copyright 2012 Google Inc. All Rights Reserved. * * 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. */ var files = [ 'stdlib', 'io', 'writer', 'socket', 'hash', 'base64', 'encodings', 'utf8', 'parse', 'event', 'JSONUtil', 'XMLUtil', 'context', 'FOAM', 'TemplateUtil', 'AbstractPrototype', 'ModelProto', 'mm1Model', 'mm2Property', 'mm3Types', 'mm4Method', 'mm5Misc', 'mm6Protobuf', 'mlang', 'QueryParser', 'search', 'async', 'visitor', 'dao', 'ClientDAO', 'diff', 'SplitDAO', 'index', 'experimental/protobufparser', 'experimental/protobuf', 'models', 'oauth' ];
Update administration tool copyright year
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2010 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2008 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
Add togglepause command documentation and change command order
module.exports = { help: (message, config) => { const p = config.prefix; message.channel.send( `\`\`\`diff ++ MUSIC COMMANDS ++ ${p}play URL - Plays a song at a YouTube URL. ${p}stop - Interrupts the current song. ${p}queue - Says the current queue. ${p}clearqueue - Clears the queue. ${p}pleasestop - Clears the queue and interrupts the current song. ${p}togglepause - Pauses (or resumes) the current stream. ${p}volume - Displays the volume. ${p}volumeshift n - Shifts the volume by n%. (Negative numbers can be used to decrease volume). ++ TESTING COMMANDS ++ ${p}ping - Says "pong." ${p}echo text - Repeats whatever text is given. ++ RANDOMNESS COMMANDS ++ ${p}coin - Says heads or tails. ${p}dice n - Says a random number between 1 and n. 6 is the default. ${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user. ++ MISC. COMMANDS ++ ${p}effify text - Effifies some text. \`\`\``); }, };
module.exports = { help: (message, config) => { const p = config.prefix; message.channel.send( `\`\`\`diff ++ MUSIC COMMANDS ++ ${p}play URL - Plays a song at a YouTube URL. ${p}stop - Interrupts the current song. ${p}queue - Says the current queue. ${p}pleasestop - Clears the queue and interrupts the current song. ${p}clearqueue - Clears the queue. ${p}volume - Displays the volume. ${p}volumeshift n - Shifts the volume by n%. (Negative numbers can be used to decrease volume). ++ TESTING COMMANDS ++ ${p}ping - Says "pong." ${p}echo text - Repeats whatever text is given. ++ RANDOMNESS COMMANDS ++ ${p}coin - Says heads or tails. ${p}dice n - Says a random number between 1 and n. 6 is the default. ${p}factcheck fact - Uses advanced neural networks and quantum bubble extrapolation to calculate a fact's veracity. If no fact is provided, it will give a more general statement about the command user. ++ MISC. COMMANDS ++ ${p}effify text - Effifies some text. \`\`\``); }, };
[docs/hugo] Move to hugo version 0.82.0 When adding more pinmux signals and pads, we run into a funny error where HUGO can't read the generated pinmux register documentation anymore since the file is too big. This file limitation has just recently (3 months ago) been removed. See https://github.com/gohugoio/hugo/pull/8172 for reference. This commit moves to HUGO 0.82.0 which contains this fix. Signed-off-by: Michael Schaffner <a005a2d3342a687ea2d05360c953107acbe83e08@opentitan.org>
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # Version requirements for various tools. Checked by tooling (e.g. fusesoc), # and inserted into the documentation. # # Entries are keyed by tool name. The value is either a string giving the # minimum version number or is a dictionary. If a dictionary, the following # keys are recognised: # # min_version: Required string. Minimum version number. # # as_needed: Optional bool. Defaults to False. If set, this tool is not # automatically required. If it is asked for, the rest of the # entry gives the required version. # __TOOL_REQUIREMENTS__ = { 'edalize': '0.2.0', 'ninja': '1.8.2', 'verilator': '4.104', 'hugo_extended': { 'min_version': '0.82.0', 'as_needed': True }, 'verible': { 'min_version': 'v0.0-808-g1e17daa', 'as_needed': True }, 'vcs': { 'min_version': '2020.03-SP2', 'as_needed': True } }
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 # Version requirements for various tools. Checked by tooling (e.g. fusesoc), # and inserted into the documentation. # # Entries are keyed by tool name. The value is either a string giving the # minimum version number or is a dictionary. If a dictionary, the following # keys are recognised: # # min_version: Required string. Minimum version number. # # as_needed: Optional bool. Defaults to False. If set, this tool is not # automatically required. If it is asked for, the rest of the # entry gives the required version. # __TOOL_REQUIREMENTS__ = { 'edalize': '0.2.0', 'ninja': '1.8.2', 'verilator': '4.104', 'hugo_extended': { 'min_version': '0.71.0', 'as_needed': True }, 'verible': { 'min_version': 'v0.0-808-g1e17daa', 'as_needed': True }, 'vcs': { 'min_version': '2020.03-SP2', 'as_needed': True } }
Add message when volume attached to instance outside project
/** @jsx React.DOM */ define( [ 'react', 'backbone' ], function (React, Backbone) { return React.createClass({ propTypes: { volume: React.PropTypes.instanceOf(Backbone.Model).isRequired, instances: React.PropTypes.instanceOf(Backbone.Collection).isRequired }, render: function () { var status = this.props.volume.get('status'), placeholderMessage = status; if(status === "available"){ placeholderMessage = "Unattached"; }else if(status === "in-use"){ var attachData = this.props.volume.get('attach_data'); var instance = this.props.instances.get(attachData.instance_id); if(instance) { placeholderMessage = "Attached to " + instance.get('name') + " as device " + attachData.device; }else{ placeholderMessage = "Attached to instance outside project (" + attachData.instance_id + ")"; } } return ( <span> {placeholderMessage} </span> ); } }); });
/** @jsx React.DOM */ define( [ 'react', 'backbone' ], function (React, Backbone) { return React.createClass({ propTypes: { volume: React.PropTypes.instanceOf(Backbone.Model).isRequired, instances: React.PropTypes.instanceOf(Backbone.Collection).isRequired }, render: function () { var status = this.props.volume.get('status'), placeholderMessage = status; if(status === "available"){ placeholderMessage = "Unattached"; }else if(status === "in-use"){ var attachData = this.props.volume.get('attach_data'); var instance = this.props.instances.get(attachData.instance_id); placeholderMessage = "Attached to " + instance.get('name') + " as device " + attachData.device; } return ( <span> {placeholderMessage} </span> ); } }); });
Correct base_url usage, and force commit
from flask import current_app from changes.config import queue, db from changes.backends.jenkins.builder import JenkinsBuilder from changes.constants import Status from changes.models.build import Build @queue.job def sync_build(build_id): try: build = Build.query.get(build_id) if build.status == Status.finished: return builder = JenkinsBuilder( app=current_app, base_url=current_app.config['JENKINS_URL'], ) builder.sync_build(build) db.session.commit() if build.status != Status.finished: sync_build.delay( build_id=build.id, ) except Exception: # Ensure we continue to synchronize this build as this could be a # temporary failure sync_build.delay( build_id=build.id, ) raise
from flask import current_app from changes.config import queue from changes.backends.jenkins.builder import JenkinsBuilder from changes.constants import Status from changes.models.build import Build @queue.job def sync_build(build_id): try: build = Build.query.get(build_id) if build.status == Status.finished: return builder = JenkinsBuilder( app=current_app, base_uri=current_app.config['JENKINS_URL'], ) builder.sync_build(build) if build.status != Status.finished: sync_build.delay( build_id=build.id, ) except Exception: # Ensure we continue to synchronize this build as this could be a # temporary failure sync_build.delay( build_id=build.id, ) raise
Convert 'ttp' string to link even if it appears at the first position of response
// ==UserScript== // @name Modify URL @2ch // @namespace curipha // @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link // @include http://*.2ch.net/* // @include http://*.bbspink.com/* // @version 0.1.2 // @grant none // @noframes // ==/UserScript== (function(){ 'use strict'; var anchor = document.getElementsByTagName('a'); for (var a of anchor) { if (a.href.indexOf('http://jump.2ch.net/?') === 0) { a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21 } else if (a.href.indexOf('http://pinktower.com/?') === 0) { a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22 } } var res = document.getElementsByTagName('dd'); if (res.length < 1) res = document.getElementsByClassName('message'); var ttp = /([^h]|^)(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig; for (var d of res) { d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>'); } })();
// ==UserScript== // @name Modify URL @2ch // @namespace curipha // @description Modify texts starting with "ttp://" to anchor and redirect URIs to direct link // @include http://*.2ch.net/* // @include http://*.bbspink.com/* // @version 0.1.2 // @grant none // @noframes // ==/UserScript== (function(){ 'use strict'; var anchor = document.getElementsByTagName('a'); for (var a of anchor) { if (a.href.indexOf('http://jump.2ch.net/?') === 0) { a.href = decodeURIComponent(a.href.slice(21)); // 'http://jump.2ch.net/?'.length -> 21 } else if (a.href.indexOf('http://pinktower.com/?') === 0) { a.href = decodeURIComponent('http://' + a.href.slice(22)); // 'http://pinktower.com/?'.length -> 22 } } var res = document.getElementsByTagName('dd'); if (res.length < 1) res = document.getElementsByClassName('message'); var ttp = /([^h])(ttps?:\/\/[\x21\x23-\x3b\x3d\x3f-\x7E]+)/ig; for (var d of res) { d.innerHTML = d.innerHTML.replace(ttp, '$1<a href="h$2">$2</a>'); } })();
Throw error instead of returning it.
// http://cs.selu.edu/~rbyrd/math/midpoint/ // ((x1+x2)/2), ((y1+y2)/2) var point = require('turf-point'); /** * Takes two point features and returns a point between the two. * * @module turf/midpoint * @param {Point} a * @param {Point} b * @return {Point} a point between the two * @example * var pt1 = turf.point(0,0) * var pt2 = turf.point(10, 0) * var midpointed = turf.midpoint(pt1, pt2) * var features = turf.featurecollection([ * pt1, pt2, midpointed]); * //=features */ module.exports = function(point1, point2) { if (point1 === null || point2 === null){ throw new Error('Less than two points passed.'); } var x1 = point1.geometry.coordinates[0]; var x2 = point2.geometry.coordinates[0]; var y1 = point1.geometry.coordinates[1]; var y2 = point2.geometry.coordinates[1]; var x3 = x1 + x2; var midX = x3/2; var y3 = y1 + y2; var midY = y3/2; var midpoint = point(midX, midY); return midpoint; };
// http://cs.selu.edu/~rbyrd/math/midpoint/ // ((x1+x2)/2), ((y1+y2)/2) var point = require('turf-point'); /** * Takes two point features and returns a point between the two. * * @module turf/midpoint * @param {Point} a * @param {Point} b * @return {Point} a point between the two * @example * var pt1 = turf.point(0,0) * var pt2 = turf.point(10, 0) * var midpointed = turf.midpoint(pt1, pt2) * var features = turf.featurecollection([ * pt1, pt2, midpointed]); * //=features */ module.exports = function(point1, point2) { if(point1 === null || point2 === null){ return new Error('Less than two points passed.'); } var x1 = point1.geometry.coordinates[0]; var x2 = point2.geometry.coordinates[0]; var y1 = point1.geometry.coordinates[1]; var y2 = point2.geometry.coordinates[1]; var x3 = x1 + x2; var midX = x3/2; var y3 = y1 + y2; var midY = y3/2; var midpoint = point(midX, midY); return midpoint; }
Store released dark_lang codes as all lower-case
""" Models for the dark-launching languages """ from django.db import models from config_models.models import ConfigurationModel class DarkLangConfig(ConfigurationModel): """ Configuration for the dark_lang django app """ released_languages = models.TextField( blank=True, help_text="A comma-separated list of language codes to release to the public." ) @property def released_languages_list(self): """ ``released_languages`` as a list of language codes. Example: ['it', 'de-at', 'es', 'pt-br'] """ if not self.released_languages.strip(): # pylint: disable=no-member return [] languages = [lang.lower().strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member # Put in alphabetical order languages.sort() return languages
""" Models for the dark-launching languages """ from django.db import models from config_models.models import ConfigurationModel class DarkLangConfig(ConfigurationModel): """ Configuration for the dark_lang django app """ released_languages = models.TextField( blank=True, help_text="A comma-separated list of language codes to release to the public." ) @property def released_languages_list(self): """ ``released_languages`` as a list of language codes. Example: ['it', 'de-at', 'es', 'pt-br'] """ if not self.released_languages.strip(): # pylint: disable=no-member return [] languages = [lang.strip() for lang in self.released_languages.split(',')] # pylint: disable=no-member # Put in alphabetical order languages.sort() return languages
Use 'my_counts' as name for MyCountsListView
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.main.views import new_count, view_count, edit_count, ListMyCountsView admin.autodiscover() urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'main/index.html'}, name="index"), url(r'^count/$', new_count, name="count_home"), url(r'^count/new/$', new_count, name="new_count"), url(r'^count/(?P<count_id>\d+)/$', view_count, name="view_count"), url(r'^count/(?P<count_id>\d+)/edit/$', edit_count, name="edit_count"), url(r'^user/$', ListMyCountsView.as_view(), name="my_counts"), url(r'^login/$', login, {'template_name': 'main/login.html'}, name='login'), url(r'^logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns()
from django.conf.urls import patterns, include, url from django.views.generic.simple import direct_to_template from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.contrib.auth.views import login, logout from cellcounter.main.views import new_count, view_count, edit_count, ListMyCountsView admin.autodiscover() urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'main/index.html'}, name="index"), url(r'^count/$', new_count, name="count_home"), url(r'^count/new/$', new_count, name="new_count"), url(r'^count/(?P<count_id>\d+)/$', view_count, name="view_count"), url(r'^count/(?P<count_id>\d+)/edit/$', edit_count, name="edit_count"), url(r'^user/$', ListMyCountsView.as_view()), url(r'^login/$', login, {'template_name': 'main/login.html'}, name='login'), url(r'^logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^admin/', include(admin.site.urls)), ) urlpatterns += staticfiles_urlpatterns()
Drop try/catch that causes uncaught errors in the Observer to be silently ignored
import threading import time from observer.event_loop import PlanetStackObserver from observer.event_manager import EventListener from util.logger import Logger, logging logger = Logger(level=logging.INFO) class Backend: def run(self): # start the openstack observer observer = PlanetStackObserver() observer_thread = threading.Thread(target=observer.run) observer_thread.start() # start event listene event_manager = EventListener(wake_up=observer.wake_up) event_manager_thread = threading.Thread(target=event_manager.run) event_manager_thread.start()
import threading import time from observer.event_loop import PlanetStackObserver from observer.event_manager import EventListener from util.logger import Logger, logging logger = Logger(level=logging.INFO) class Backend: def run(self): try: # start the openstack observer observer = PlanetStackObserver() observer_thread = threading.Thread(target=observer.run) observer_thread.start() # start event listene event_manager = EventListener(wake_up=observer.wake_up) event_manager_thread = threading.Thread(target=event_manager.run) event_manager_thread.start() except: logger.log_exc("Exception in child thread")
Make POST request when updating object
<?php /** * Abstraction of an instance resource from the Twilio API. * * @category Services * @package Services_Twilio * @author Neuman Vong <neuman@twilio.com> * @license http://creativecommons.org/licenses/MIT/ MIT * @link http://pear.php.net/package/Services_Twilio */ abstract class Services_Twilio_InstanceResource extends Services_Twilio_Resource { /** * @param mixed $params An array of updates, or a property name * @param mixed $value A value with which to update the resource * * @return null */ public function update($params, $value = null) { if (!is_array($params)) { $params = array($params => $value); } $this->client->createData($this->uri, $params); } /** * Get the value of a property on this resource. * * @param string $key The property name * * @return mixed Could be anything. */ public function __get($key) { if ($subresource = $this->getSubresources($key)) { return $subresource; } return $this->client->$key; } }
<?php /** * Abstraction of an instance resource from the Twilio API. * * @category Services * @package Services_Twilio * @author Neuman Vong <neuman@twilio.com> * @license http://creativecommons.org/licenses/MIT/ MIT * @link http://pear.php.net/package/Services_Twilio */ abstract class Services_Twilio_InstanceResource extends Services_Twilio_Resource { /** * @param mixed $params An array of updates, or a property name * @param mixed $value A value with which to update the resource * * @return null */ public function update($params, $value = null) { if (!is_array($params)) { $params = array($params => $value); } $this->client->updateData($params); } /** * Get the value of a property on this resource. * * @param string $key The property name * * @return mixed Could be anything. */ public function __get($key) { if ($subresource = $this->getSubresources($key)) { return $subresource; } return $this->client->$key; } }
[IMP] Use TransientModel for the dummy model used in translation testing
# -*- coding: utf-8 -*- import openerp from openerp.tools.translate import _ class m(openerp.osv.orm.TransientModel): """ A model to provide source strings. """ _name = 'test.translation.import' _columns = { 'name': openerp.osv.fields.char( '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB', size=32, help='Efgh'), } _('Ijkl') # With the name label above, this source string should be generated twice. _('1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- import openerp from openerp.tools.translate import _ class m(openerp.osv.osv.Model): """ A model to provide source strings. """ _name = 'test.translation.import' _columns = { 'name': openerp.osv.fields.char( '1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB', size=32, help='Efgh'), } _('Ijkl') # With the name label above, this source string should be generated twice. _('1XBUO5PUYH2RYZSA1FTLRYS8SPCNU1UYXMEYMM25ASV7JC2KTJZQESZYRV9L8CGB') # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: