text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Add -l/--last flag as alias for --recent
#!/usr/bin/env node 'use strict'; var program = require('commander'); var core = require('./lib/core'); var words = []; program .version(core.VERSION) .option( '-c, --config-file <config-file>', 'Path to config file. Defaults to ~/.tanager.json', String, core.DEFAULT_CONFIG_PATH ) .option( '-d, --date <date>', 'Date of the entry. Yesterday, dec5, "dec 5", etc' ) .option( '-e, --editor-cmd <editor-cmd>', 'Editor used to edit. Defaults to config.editor, $VISUAL, then $EDITOR', String ) .option( '-r, --recent', 'Edit the most recently modified file in a notebook (same as --last)' ) .option( '-l, --last', 'Edit the most last modified file in a notebook (same as --recent)' ) .arguments('<words...>') .action(function(cliWords) { words = cliWords; }) .parse(process.argv); core.handleRawInput( { editRecent: program.recent || program.last, configFile: program.configFile, date: program.date, editorCmd: program.editorCmd }, words );
#!/usr/bin/env node 'use strict'; var program = require('commander'); var core = require('./lib/core'); var words = []; program .version(core.VERSION) .option( '-c, --config-file <config-file>', 'Path to config file. Defaults to ~/.tanager.json', String, core.DEFAULT_CONFIG_PATH ) .option( '-d, --date <date>', 'Date of the entry. Yesterday, dec5, "dec 5", etc' ) .option( '-e, --editor-cmd <editor-cmd>', 'Editor used to edit. Defaults to config.editor, $VISUAL, then $EDITOR', String ) .option( '-r, --recent', 'Edit the most recently modified file in a notebook' ) .arguments('<words...>') .action(function(cliWords) { words = cliWords; }) .parse(process.argv); core.handleRawInput( { editRecent: program.recent, configFile: program.configFile, date: program.date, editorCmd: program.editorCmd }, words );
Address review comment: More useful help output.
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """The command-line ``flocker-volume`` tool.""" import sys from twisted.python.usage import Options from twisted.python.filepath import FilePath from twisted.internet.task import react from twisted.internet.defer import succeed from .service import VolumeService from .. import __version__ class FlockerVolumeOptions(Options): """Command line options for ``flocker-volume`` volume management tool.""" longdesc = """flocker-volume allows you to manage volumes, filesystems that can be attached to Docker containers. At the moment no functionality has been implemented. """ optParameters = [ ["config", None, b"/etc/flocker/volume.json", "The path to the config file."], ] def postOptions(self): self["config"] = FilePath(self["config"]) def opt_version(self): """Print the program's version and exit.""" print(__version__) raise SystemExit(0) def _main(reactor, *arguments): """Parse command-line options and use them to run volume management.""" # Much of this should be moved (and expanded) into shared class: # https://github.com/hybridlogic/flocker/issues/30 options = FlockerVolumeOptions() options.parseOptions(arguments) service = VolumeService(options["config"]) service.startService() return succeed(None) def main(): """Entry point to the ``flocker-volume`` command-line tool.""" react(_main, sys.argv[1:])
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """The command-line ``flocker-volume`` tool.""" import sys from twisted.python.usage import Options from twisted.python.filepath import FilePath from twisted.internet.task import react from twisted.internet.defer import succeed from .service import VolumeService from .. import __version__ class FlockerVolumeOptions(Options): """flocker-volume - volume management.""" optParameters = [ ["config", None, b"/etc/flocker/volume.json", "The path to the config file."], ] def postOptions(self): self["config"] = FilePath(self["config"]) def opt_version(self): print(__version__) raise SystemExit(0) def _main(reactor, *arguments): """Parse command-line options and use them to run volume management.""" # Much of this should be moved (and expanded) into shared class: # https://github.com/hybridlogic/flocker/issues/30 options = FlockerVolumeOptions() options.parseOptions(arguments) service = VolumeService(options["config"]) service.startService() return succeed(None) def main(): """Entry point to the ``flocker-volume`` command-line tool.""" react(_main, sys.argv[1:])
Make the username field unique
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('username')->unique(); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('username'); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Create database if it doesn't exist
from behave import given, when, then from mock import patch, call from tinkerforge.ip_connection import IPConnection from pytoon.models import Electricity, db from pytoon.connection import BrickConnection @given('we connect to the master brick') @patch('pytoon.connection.IPConnection') def step_impl(context, mock_class): host = None port = None context.brick_conn = BrickConnection(host, port, db) @then('we are connected') def step_impl(context): calls = [call(), call()] context.brick_conn.connection.register_callback.has_calls(calls) @when('we have an {sensor_type} sensor') def step_impl(context, sensor_type): if sensor_type == 'electricity': context.brick_conn.cb_enumerate('3', None, None, None, None, device_identifier=21, enumeration_type=IPConnection.ENUMERATION_TYPE_CONNECTED) assert (context.brick_conn.ambient is not None ) @then('we can measure {sensor_type}') def step_impl(context, sensor_type): if sensor_type == 'electricity': context.brick_conn.cb_ambient() @then('we store the {sensor_type} measurements in the database') def step_impl(context, sensor_type): db.create_all() result = Electricity.query.all() assert result is not None
from behave import given, when, then from mock import patch, call from tinkerforge.ip_connection import IPConnection from pytoon.models import Electricity, db from pytoon.connection import BrickConnection @given('we connect to the master brick') @patch('pytoon.connection.IPConnection') def step_impl(context, mock_class): host = None port = None context.brick_conn = BrickConnection(host, port, db) @then('we are connected') def step_impl(context): calls = [call(), call()] context.brick_conn.connection.register_callback.has_calls(calls) @when('we have an {sensor_type} sensor') def step_impl(context, sensor_type): if sensor_type == 'electricity': context.brick_conn.cb_enumerate('3', None, None, None, None, device_identifier=21, enumeration_type=IPConnection.ENUMERATION_TYPE_CONNECTED) assert (context.brick_conn.ambient is not None ) @then('we can measure {sensor_type}') def step_impl(context, sensor_type): if sensor_type == 'electricity': context.brick_conn.cb_ambient() @then('we store the {sensor_type} measurements in the database') def step_impl(context, sensor_type): result = Electricity.query.all() assert result is not None
Update errbit calls to use non-deprecated methods, and add app version
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var userName = this.get("session.currentUser.fullName"); var userId = this.get("session.currentUser.id"); var error = reason instanceof Error || typeof reason != "object" ? reason : JSON.stringify(reason); var environment = config.staging ? "staging" : config.environment; var version = `${config.APP.SHA} (shared ${config.APP.SHARED_SHA})`; var airbrake = new airbrakeJs.Client({ projectId: config.APP.AIRBRAKE_PROJECT_ID, projectKey: config.APP.AIRBRAKE_PROJECT_KEY }); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.notify({ error, context: { userId, userName, environment, version } }); } } });
import Ember from "ember"; import config from "../config/environment"; export default Ember.Service.extend({ session: Ember.inject.service(), error: function(reason) { if (reason.status === 0) { return; } console.info(reason); if (config.environment === "production" || config.staging) { var userName = this.get("session.currentUser.fullName"); var userId = this.get("session.currentUser.id"); var error = reason instanceof Error || typeof reason != "object" ? reason : JSON.stringify(reason); var airbrake = new airbrakeJs.Client(); airbrake.setHost(config.APP.AIRBRAKE_HOST); airbrake.setProject(config.APP.AIRBRAKE_PROJECT_ID, config.APP.AIRBRAKE_PROJECT_KEY); airbrake.setEnvironmentName(config.staging ? "staging" : config.environment); airbrake.push({ error: error, context: { userId: userId, userName: userName } }); } } });
Use correct name for array method 'forEach'
let task = require('./lib/task'); if (process.platform === 'win32') { console.log('Windows is currently not supported. Please use'); console.log(' npm run test:end2end:ldap'); console.log(' npm run test:end2end:meteor'); console.log('instead.'); process.exit(0); } function logTask(taskname) { return function (data) { process.stdout.write(taskname + ': ' + data); } } const tasks = [ task.run('npm', ['run', 'test:end2end:ldap'], logTask('ldap')), task.run('npm', ['run', 'test:end2end:meteor'], logTask('meteor')) ]; if (process.platform === 'win32') { var readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.on('SIGINT', function () { process.emit('SIGINT'); }); } process.on('SIGINT', function () { tasks.forEach((task) => { task.kill(); }); process.exit(); });
let task = require('./lib/task'); if (process.platform === 'win32') { console.log('Windows is currently not supported. Please use'); console.log(' npm run test:end2end:ldap'); console.log(' npm run test:end2end:meteor'); console.log('instead.'); process.exit(0); } function logTask(taskname) { return function (data) { process.stdout.write(taskname + ': ' + data); } } const tasks = [ task.run('npm', ['run', 'test:end2end:ldap'], logTask('ldap')), task.run('npm', ['run', 'test:end2end:meteor'], logTask('meteor')) ]; if (process.platform === 'win32') { var readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.on('SIGINT', function () { process.emit('SIGINT'); }); } process.on('SIGINT', function () { tasks.each((task) => { task.kill(); }); process.exit(); });
Remove timeout argument on update job
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph) @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
import sys import time import logging logging.basicConfig(level=logging.DEBUG) from redis import StrictRedis from rq import Queue from apscheduler.schedulers.blocking import BlockingScheduler from d1lod import jobs conn = StrictRedis(host='redis', port='6379') q = Queue(connection=conn) sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def queue_update_job(): q.enqueue(jobs.update_graph, timeout=3600) # 1 hour timeout @sched.scheduled_job('interval', minutes=1) def queue_stats_job(): q.enqueue(jobs.calculate_stats) @sched.scheduled_job('interval', minutes=1) def queue_export_job(): q.enqueue(jobs.export_graph) @sched.scheduled_job('interval', minutes=1) def print_jobs_job(): sched.print_jobs() # Wait a bit for Sesame to start time.sleep(10) # Queue the stats job first. This creates the repository before any other # jobs are run. q.enqueue(jobs.calculate_stats) # Start the scheduler sched.start()
Exclude PropTypes from UMD build
var config = { output: { libraryTarget: 'umd', library: 'ReactTabs' }, resolve: { extensions: ['', '.js'], alias: { src: __dirname + '/src' } }, externals: { // Use external version of React react: { commonjs: 'react', commonjs2: 'react', amd: 'react', root: 'React' // indicates global variable }, 'prop-types': { commonjs: 'prop-types', commonjs2: 'prop-types', amd: 'prop-types', root: 'PropTypes' } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }] } }; module.exports = config;
var config = { output: { libraryTarget: 'umd', library: 'ReactTabs' }, resolve: { extensions: ['', '.js'], alias: { src: __dirname + '/src' } }, externals: { // Use external version of React react: { commonjs: 'react', commonjs2: 'react', amd: 'react', root: 'React' // indicates global variable } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/ }] } }; module.exports = config;
Make test model metadata configurable
<?php namespace AlgoWeb\PODataLaravel\Models; use AlgoWeb\PODataLaravel\Models\MetadataTrait; use Illuminate\Database\Eloquent\Model as Model; use Illuminate\Database\Schema\Builder as SchemaBuilder; class TestModel extends Model { use MetadataTrait; protected $metaArray; public function __construct(array $meta = null) { if (isset($meta)) { $this->metaArray = $meta; } parent::__construct(); } public function getTable() { return 'testmodel'; } public function getConnectionName() { return 'testconnection'; } protected function getAllAttributes() { return ['id' => 0, 'name' => '', 'added_at' => '', 'weight' => '', 'code' => '']; } public function getFillable() { return [ 'name', 'added_at', 'weight', 'code']; } public function metadata() { if (isset($this->metaArray)) { return $this->metaArray; } return parent::metadata(); } }
<?php namespace AlgoWeb\PODataLaravel\Models; use AlgoWeb\PODataLaravel\Models\MetadataTrait; use Illuminate\Database\Eloquent\Model as Model; use Illuminate\Database\Schema\Builder as SchemaBuilder; class TestModel extends Model { use MetadataTrait; public function getTable() { return 'testmodel'; } public function getConnectionName() { return 'testconnection'; } protected function getAllAttributes() { return ['id' => 0, 'name' => '', 'added_at' => '', 'weight' => '', 'code' => '']; } public function getFillable() { return [ 'name', 'added_at', 'weight', 'code']; } }
Remove dates of existence from bioghist
<?php if (0 < count($creators)): ?> <?php foreach($events as $date): ?> <?php $creator = QubitActor::getById($date->actorId); ?> <?php if (($value = $creator->getHistory(array('cultureFallback' => true))) || $creator->datesOfExistence): ?> <bioghist id="<?php echo 'md5-' . md5(url_for(array($creator, 'module' => 'actor'), true)) ?>" encodinganalog="<?php echo $ead->getMetadataParameter('bioghist') ?>"> <?php if ($value): ?> <note><p><?php echo escape_dc(esc_specialchars($value)) ?></p></note> <?php endif; ?> </bioghist> <?php endif; ?> <?php endforeach; ?> <?php endif; ?>
<?php if (0 < count($creators)): ?> <?php foreach($events as $date): ?> <?php $creator = QubitActor::getById($date->actorId); ?> <?php if (($value = $creator->getHistory(array('cultureFallback' => true))) || $creator->datesOfExistence): ?> <bioghist id="<?php echo 'md5-' . md5(url_for(array($creator, 'module' => 'actor'), true)) ?>" encodinganalog="<?php echo $ead->getMetadataParameter('bioghist') ?>"> <?php if ($value): ?> <note><p><?php echo escape_dc(esc_specialchars($value)) ?></p></note> <?php endif; ?> <?php if ($creator->datesOfExistence): ?> <note><p><date type="existence"><?php echo escape_dc(esc_specialchars($creator->datesOfExistence)) ?></date></p></note> <?php endif; ?> </bioghist> <?php endif; ?> <?php endforeach; ?> <?php endif; ?>
Remove localhost as an explicit dev server
<?php global $project; $project = 'mysite'; include_once dirname(__FILE__).'/local.conf.php'; // Sites running on the following servers will be // run in development mode. See // http://doc.silverstripe.com/doku.php?id=devmode // for a description of what dev mode does. Director::set_dev_servers(array( '127.0.0.1', )); if (!defined('SS_LOG_FILE')) { define('SS_LOG_FILE', '/var/log/silverstripe/'.basename(dirname(dirname(__FILE__))).'.log'); } SS_Log::add_writer(new SS_LogFileWriter(SS_LOG_FILE), SS_Log::NOTICE, '<='); // This line set's the current theme. More themes can be // downloaded from http://www.silverstripe.com/themes/ SSViewer::set_theme('blackcandy'); // enable nested URLs for this site (e.g. page/sub-page/) SiteTree::enable_nested_urls(); MySQLDatabase::set_connection_charset('utf8'); // necessary for now SQLite3Database::$vacuum = false;
<?php global $project; $project = 'mysite'; include_once dirname(__FILE__).'/local.conf.php'; // Sites running on the following servers will be // run in development mode. See // http://doc.silverstripe.com/doku.php?id=devmode // for a description of what dev mode does. Director::set_dev_servers(array( 'localhost', '127.0.0.1', )); if (!defined('SS_LOG_FILE')) { define('SS_LOG_FILE', '/var/log/silverstripe/'.basename(dirname(dirname(__FILE__))).'.log'); } SS_Log::add_writer(new SS_LogFileWriter(SS_LOG_FILE), SS_Log::NOTICE, '<='); // This line set's the current theme. More themes can be // downloaded from http://www.silverstripe.com/themes/ SSViewer::set_theme('blackcandy'); // enable nested URLs for this site (e.g. page/sub-page/) SiteTree::enable_nested_urls(); MySQLDatabase::set_connection_charset('utf8'); // necessary for now SQLite3Database::$vacuum = false;
Add a method to know the number of listeners
package zephyr.plugin.core.api.signals; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Signal<T> { static public interface EventInfoGenerator<T> { T generate(); } private final List<Listener<T>> listeners = new LinkedList<Listener<T>>(); public Signal() { super(); } synchronized public Listener<T> connect(Listener<T> listener) { assert listener != null; assert this.listeners.indexOf(listener) == -1; this.listeners.add(listener); return listener; } synchronized public void disconnect(Listener<T> listener) { boolean elementFound; elementFound = listeners.remove(listener); assert elementFound; } public final void fire(T eventInfo) { for (Listener<T> listener : getListeners()) listener.listen(eventInfo); } synchronized private ArrayList<Listener<T>> getListeners() { return new ArrayList<Listener<T>>(listeners); } public final void fireIFN(EventInfoGenerator<T> eventInfoGenerator) { if (listeners.isEmpty()) return; fire(eventInfoGenerator.generate()); } public int nbListeners() { return listeners.size(); } }
package zephyr.plugin.core.api.signals; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Signal<T> { static public interface EventInfoGenerator<T> { T generate(); } private final List<Listener<T>> listeners = new LinkedList<Listener<T>>(); public Signal() { super(); } synchronized public Listener<T> connect(Listener<T> listener) { assert listener != null; assert this.listeners.indexOf(listener) == -1; this.listeners.add(listener); return listener; } synchronized public void disconnect(Listener<T> listener) { boolean elementFound; elementFound = listeners.remove(listener); assert elementFound; } public final void fire(T eventInfo) { for (Listener<T> listener : getListeners()) listener.listen(eventInfo); } synchronized private ArrayList<Listener<T>> getListeners() { return new ArrayList<Listener<T>>(listeners); } public final void fireIFN(EventInfoGenerator<T> eventInfoGenerator) { if (listeners.isEmpty()) return; fire(eventInfoGenerator.generate()); } }
Refactor Javascript now concepts are understood (again)
var maxColumns = 3 var buildStatusPadding = 10 var fontResizeFactor = 1.6 function buildStatusCount() { return $('li').size() } function numberOfColumns() { return Math.min(maxColumns, buildStatusCount()) } function numberOfRows() { return Math.ceil(buildStatusCount() / maxColumns) } function buildStatusWidth() { return window.innerWidth / numberOfColumns() - buildStatusPadding } function buildStatusHeight() { return window.innerHeight / numberOfRows() - buildStatusPadding } function scaleFontToContainerSize() { $(".outerContainer").fitText(fontResizeFactor) } function styleListItems() { $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth()) scaleFontToContainerSize() } function addBuildStatusToScreen(project) { var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } } function addListItems(data) { $('#projects').empty() data.body.forEach(addBuildStatusToScreen) } function updateBuildMonitor() { $.getJSON("/projects").then(function(data){ addListItems(data) styleListItems() }) } updateBuildMonitor() // run immediately setInterval(updateBuildMonitor, 5000)
var columns = 3 var itemPadding = 10 function numberOfColumns() { var buildStatusCount = $('li').size() return Math.min(columns, $('li').size()) } function numberOfRows() { var buildStatusCount = $('li').size() return Math.ceil(buildStatusCount / columns) } function buildStatusWidth() { return window.innerWidth / numberOfColumns() - itemPadding } function buildStatusHeight() { return window.innerHeight / numberOfRows() - itemPadding } function styleListItems() { $('.outerContainer').height(buildStatusHeight()).width(buildStatusWidth()) scaleFontToContainerSize() } function scaleFontToContainerSize() { $(".outerContainer").fitText(1.75) } function addBuildStatusToScreen(project) { var buildStatus = project.lastBuildStatus if(buildStatus !== "Success"){ $('#projects').append("<li><div class=outerContainer><div class=innerContainer>" + project.name + "</div></div></li>") } } function addListItems(data) { $('#projects').empty() data.body.forEach(addBuildStatusToScreen) } function updateBuildMonitor() { $.getJSON("/projects").then(function(data){ addListItems(data) styleListItems() }) } updateBuildMonitor() // run immediately setInterval(updateBuildMonitor, 5000)
Fix trove classifier: Cython is not used
import sys from setuptools import setup if sys.version_info < (2, 6): sys.stdout.write("At least Python 2.6 is required.\n") sys.exit(1) setup( name = 'xopen', version = '0.1.0', author = 'Marcel Martin', author_email = 'mail@marcelm.net', url = 'https://github.com/marcelm/xopen/', description = 'Open compressed files transparently', license = 'MIT', py_modules = ['xopen'], classifiers = [ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
import sys from setuptools import setup if sys.version_info < (2, 6): sys.stdout.write("At least Python 2.6 is required.\n") sys.exit(1) setup( name = 'xopen', version = '0.1.0', author = 'Marcel Martin', author_email = 'mail@marcelm.net', url = 'https://github.com/marcelm/xopen/', description = 'Open compressed files transparently', license = 'MIT', py_modules = ['xopen'], classifiers = [ "Development Status :: 4 - Beta", "License :: OSI Approved :: MIT License", "Programming Language :: Cython", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", ] )
Add a constant for `pipe`.
// Copyright 2012 The Obvious Corporation. /* * Common constants used within this module */ /* * Exported bindings */ /** * Special error value indicating that there was in fact no error. This * is used instead of `undefined` to disambiguate the no-error case from * the case of an error receieved but with an `undefined` payload. * * The deal is that because we know no other code can legitimately * reach into this module to retrieve this value, we can use a `===` * comparison to this value to make the error / no-error * determination. */ var NO_ERROR = [ "no-error" ]; Object.freeze(NO_ERROR); module.exports = { // event names CLOSE: "close", DATA: "data", DRAIN: "drain", END: "end", ERROR: "error", // also used as an ifPartial value PIPE: "pipe", // encoding names ASCII: "ascii", BASE64: "base64", UCS2: "ucs2", HEX: "hex", UTF16LE: "utf16le", UTF8: "utf8", // ifPartial option values EMIT: "emit", IGNORE: "ignore", PAD: "pad", // other NO_ERROR: NO_ERROR };
// Copyright 2012 The Obvious Corporation. /* * Common constants used within this module */ /* * Exported bindings */ /** * Special error value indicating that there was in fact no error. This * is used instead of `undefined` to disambiguate the no-error case from * the case of an error receieved but with an `undefined` payload. * * The deal is that because we know no other code can legitimately * reach into this module to retrieve this value, we can use a `===` * comparison to this value to make the error / no-error * determination. */ var NO_ERROR = [ "no-error" ]; Object.freeze(NO_ERROR); module.exports = { // event names CLOSE: "close", DATA: "data", DRAIN: "drain", END: "end", ERROR: "error", // also used as an ifPartial value // encoding names ASCII: "ascii", BASE64: "base64", UCS2: "ucs2", HEX: "hex", UTF16LE: "utf16le", UTF8: "utf8", // ifPartial option values EMIT: "emit", IGNORE: "ignore", PAD: "pad", // other NO_ERROR: NO_ERROR };
Add some cleanup. * Move the icons into their own dictionary. * Use a url object to do the parsing. * Check for all 200-level statuses. * Check that the response was JSON.
var require("sdk/tabs"); var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var domain, reqest, response ; var icons = { "inactive": { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" } "active": { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" } } var button = buttons.ActionButton({ id: "contribute", label: "How to contribute!", icon: icons.inactive, onClick: dealWithIt; }); functon dealWithIt() { console.log(""); }; function toggleIcon(state) { if(state == true){ button.icon = icons.active; } } tab.on('ready', function(tab){ req = require("sdk/request").Request({ url: new URL("/contribute.json", window.location), onComplete: function(resp){ if(resp.status >= 200 && resp.status < 300 && resp.json != null){ toggleIcon(true); console.log(url + " - Contribute.json available!"); } else { toggleIcon(false); console.log(url + " - Contribute.json unavailable, humbug."); }); });
var require("sdk/tabs"); var buttons = require('sdk/ui/button/action'); var tabs = require("sdk/tabs"); var domain, reqest, response ; var icons = var button = buttons.ActionButton({ id: "contribute", label: "How to contribute!", icon: { "16": "./icon-16.png", "32": "./icon-32.png", "64": "./icon-64.png" }, onClick: dealWithIt; }); functon dealWithIt() { console.log(""); }; function toggleIcon(state) { if(state == true){ button.icon.16 = "./ tab.on('ready', function(tab){ req = require("sdk/request").Request({ url: window.location.protocol + window.location.host + "/contribute.json", onComplete: function(resp){ if(req.status == 200){ toggleIcon(true); console.log(url + " - Contribute.json available!"); } else { toggleIcon(false); console.log(url + " - Contribute.json unavailable, humbug."); }); });
Update to laravel 5.1 ::class notation
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application( realpath(__DIR__.'/../') ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $app->singleton( Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application( realpath(__DIR__.'/../') ); /* |-------------------------------------------------------------------------- | Bind Important Interfaces |-------------------------------------------------------------------------- | | Next, we need to bind some important interfaces into the container so | we will be able to resolve them when needed. The kernels serve the | incoming requests to this application from both the web and CLI. | */ $app->singleton( 'Illuminate\Contracts\Http\Kernel', 'App\Http\Kernel' ); $app->singleton( 'Illuminate\Contracts\Console\Kernel', 'App\Console\Kernel' ); $app->singleton( 'Illuminate\Contracts\Debug\ExceptionHandler', 'App\Exceptions\Handler' ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate') config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') config.add_subpackage('linsolve') config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') config.add_subpackage('sandbox') config.add_subpackage('signal') config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') config.add_subpackage('ndimage') config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpolate') #config.add_subpackage('io') config.add_subpackage('lib') config.add_subpackage('linalg') #config.add_subpackage('linsolve') #config.add_subpackage('maxentropy') config.add_subpackage('misc') #config.add_subpackage('montecarlo') config.add_subpackage('optimize') #config.add_subpackage('sandbox') #config.add_subpackage('signal') #config.add_subpackage('sparse') config.add_subpackage('special') config.add_subpackage('stats') #config.add_subpackage('ndimage') #config.add_subpackage('weave') config.make_svn_version_py() # installs __svn_version__.py config.make_config_py() return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
Comment out paste plain text line and give the option to paste with formatting.
CKEDITOR.editorConfig = function( config ) { config.allowedContent = true; config.removeFormatTags = ""; config.protectedSource.push(/<r:([\S]+).*<\/r:\1>/g); config.protectedSource.push(/<r:[^>/]*\/>/g); //let paste from word be available // config.forcePasteAsPlainText = false; // if you want to remove clipboard, you have to remove all of these: // clipboard, pastetext, pastefromword config.removePlugins = "save, newpage, preview, print, templates, forms, flash, smiley, language, pagebreak, iframe, bidi"; var startupMode = $.cookie('ckeditor.startupMode'); if (startupMode == 'source' || startupMode == 'wysiwyg' ) { config.startupMode = startupMode; } this.on('mode', function(){ $.cookie('ckeditor.startupMode', this.mode); }) };
CKEDITOR.editorConfig = function( config ) { config.allowedContent = true; config.removeFormatTags = ""; config.protectedSource.push(/<r:([\S]+).*<\/r:\1>/g); config.protectedSource.push(/<r:[^>/]*\/>/g); config.forcePasteAsPlainText = true; // if you want to remove clipboard, you have to remove all of these: // clipboard, pastetext, pastefromword config.removePlugins = "save, newpage, preview, print, templates, forms, flash, smiley, language, pagebreak, iframe, bidi"; var startupMode = $.cookie('ckeditor.startupMode'); if (startupMode == 'source' || startupMode == 'wysiwyg' ) { config.startupMode = startupMode; } this.on('mode', function(){ $.cookie('ckeditor.startupMode', this.mode); }) };
Fix creation of Auth instance and pass entryUUID to it.
'use strict'; var method = require('../../waterlock-ldap-auth'); var ldap = method.ldap; var connection = method.connection; /** * Login action */ module.exports = function(req, res) { var params = req.params.all(); if (typeof params.username === 'undefined' || typeof params.password === 'undefined') { waterlock.cycle.loginFailure(req, res, null, {error: 'Invalid username or password'}); } else { var auth = new ldap(connection); console.log("User attributes: %j", waterlock.User.attributes); auth.authenticate(params.username, params.password, function(err, user) { if (err) { waterlock.cycle.loginFailure(req, res, user, {error: 'Invalid username or password'}); } else { var criteria = { username: params.username }; var attr = { username: params.username, entryUUID: user.entryUUID }; waterlock.engine.findOrCreateAuth(criteria, attr, function(err, user) { if (err) { waterlock.cycle.loginFailure(req, res, null, {error: 'user not found'}); } else { waterlock.cycle.loginSuccess(req, res, user); } }); } }); } };
'use strict'; var method = require('../../waterlock-ldap-auth'); var ldap = method.ldap; var connection = method.connection; /** * Login action */ module.exports = function(req, res) { var params = req.params.all(); if (typeof params.username === 'undefined' || typeof params.password === 'undefined') { waterlock.cycle.loginFailure(req, res, null, {error: 'Invalid username or password'}); } else { var auth = new ldap(connection); console.log("User attributes: %j", waterlock.User.attributes); auth.authenticate(params.username, params.password, function(err, user) { if (err) { waterlock.cycle.loginFailure(req, res, user, {error: 'Invalid username or password'}); } else { var criteria = { username: params.username }; var attr = { username: params.username, entryUUID: user }; waterlock.engine.findOrCreateAuth(criteria, attr).exec(function(err, user) { if (err) { waterlock.cycle.loginFailure(req, res, null, {error: 'user not found'}); } else { waterlock.cycle.loginSuccess(req, res, user); } }); } }); } };
Allow custom translation loader for resources.
<?php namespace Devture\Bundle\LocalizationBundle\Translation; use Symfony\Component\Translation\Translator; class ResourceLoader { private $translator; private $format; public function __construct(Translator $translator, $format) { $this->translator = $translator; $this->format = $format; } public function addResources($path, $loaderName = null) { if ($loaderName === null) { $loaderName = $this->format; } $path = rtrim($path, '/'); foreach (glob($path . '/*.' . $this->format) as $filePath) { $parts = explode('/', $filePath); list($localeKey, $_extension) = explode('.', array_pop($parts)); $this->translator->addResource($loaderName, $filePath, $localeKey); } } }
<?php namespace Devture\Bundle\LocalizationBundle\Translation; use Symfony\Component\Translation\Translator; class ResourceLoader { private $translator; private $format; public function __construct(Translator $translator, $format) { $this->translator = $translator; $this->format = $format; } public function addResources($path) { $path = rtrim($path, '/'); foreach (glob($path . '/*.' . $this->format) as $filePath) { $parts = explode('/', $filePath); list($localeKey, $_extension) = explode('.', array_pop($parts)); $this->translator->addResource($this->format, $filePath, $localeKey); } } }
Convert script to Python 3 Changed print function in main to be Python 3 compatible
import sys from datetime import datetime TEMPLATE = """ Title: {title} Date: {year}-{month}-{day} {hour}:{minute:02d} Modified: Author: Category: Tags: """ def make_entry(title): today = datetime.today() title_no_whitespaces = title.lower().strip().replace(' ', '-') f_create = "content/{}_{:0>2}_{:0>2}_{}.md".format( today.year, today.month, today.day, title_no_whitespaces) t = TEMPLATE.strip().format(title=title, year=today.year, month=today.month, day=today.day, hour=today.hour, minute=today.minute) with open(f_create, 'w') as w: w.write(t) print("File created -> " + f_create) if __name__ == '__main__': if len(sys.argv) > 1: make_entry(sys.argv[1]) else: print("No title given")
import sys from datetime import datetime TEMPLATE = """ Title: {title} Date: {year}-{month}-{day} {hour}:{minute:02d} Modified: Author: Category: Tags: """ def make_entry(title): today = datetime.today() title_no_whitespaces = title.lower().strip().replace(' ', '-') f_create = "content/{}_{:0>2}_{:0>2}_{}.md".format( today.year, today.month, today.day, title_no_whitespaces) t = TEMPLATE.strip().format(title=title, year=today.year, month=today.month, day=today.day, hour=today.hour, minute=today.minute) with open(f_create, 'w') as w: w.write(t) print("File created -> " + f_create) if __name__ == '__main__': if len(sys.argv) > 1: make_entry(sys.argv[1]) else: print "No title given"
Fix random strings minimal expected length
from django.test import TestCase from .. import factories, models class RepositoryFactoryTestCase(TestCase): def test_can_create_repository(self): qs = models.Repository.objects.all() self.assertEqual(qs.count(), 0) repository = factories.RepositoryFactory() self.assertGreater(len(repository.name), 0) self.assertGreater(len(repository.url), 0) self.assertEqual(qs.count(), 1) class EntryFactoryTestCase(TestCase): def test_can_create_entry(self): entry_qs = models.Entry.objects.all() repository_qs = models.Repository.objects.all() self.assertEqual(entry_qs.count(), 0) self.assertEqual(repository_qs.count(), 0) entry = factories.EntryFactory() self.assertGreater(len(entry.identifier), 0) self.assertGreater(len(entry.description), 0) self.assertGreater(len(entry.url), 0) self.assertGreater(len(entry.repository.name), 0) self.assertEqual(entry_qs.count(), 1) self.assertEqual(repository_qs.count(), 1)
from django.test import TestCase from .. import factories, models class RepositoryFactoryTestCase(TestCase): def test_can_create_repository(self): qs = models.Repository.objects.all() self.assertEqual(qs.count(), 0) repository = factories.RepositoryFactory() self.assertGreater(len(repository.name), 1) self.assertGreater(len(repository.url), 1) self.assertEqual(qs.count(), 1) class EntryFactoryTestCase(TestCase): def test_can_create_entry(self): entry_qs = models.Entry.objects.all() repository_qs = models.Repository.objects.all() self.assertEqual(entry_qs.count(), 0) self.assertEqual(repository_qs.count(), 0) entry = factories.EntryFactory() self.assertGreater(len(entry.identifier), 1) self.assertGreater(len(entry.description), 1) self.assertGreater(len(entry.url), 1) self.assertGreater(len(entry.repository.name), 1) self.assertEqual(entry_qs.count(), 1) self.assertEqual(repository_qs.count(), 1)
Add line breaks between methods in HTMLRenderer
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
import React from 'react'; import renderHTML from 'react-render-html'; import SocketClient from './socket-client'; import PropTypes from 'prop-types'; class HTMLRenderer extends React.Component { constructor(props) { super(props); this.state = { html: '' }; } componentDidMount() { this.socketClient = new SocketClient(this.props.location); this.socketClient.onData(html => this.setState({ html })); } componentDidUpdate() { if (this.props.onUpdate) { this.props.onUpdate(); } } render() { return React.createElement('div', null, renderHTML(this.state.html)); } } HTMLRenderer.propTypes = { location: PropTypes.shape({ host: PropTypes.string.isRequired, pathname: PropTypes.string.isRequired, }).isRequired, onUpdate: PropTypes.func, }; export default HTMLRenderer;
Use hyphen in package name Signed-off-by: Michael Barton <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@michaelbarton.me.uk>
from setuptools import setup, find_packages import biobox_cli setup( name = 'biobox-cli', version = biobox_cli.__version__, description = 'Run biobox Docker containers on the command line', author = 'bioboxes', author_email = 'mail@bioboxes.org', url = 'http://bioboxes.org', packages = ['biobox_cli'], scripts = ['bin/biobox'], install_requires = open('requirements.txt').read().splitlines(), classifiers = [ 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Intended Audience :: Science/Research', 'Operating System :: POSIX' ], )
from setuptools import setup, find_packages import biobox_cli setup( name = 'biobox_cli', version = biobox_cli.__version__, description = 'Run biobox Docker containers on the command line', author = 'bioboxes', author_email = 'mail@bioboxes.org', url = 'http://bioboxes.org', packages = ['biobox_cli'], scripts = ['bin/biobox'], install_requires = open('requirements.txt').read().splitlines(), classifiers = [ 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Bio-Informatics', 'Intended Audience :: Science/Research', 'Operating System :: POSIX' ], )
Add headers and change the email which is generated when registering.
<?php class Email { public $db = null; public $email = ''; public $from = 'luke@lcahill.co.uk'; public $subject = 'Note Keeper - please confirm your email.'; public $message = ''; public $userId = ''; public $headers = 'From: luke@lcahill.co.uk' . "\r\n" . 'Reply-To: luke@lcahill.co.uk' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); function __construct($email, $userId, $db) { $this->email = $email; $this->userId = $userId; $this->db = $db; } function constructConfirmLink() { $date = new DateTime(); $timestamp = $date->getTimestamp(); $confirm = md5($timestamp); $stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId"); $stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId)); $url = $_SERVER['SERVER_NAME']; $link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId; $this->message = 'Please follow this link to confirm your account ' . $link; $this->sendEmail(); } function sendEmail() { mail($this->email, $this->subject, $this->message, $this->headers); } } ?>
<?php class Email { public $db = null; public $email = ''; public $from = 'luke@lcahill.co.uk'; public $subject = 'Note Keeper - please confirm your email.'; public $message = ''; public $userId = ''; function __construct($email, $userId, $db) { $this->email = $email; $this->userId = $userId; $this->db = $db; } function constructConfirmLink() { $date = new DateTime(); $timestamp = $date->getTimestamp(); $confirm = md5($timestamp); $stmt = $this->db->prepare("UPDATE note_users SET EmailConfirmation = :confirm WHERE UserId = :userId"); $stmt->execute(array(':confirm' => $confirm, ':userId' => $this->userId)); $url = $_SERVER['SERVER_NAME']; $link = 'http://' . $url . '/notes/confirm.php?hash=' . $confirm . '&user=' . $this->userId; $this->message = 'Please follow this link to confirm your account <a href="' . $link . '">' . $link . '</a>'; $this->sendEmail(); } function sendEmail() { mail($this->email, $this->subject, $this->message); } } ?>
Add full browser height page layout.
/* @flow */ import React, { Component, PropTypes } from 'react'; import GrommetApp from 'grommet/components/App'; import Box from 'grommet/components/Box'; import { AppContainer as ReactHotLoader } from 'react-hot-loader'; import { Nav, PageMarquee, Footer } from 'components'; // eslint-disable-next-line react/prefer-stateless-function class RootApp extends Component { render() { return ( <ReactHotLoader> <GrommetApp centered={false} style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', }} > <Nav /> <Box flex style={{ minHeight: '100%' }}> <PageMarquee /> <Box flex> {this.props.children} </Box> <Footer /> </Box> </GrommetApp> </ReactHotLoader> ); } } RootApp.propTypes = { children: PropTypes.node.isRequired, }; export default RootApp;
/* @flow */ import React, { Component, PropTypes } from 'react'; import GrommetApp from 'grommet/components/App'; import { AppContainer as ReactHotLoader } from 'react-hot-loader'; import { Nav, PageMarquee, Footer } from 'components'; // eslint-disable-next-line react/prefer-stateless-function class RootApp extends Component { render() { return ( <ReactHotLoader> <GrommetApp centered={false}> <Nav /> <PageMarquee /> {this.props.children} <Footer /> </GrommetApp> </ReactHotLoader> ); } } RootApp.propTypes = { children: PropTypes.node.isRequired, }; export default RootApp;
[ADD] Create account.tax.template with external ids
# Copyright 2020 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class L10nBrAccountTaxTemplate(models.Model): _name = 'l10n_br_account.tax.template' _inherit = 'account.tax.template' chart_template_id = fields.Many2one(required=False) def create_account_tax_templates(self, chart_template_id): self.ensure_one() chart = self.env['account.chart.template'].browse(chart_template_id) module = chart.get_external_id()[chart_template_id].split('.')[0] xmlid = '.'.join( [module, self.get_external_id()[self.id].split('.')[1]]) tax_template_data = self.copy_data()[0] tax_template_data.update({'chart_template_id': chart_template_id}) data = dict(xml_id=xmlid, values=tax_template_data, noupdate=True) self.env['account.tax.template']._load_records([data])
# Copyright 2020 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class L10nBrAccountTaxTemplate(models.Model): _name = 'l10n_br_account.tax.template' _inherit = 'account.tax.template' chart_template_id = fields.Many2one(required=False) def create_account_tax_templates(self, chart_template_id): self.ensure_one() account_tax_template_data = {'chart_template_id': chart_template_id} account_tax_template_data.update({ field: self[field] for field in self._fields if self[field] is not False}) self.env['account.tax.template'].create(account_tax_template_data)
Remove the code instead of having the compiler do this.
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.qp.operator; public abstract class OperatorCursor extends OperatorExecutionBase implements Cursor { protected OperatorCursor(QueryContext context) { super(context); } @Override public QueryBindings openTopLevel() { openBindings(); QueryBindings bindings = nextBindings(); assert (bindings != null); open(); return bindings; } @Override public void closeTopLevel() { close(); closeBindings(); } }
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.qp.operator; public abstract class OperatorCursor extends OperatorExecutionBase implements Cursor { protected OperatorCursor(QueryContext context) { super(context); } @Override public QueryBindings openTopLevel() { openBindings(); QueryBindings bindings = nextBindings(); assert (bindings != null); open(); return bindings; } @Override public void closeTopLevel() { close(); if (CURSOR_LIFECYCLE_ENABLED) { QueryBindings bindings = nextBindings(); assert (bindings == null); } closeBindings(); } }
Remove uuid in constructor, since strong loop server will see null as value provided, there won't be any defaultFn called. Otherwise you can give uuid "undefined", it's OK.
import CartBlogEditorCtrl from './base/cart-blog-editor.js'; class CartBlogCreateCtrl extends CartBlogEditorCtrl { constructor(...args) { super(...args); this.logInit('CartBlogCreateCtrl'); this.init(); } init() { this.apiService.postDefaultCategory().then( (category) => { this.category = category; this.post.category = category.uuid; }, (error) => this.msgService.error(error) ); this.tags = []; this.attachments = []; this.post = { driveId: null, title: '', created: new Date(), updated: new Date(), category: null, tags: [], attachments: [], isPublic: this.apiService.postDefaultPrivacy() } } //noinspection ES6Validation async save() { try { //noinspection ES6Validation let post = await this.apiService.postUpsert(this.post); this.msgService.info('Post saved: ', post); } catch (e) { this.msgService.error('Error when creating post: ', e.data.error.message); } } } CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject]; export default CartBlogCreateCtrl;
import CartBlogEditorCtrl from './base/cart-blog-editor.js'; class CartBlogCreateCtrl extends CartBlogEditorCtrl { constructor(...args) { super(...args); this.logInit('CartBlogCreateCtrl'); this.init(); } init() { this.apiService.postDefaultCategory().then( (category) => { this.category = category; this.post.category = category.uuid; }, (error) => this.msgService.error(error) ); this.tags = []; this.attachments = []; this.post = { uuid: null, driveId: null, title: '', created: new Date(), updated: new Date(), category: null, tags: [], attachments: [], isPublic: this.apiService.postDefaultPrivacy() } } //noinspection ES6Validation async save() { try { //noinspection ES6Validation let post = await this.apiService.postUpsert(this.post); this.msgService.info('Post saved: ', post); } catch (e) { this.msgService.error('Error when creating post: ', e.data.error.message); } } } CartBlogCreateCtrl.$inject = [...CartBlogEditorCtrl.$inject]; export default CartBlogCreateCtrl;
Fix permissions on Aphlict log Summary: Currently, the Aphlict server created the log file (if it doesn't exist) but then immediately fails with "Unable to open logfile". It seems that we don't set the permissions correctly. Test Plan: Deleted log file and was able to start the Aphlict server. Reviewers: epriestley, #blessed_reviewers Reviewed By: epriestley, #blessed_reviewers Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.com/D11351
var JX = require('javelin').JX; var fs = require('fs'); var util = require('util'); JX.install('AphlictLog', { construct: function() { this._writeToLogs = []; this._writeToConsoles = []; }, members: { _writeToConsoles: null, _writeToLogs: null, addLogfile: function(path) { var options = { flags: 'a', encoding: 'utf8', mode: 0664, }; var logfile = fs.createWriteStream(path, options); this._writeToLogs.push(logfile); return this; }, addConsole: function(console) { this._writeToConsoles.push(console); return this; }, log: function() { var str = util.format.apply(null, arguments); var date = new Date().toLocaleString(); str = '[' + date + '] ' + str; var ii; for (ii = 0; ii < this._writeToConsoles.length; ii++) { this._writeToConsoles[ii].log(str); } for (ii = 0; ii < this._writeToLogs.length; ii++) { this._writeToLogs[ii].write(str + '\n'); } } } });
var JX = require('javelin').JX; var fs = require('fs'); var util = require('util'); JX.install('AphlictLog', { construct: function() { this._writeToLogs = []; this._writeToConsoles = []; }, members: { _writeToConsoles: null, _writeToLogs: null, addLogfile: function(path) { var options = { flags: 'a', encoding: 'utf8', mode: 066 }; var logfile = fs.createWriteStream(path, options); this._writeToLogs.push(logfile); return this; }, addConsole: function(console) { this._writeToConsoles.push(console); return this; }, log: function() { var str = util.format.apply(null, arguments); var date = new Date().toLocaleString(); str = '[' + date + '] ' + str; var ii; for (ii = 0; ii < this._writeToConsoles.length; ii++) { this._writeToConsoles[ii].log(str); } for (ii = 0; ii < this._writeToLogs.length; ii++) { this._writeToLogs[ii].write(str + '\n'); } } } });
Update test to use new adapter
/** * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.groupby; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.SelectProvider; import org.mybatis.dynamic.sql.select.render.SelectStatement; import org.mybatis.dynamic.sql.util.SqlProviderAdapter; public interface GroupByMapper { @SelectProvider(type=SqlProviderAdapter.class, method="select") List<Map<String, Object>> generalSelect(SelectStatement selectStatement); }
/** * Copyright 2016-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.groupby; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Select; import org.mybatis.dynamic.sql.select.render.SelectStatement; public interface GroupByMapper { @Select({ "${selectStatement}" }) List<Map<String, Object>> generalSelect(SelectStatement selectStatement); }
Add whitespace to be consistent with other modules
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; /** * Representation of Message. */ public class Message extends Entity { /** * Class Constructor. * * @param service The connected service instance. * @param path The message endpoint. */ Message(Service service, String path) { super(service, path); } /** * Returns this message's title. * * @return This message's title. */ public String getKey() { return getTitle(); } /** * Returns this message's value. * * @return This message's value. */ public String getValue() { return getString(getKey()); } }
/* * Copyright 2011 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.splunk; /** * Representation of Message. */ public class Message extends Entity { /** * Class Constructor. * * @param service The connected service instance. * @param path The message endpoint. */ Message(Service service, String path) { super(service, path); } /** * Returns this message's title. * @return This message's title. */ public String getKey() { return getTitle(); } /** * Returns this message's value. * @return This message's value. */ public String getValue() { return getString(getKey()); } }
Allow plusplus in for loops
module.exports = { "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "experimentalObjectRestSpread": true, }, }, "rules": { "arrow-parens": "warn", "comma-dangle": ["error", "always-multiline"], "max-len": ["error", { "code": 100, "ignoreUrls": true, "ignoreRegExpLiterals": true, "tabWidth": 2, }], "no-plusplus": ["error", { "allowForLoopAfterthoughts": true, }], "no-prototype-builtins": "off", "no-underscore-dangle": "off", "quotes": ["error", "double", { "avoidEscape": true, }], "semi": ["error", "never"], "import/no-unresolved": "off", }, }
module.exports = { "parserOptions": { "ecmaVersion": 6, "sourceType": "module", "ecmaFeatures": { "experimentalObjectRestSpread": true, }, }, "rules": { "arrow-parens": "warn", "comma-dangle": ["error", "always-multiline"], "max-len": ["error", { "code": 100, "ignoreUrls": true, "ignoreRegExpLiterals": true, "tabWidth": 2, }], "no-prototype-builtins": "off", "no-underscore-dangle": "off", "quotes": ["error", "double", { "avoidEscape": true, }], "semi": ["error", "never"], "import/no-unresolved": "off", }, }
test/unit/default-config: Add describe() block per config file
var fs = require('fs'); var path = require('path'); var assert = require('power-assert'); var rules = require('../../lib/rules'); var DEFAULT_CONFIG_PATH = path.join(__dirname, '..', '..', 'lib', 'config'); describe('default configurations', function() { var configFiles = fs.readdirSync(DEFAULT_CONFIG_PATH); configFiles.forEach(function(file) { describe(file, function() { it('should contain only valid rules', function() { var config = require(path.join(DEFAULT_CONFIG_PATH, file)); for (var rule in config.rules) { assert(rule in rules); } }); it('should contain only valid rule configuration', function() { var config = require(path.join(DEFAULT_CONFIG_PATH, file)); for (var rule in config.rules) { var options = { config: config.rules[rule] }; var Rule = rules[rule](options); assert.doesNotThrow(function() { new Rule({ rawSource: '' }); }); } }); }); }); });
var fs = require('fs'); var path = require('path'); var assert = require('power-assert'); var rules = require('../../lib/rules'); var DEFAULT_CONFIG_PATH = path.join(__dirname, '..', '..', 'lib', 'config'); describe('default configurations', function() { describe('use valid rules', function() { var configFiles = fs.readdirSync(DEFAULT_CONFIG_PATH); configFiles.forEach(function(file) { it('should contain only valid rules', function() { var config = require(path.join(DEFAULT_CONFIG_PATH, file)); for (var rule in config.rules) { assert(rule in rules); } }); it('should contain only valid rule configuration', function() { var config = require(path.join(DEFAULT_CONFIG_PATH, file)); for (var rule in config.rules) { var options = { config: config.rules[rule] }; var Rule = rules[rule](options); assert.doesNotThrow(function() { new Rule({ rawSource: '' }); }); } }); }); }); });
Make config schema path to be relative to installation directory. This changed fixes wrong assumption that working directory of IRC bridge is always a directory where it's installed. Schema path has been changed to be relative to installation directory, not working directory. Signed-off-by: Oleg Girko <665b39a1e96a9a15fc99f73183af3f04bf8111eb@infoserver.lv>
"use strict"; var Cli = require("matrix-appservice-bridge").Cli; var log = require("./lib/logging").get("CLI"); var main = require("./lib/main"); var path = require("path"); const REG_PATH = "appservice-registration-irc.yaml"; new Cli({ registrationPath: REG_PATH, enableRegistration: true, enableLocalpart: true, bridgeConfig: { affectsRegistration: true, schema: path.join(__dirname, "lib/config/schema.yml"), defaults: main.defaultConfig() }, generateRegistration: function(reg, callback) { main.generateRegistration(reg, this.getConfig()).done(function(completeRegistration) { callback(completeRegistration); }); }, run: function(port, config, reg) { main.runBridge(port, config, reg).catch(function(err) { log.error("Failed to run bridge."); throw err; }); } }).run();
"use strict"; var Cli = require("matrix-appservice-bridge").Cli; var log = require("./lib/logging").get("CLI"); var main = require("./lib/main"); const REG_PATH = "appservice-registration-irc.yaml"; new Cli({ registrationPath: REG_PATH, enableRegistration: true, enableLocalpart: true, bridgeConfig: { affectsRegistration: true, schema: "./lib/config/schema.yml", defaults: main.defaultConfig() }, generateRegistration: function(reg, callback) { main.generateRegistration(reg, this.getConfig()).done(function(completeRegistration) { callback(completeRegistration); }); }, run: function(port, config, reg) { main.runBridge(port, config, reg).catch(function(err) { log.error("Failed to run bridge."); throw err; }); } }).run();
Fix IndexController test for string differences Sometimes the whitespace may be different, but the content shouldn’t be.
<?php namespace Ilios\WebBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class IndexControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $client->request('GET', '/'); $response = $client->getResponse(); $content = $response->getContent(); $container = $client->getContainer(); $builder = $container->get('iliosweb.jsonindex'); $text = $builder->getIndex('prod'); $text = preg_replace('/\s+/', '', $text); $content = preg_replace('/\s+/', '', $content); $this->assertSame($text, $content); //ensure we have a 60 second max age $this->assertSame(60, $response->getMaxAge()); } }
<?php namespace Ilios\WebBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class IndexControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $client->request('GET', '/'); $response = $client->getResponse(); $content = $response->getContent(); $container = $client->getContainer(); $builder = $container->get('iliosweb.jsonindex'); $text = $builder->getIndex('prod'); $this->assertSame($text, $content); //ensure we have a 60 second max age $this->assertSame(60, $response->getMaxAge()); } }
Add options property to trait
<?php declare(strict_types=1); namespace GarethEllis\Tldr\Fetcher; use GarethEllis\Tldr\Fetcher\Exception\PageNotFoundException; use GarethEllis\Tldr\Fetcher\Exception\UnknownOperatingSystemException; trait OperatingSystemTrait { /** * @var array */ private $options; protected function getOperatingSystem(): String { if (isset($this->options["operatingSystem"])) { return $this->options["operatingSystem"]; } $uname = strtolower(php_uname()); if (strpos($uname, "darwin") !== false) { return "osx"; } elseif (strpos($uname, "win") !== false) { return "windows"; } elseif (strpos($uname, "linux") !== false) { return "linux"; } throw new UnknownOperatingSystemException("Unknown operating system {$uname}"); } }
<?php declare(strict_types=1); namespace GarethEllis\Tldr\Fetcher; use GarethEllis\Tldr\Fetcher\Exception\PageNotFoundException; use GarethEllis\Tldr\Fetcher\Exception\UnknownOperatingSystemException; trait OperatingSystemTrait { protected function getOperatingSystem(): String { if (isset($this->options["operatingSystem"])) { return $this->options["operatingSystem"]; } $uname = strtolower(php_uname()); if (strpos($uname, "darwin") !== false) { return "osx"; } elseif (strpos($uname, "win") !== false) { return "windows"; } elseif (strpos($uname, "linux") !== false) { return "linux"; } throw new UnknownOperatingSystemException("Unknown operating system {$uname}"); } }
Clean-up: Use globally define number of spaces.
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf from .utils import SPACES class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
from __future__ import unicode_literals from lib2to3.fixer_base import BaseFix from lib2to3.pytree import Leaf SPACES = ' ' * 4 class FixTabs(BaseFix): ''' For new projects, spaces-only are strongly recommended over tabs. Most editors have features that make this easy to do. ''' def match(self, node): if node.prefix.count('\t') or (isinstance(node, Leaf) and node.value.count('\t')): return True return False def transform(self, node, results): new_prefix = node.prefix.replace('\t', SPACES) new_value = node.value.replace('\t', SPACES) if node.prefix != new_prefix or node.value != new_value: node.prefix = new_prefix node.value = new_value node.changed()
Add the ability to list services and reporters
<?php namespace ScottRobertson\Scrutiny; class Client { private $services = array(); private $reporters = array(); public function addService($service) { $this->services[] = $service; } public function addReporter($reporter) { $this->reporters[] = $reporter; } public function getServices() { return $this->services; } public function getReporters() { return $this->reporters; } public function watch($global_interval = 20) { while (true) { foreach ($this->services as $service) { if ($service->checkable()) { $this->report($service->getStatus()); } } sleep($global_interval); } } public function report(\ScottRobertson\Scrutiny\Service\Base $service) { foreach ($this->reporters as $report) { if ($report->subscribed($service->getEvent())) { $report->report($service, $this->hostname); } } } }
<?php namespace ScottRobertson\Scrutiny; class Client { private $services = array(); private $reporters = array(); public function addService($service) { $this->services[] = $service; } public function addReporter($reporter) { $this->reporters[] = $reporter; } public function watch($global_interval = 20) { while (true) { foreach ($this->services as $service) { if ($service->checkable()) { $this->report($service->getStatus()); } } sleep($global_interval); } } public function report(\ScottRobertson\Scrutiny\Service\Base $service) { foreach ($this->reporters as $report) { if ($report->subscribed($service->getEvent())) { $report->report($service, $this->hostname); } } } }
Use braces for Python sets
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type({1, 2, 3}) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == range) assert(type(set([1, 2, 3])) == set) assert(type(frozenset([1, 2, 3])) == frozenset) assert(type({'x': 1, 'y': 2}) == dict) assert(type(int) == type) assert(type(type) == type) assert(type(enumerate([])) == enumerate) assert(type(slice([])) == slice) assert(str(type(None)) == "<class 'NoneType'>") assert(str(type(NotImplemented)) == "<class 'NotImplementedType'>") assert(str(type(abs)) == "<class 'builtin_function_or_method'>")
Break out page data code into separate function
/*eslint no-console:0*/ "use strict" const express = require("express") const fs = require("fs") const utils = require(__dirname+"/src/js/Utils") const dateformat = require("dateformat") const phone = require("phone-formatter") const app = express() const template = require("jade").compileFile(__dirname + "/src/templates/main.jade") app.use(express.static(__dirname + "/static")) app.get("/", function (req, res, next) { try { fs.readFile(__dirname+"/data.json", (err,contents)=>{ sendHtmlResponse(res, prepareLocalPageData( JSON.parse(contents, utils.JSON.dateParser) )) }) } catch (e) { next(e) } }) function prepareLocalPageData (sourceData) { let locals = Object.assign( { "$utils": { dateformat: dateformat, shortDate: (date)=> dateformat.call(dateformat, date, "mmm yyyy"), dateRange: (start, end) => locals.$utils.shortDate(start)+" - "+(end?locals.$utils.shortDate(end):"Present"), phone: phone } }, sourceData ) return locals } function sendHtmlResponse (res, locals) { res.send( template(locals) ) } app.listen(process.env.PORT || 3000, function () { console.log("Listening on http://localhost:" + (process.env.PORT || 3000)) })
/*eslint no-console:0*/ "use strict" const express = require("express") const app = express() const template = require("jade").compileFile(__dirname + "/src/templates/main.jade") const fs = require("fs") const utils = require(__dirname+"/src/js/Utils") const dateformat = require("dateformat") const phone = require("phone-formatter") app.use(express.static(__dirname + "/static")) app.get("/", function (req, res, next) { try { fs.readFile(__dirname+"/data.json", (err,contents)=>{ let locals = Object.assign( { "$utils": { dateformat: dateformat, shortDate: (date)=> dateformat.call(dateformat, date, "mmm yyyy"), dateRange: (start, end) => locals.$utils.shortDate(start)+" - "+(end?locals.$utils.shortDate(end):"Present"), phone: phone } }, JSON.parse(contents, utils.JSON.dateParser) ) let html = template(locals) res.send(html) }) } catch (e) { next(e) } }) app.listen(process.env.PORT || 3000, function () { console.log("Listening on http://localhost:" + (process.env.PORT || 3000)) })
Rename "address" to more precise "host"
var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config.cli.dev'); var app = express(); var compiler = webpack(config); var port = process.env.STRIPES_PORT || 3000; var host = process.env.STRIPES_IFACE || 'localhost'; app.use(express.static(__dirname + '/public')); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(port, host, function(err) { if (err) { console.log(err); return; } console.log('Listening at http://' + host + ':' + port); });
var path = require('path'); var express = require('express'); var webpack = require('webpack'); var config = require('./webpack.config.cli.dev'); var app = express(); var compiler = webpack(config); var port = process.env.STRIPES_PORT || 3000; var address = process.env.STRIPES_IFACE || 'localhost'; app.use(express.static(__dirname + '/public')); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(require('webpack-hot-middleware')(compiler)); app.get('*', function(req, res) { res.sendFile(path.join(__dirname, 'index.html')); }); app.listen(port, address, function(err) { if (err) { console.log(err); return; } console.log('Listening at http://' + address + ':' + port); });
Fix bug: missing bold end tag
<?php namespace PhunkieConsole\IO\Colours; use const Phunkie\Functions\function1\identity; const colours = "PhunkieConsole\\IO\\Colours\\colours"; const noColours = "PhunkieConsole\\IO\\Colours\\noColours"; function colours() { $colours = [ "boldRed" => function($message) use (&$colours) { return $colours['bold']($colours['red']($message)); }, "red" => function($message) { return "\e[31m$message\e[0m"; }, "blue" => function($message) { return "\e[34m$message\e[0m"; }, "bold" => function($message) { return "\e[1m$message\e[0m"; }, "cyan" => function($message) { return "\e[36m$message\e[0m"; }, "green" => function($message) { return "\e[32m$message\e[0m"; }, "magenta" => function($message) { return "\e[35m$message\e[0m"; }, "purple" => function($message) { return "\e[38;5;57m$message\e[0m"; } ]; return $colours; } function noColours() { return [ "boldRed" => identity, "red" => identity, "blue" => identity, "bold" => identity, "cyan" => identity, "magenta" => identity, "purple" => identity ]; }
<?php namespace PhunkieConsole\IO\Colours; use const Phunkie\Functions\function1\identity; const colours = "PhunkieConsole\\IO\\Colours\\colours"; const noColours = "PhunkieConsole\\IO\\Colours\\noColours"; function colours() { $colours = [ "boldRed" => function($message) use (&$colours) { return $colours['bold']($colours['red']($message)); }, "red" => function($message) { return "\e[31m$message\e[0m"; }, "blue" => function($message) { return "\e[34m$message\e[0m"; }, "bold" => function($message) { return "\e[1m$message\e[21m"; }, "cyan" => function($message) { return "\e[36m$message\e[0m"; }, "green" => function($message) { return "\e[32m$message\e[0m"; }, "magenta" => function($message) { return "\e[35m$message\e[0m"; }, "purple" => function($message) { return "\e[38;5;57m$message\e[0m"; } ]; return $colours; } function noColours() { return [ "boldRed" => identity, "red" => identity, "blue" => identity, "bold" => identity, "cyan" => identity, "magenta" => identity, "purple" => identity ]; }
Clarify comments for columns of the ontology relations datafiles
package uk.ac.ebi.quickgo.ontology.traversal.read; /** * Enumeration representing the columns of the relationship source files. * * Columns: CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE * * Created 18/05/16 * @author Edd */ public enum Columns { COLUMN_CHILD(0, "child"), COLUMN_PARENT(1, "parent"), COLUMN_RELATIONSHIP(2,"relationship"); private int position; private String columnName; Columns(int position, String columnName) { this.position = position; this.columnName = columnName; } public int getPosition() { return position; } public String getName() { return columnName; } public static int numColumns() { return Columns.values().length; } }
package uk.ac.ebi.quickgo.ontology.traversal.read; /** * Enumeration representing the columns of the relationship source files. * * CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE * * Created 18/05/16 * @author Edd */ public enum Columns { COLUMN_CHILD(0, "child"), COLUMN_PARENT(1, "parent"), COLUMN_RELATIONSHIP(2,"relationship"); private int position; private String columnName; Columns(int position, String columnName) { this.position = position; this.columnName = columnName; } public int getPosition() { return position; } public String getName() { return columnName; } public static int numColumns() { return Columns.values().length; } }
Add Python version list trove classifiers
from setuptools import setup setup( name='skyarea', packages=['sky_area'], scripts=['bin/make_search_map', 'bin/process_areas', 'bin/run_sky_area'], version='0.1', description='Compute credible regions on the sky from RA-DEC MCMC samples', author='Will M. Farr', author_email='will.farr@ligo.org', url='http://farr.github.io/skyarea/', license='MIT', keywords='MCMC credible regions skymap LIGO', install_requires=['numpy', 'matplotlib', 'scipy', 'healpy', 'glue'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Visualization'] )
from setuptools import setup setup( name='skyarea', packages=['sky_area'], scripts=['bin/make_search_map', 'bin/process_areas', 'bin/run_sky_area'], version='0.1', description='Compute credible regions on the sky from RA-DEC MCMC samples', author='Will M. Farr', author_email='will.farr@ligo.org', url='http://farr.github.io/skyarea/', license='MIT', keywords='MCMC credible regions skymap LIGO', install_requires=['numpy', 'matplotlib', 'scipy', 'healpy', 'glue'], classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Astronomy', 'Topic :: Scientific/Engineering :: Visualization'] )
Fix paper stylesheet name in docs
import React, { PropTypes } from 'react'; import { createStyleSheet } from 'stylishly'; import Paper from 'material-ui/Paper'; const styleSheet = createStyleSheet('PaperSheet', (theme) => { return { root: theme.mixins.gutters({ paddingTop: 5, paddingBottom: 5, }), }; }); export default function PaperSheet(props, context) { const classes = context.styleManager.render(styleSheet); return ( <div> <Paper className={classes.root} zDepth={4}> <h3>This is a sheet of paper.</h3> <p> Paper can be used to build surface or other elements for your application. </p> </Paper> </div> ); } PaperSheet.contextTypes = { styleManager: PropTypes.object.isRequired, };
import React, { PropTypes } from 'react'; import { createStyleSheet } from 'stylishly'; import Paper from 'material-ui/Paper'; const styleSheet = createStyleSheet('FlatButtons', (theme) => { return { root: theme.mixins.gutters({ paddingTop: 5, paddingBottom: 5, }), }; }); export default function PaperSheet(props, context) { const classes = context.styleManager.render(styleSheet); return ( <div> <Paper className={classes.root} zDepth={4}> <h3>This is a sheet of paper.</h3> <p> Paper can be used to build surface or other elements for your application. </p> </Paper> </div> ); } PaperSheet.contextTypes = { styleManager: PropTypes.object.isRequired, };
Allow any options to be passed through test function
"""Testing support (tools to test IPython itself). """ #----------------------------------------------------------------------------- # Copyright (C) 2009-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- # User-level entry point for testing def test(**kwargs): """Run the entire IPython test suite. Any of the options for run_iptestall() may be passed as keyword arguments. """ # Do the import internally, so that this function doesn't increase total # import time from .iptestcontroller import run_iptestall, default_options options = default_options() for name, val in kwargs.items(): setattr(options, name, val) run_iptestall(options) # So nose doesn't try to run this as a test itself and we end up with an # infinite test loop test.__test__ = False
"""Testing support (tools to test IPython itself). """ #----------------------------------------------------------------------------- # Copyright (C) 2009-2011 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Functions #----------------------------------------------------------------------------- # User-level entry point for testing def test(all=False): """Run the entire IPython test suite. For fine-grained control, you should use the :file:`iptest` script supplied with the IPython installation.""" # Do the import internally, so that this function doesn't increase total # import time from .iptestcontroller import run_iptestall, default_options options = default_options() options.all = all run_iptestall(options) # So nose doesn't try to run this as a test itself and we end up with an # infinite test loop test.__test__ = False
Fix the icons of menu.
<?php namespace app\components; use app\models\Subscription; use Yii; /** * Description of FavMenuHelper * * @author charles */ class FavMenuHelper { public static function getFavMenuItems() { $result = [ [ 'label' => '我的收藏', 'icon' => 'star', 'url' => ['/subscription/list'], 'items' => [], ], ]; $subscriptions = Subscription::findAll(['user_id' => Yii::$app->user->id]); foreach ($subscriptions as $s) { $result[0]['items'][] = [ 'label' => $s->report->name, 'icon' => 'circle', 'url' => ['/report/view', 'id' => $s->report_id], ]; } return $result; } }
<?php namespace app\components; use app\models\Subscription; use Yii; /** * Description of FavMenuHelper * * @author charles */ class FavMenuHelper { public static function getFavMenuItems() { $result = [ [ 'label' => '我的收藏', 'icon' => 'fa fa-star', 'url' => ['/subscription/list'], 'items' => [], ], ]; $subscriptions = Subscription::findAll(['user_id' => Yii::$app->user->id]); foreach ($subscriptions as $s) { $result[0]['items'][] = [ 'label' => $s->report->name, 'icon' => 'fa fa-circle', 'url' => ['/report/view', 'id' => $s->report_id], ]; } return $result; } }
Remove unused form class variable.
<?php namespace Backend\Modules\Analytics\Actions; use Backend\Core\Engine\Base\ActionDelete; use Backend\Core\Engine\Model; /** * This is the reset-action. It will remove your coupling with analytics * * @author Wouter Sioen <wouter@sumocoders.be> */ final class Reset extends ActionDelete { public function execute() { $this->get('fork.settings')->delete($this->getModule(), 'certificate'); $this->get('fork.settings')->delete($this->getModule(), 'email'); $this->get('fork.settings')->delete($this->getModule(), 'account'); $this->get('fork.settings')->delete($this->getModule(), 'web_property_id'); $this->get('fork.settings')->delete($this->getModule(), 'profile'); return $this->redirect(Model::createURLForAction('Settings')); } }
<?php namespace Backend\Modules\Analytics\Actions; use Backend\Core\Engine\Base\ActionDelete; use Backend\Core\Engine\Model; /** * This is the reset-action. It will remove your coupling with analytics * * @author Wouter Sioen <wouter@sumocoders.be> */ final class Reset extends ActionDelete { /** * The form instance * * @var Form */ private $form; public function execute() { $this->get('fork.settings')->delete($this->getModule(), 'certificate'); $this->get('fork.settings')->delete($this->getModule(), 'email'); $this->get('fork.settings')->delete($this->getModule(), 'account'); $this->get('fork.settings')->delete($this->getModule(), 'web_property_id'); $this->get('fork.settings')->delete($this->getModule(), 'profile'); return $this->redirect(Model::createURLForAction('Settings')); } }
Add the metadata mock on the model validation.
/*global describe, it*/ require('../initialize-globals').load(); var Model = require('../../app/models/model').extend({ validation: { firstName: { required: true } } }); var ModelValidator = require('../../app/lib/model-validation-promise'); var model = new Model({ firstName: "Pierre", lastName: "Besson" }); describe('#model-validation-promise', function() { describe('##validation on metadatas', function() { it('should validate the metadatas'); }); describe('##validation on model', function() { it('The validation shoul be ok', function(done) { ModelValidator.validate(model).then(function(modelSuccess) { modelSuccess.toJSON().should.have.property('firstName', 'Pierre'); done(); }); }); it('The validation shoul be ko', function(done) { model.unset('firstName', { silent: true }); ModelValidator.validate(model). catch (function(error) { error.should.have.property('firstName', 'firstName not valid.'); done(); }); }); }); });
/*global describe, it*/ require('../initialize-globals').load(); var Model = require('../../app/models/model').extend({ validation: { firstName: {required: true} } }); var ModelValidator = require('../../app/lib/model-validation-promise'); describe('default model', function() { var model = new Model({ firstName: "Pierre", lastName: "Besson" }); describe('#validate', function() { it('The validation shoul be ok', function(done) { ModelValidator.validate(model).then(function(modelSuccess) { modelSuccess.toJSON().should.have.property('firstName', 'Pierre'); done(); }); }); it('The validation shoul be ko', function(done) { model.unset('firstName', {silent: true}); ModelValidator.validate(model).catch(function(error) { error.should.have.property('firstName', 'firstName not valid.'); done(); }); }); }); });
Change content type check to check for 'application/json' not 'json'
var Promise = require("bluebird"); module.exports = (response, body) => { var outResponse = { statusCode: response.statusCode, headers: response.headers, body: body }; if (response.statusCode != 200) { var errorResponse = outResponse; if (/\bapplication\/json\b/.test(response.headers['content-type'])) { var responseBody = JSON.parse(body); errorResponse.errorCode = responseBody.errorCode; errorResponse.message = responseBody.message; errorResponse.refId = responseBody.refId; if (responseBody.detail !== undefined) { errorResponse.detail = responseBody.detail; } } else { errorResponse.message = body; } return new Promise.reject(errorResponse); } else if (response.headers['content-type'] === 'application/json;charset=UTF-8') { outResponse.content = JSON.parse(body); return outResponse; } else { outResponse.content = body; return outResponse; } };
var Promise = require("bluebird"); module.exports = (response, body) => { var outResponse = { statusCode: response.statusCode, headers: response.headers, body: body }; if (response.statusCode != 200) { var errorResponse = outResponse; if (/\bjson\b/.test(response.headers['content-type'])) { var responseBody = JSON.parse(body); errorResponse.errorCode = responseBody.errorCode; errorResponse.message = responseBody.message; errorResponse.refId = responseBody.refId; if (responseBody.detail !== undefined) { errorResponse.detail = responseBody.detail; } } else { errorResponse.message = body; } return new Promise.reject(errorResponse); } else if (response.headers['content-type'] === 'application/json;charset=UTF-8') { outResponse.content = JSON.parse(body); return outResponse; } else { outResponse.content = body; return outResponse; } };
Remove "// Just for the lulz" as we are not sending to NSA TAO
<?php require "Mail.php"; require "Mail_Mime.php"; require "Crypt/GPG.php"; define('BASE', dirname(__DIR__)); require BASE.'/config.php'; if (isset($_POST['from']) && isset($_POST['message'])) { $gpg = new Crypt_GPG([ 'homedir' => BASE ]); $fingerprint = $gpg->getFingerprint( OUR_EMAIL_ADDRESS ); $ciphertext = $gpg->encrypt( "From: {$_POST['from']}\n\nMessage:\n{$_POST['message']}", $fingerprint ); $email = Mail::factory('mail'); $email->send( [OUR_EMAIL_ADDRESS], ['From' => 'Contact Form <contact@anonymo.us>'], $ciphertext ); header("Location: contact_form.php?msg=success"); exit; } header("Location: contact_form.php"); exit;
<?php require "Mail.php"; require "Mail_Mime.php"; require "Crypt/GPG.php"; define('BASE', dirname(__DIR__)); require BASE.'/config.php'; if (isset($_POST['from']) && isset($_POST['message'])) { $gpg = new Crypt_GPG([ 'homedir' => BASE ]); $fingerprint = $gpg->getFingerprint( OUR_EMAIL_ADDRESS ); $ciphertext = $gpg->encrypt( "From: {$_POST['from']}\n\nMessage:\n{$_POST['message']}", $fingerprint ); $email = Mail::factory('mail'); $email->send( [OUR_EMAIL_ADDRESS], // Just for the lulz ['From' => 'Contact Form <contact@anonymo.us>'], $ciphertext ); header("Location: contact_form.php?msg=success"); exit; } header("Location: contact_form.php"); exit;
Remove underscore from random generation to prevent issues with URI parsing.
package foundation.stack.datamill.cucumber; import java.security.SecureRandom; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class RandomGenerator { private static final SecureRandom random = new SecureRandom(); private static final char[] CHARACTERS = new char[]{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; private RandomGenerator() { } public static String generateRandomAlphanumeric(int length) { StringBuilder name = new StringBuilder("n"); for (int i = 0; i < length - 2; i++) { name.append(CHARACTERS[random.nextInt(36)]); } name.append('z'); return name.toString(); } }
package foundation.stack.datamill.cucumber; import java.security.SecureRandom; /** * @author Ravi Chodavarapu (rchodava@gmail.com) */ public class RandomGenerator { private static final SecureRandom random = new SecureRandom(); private static final char[] CHARACTERS = new char[]{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_'}; private RandomGenerator() { } public static String generateRandomAlphanumeric(int length) { StringBuilder name = new StringBuilder("n"); for (int i = 0; i < length - 2; i++) { name.append(CHARACTERS[random.nextInt(37)]); } name.append('z'); return name.toString(); } }
Make tether-to-selection use fixed positioning relative to selection Changes `{{tether-to-selection}}` to: * use "position: fixed". Avoids issues when the editor is in an absolutely-positioned div * (bugfix) Do not position relative to ".mobiledoc-editor". This was error-prone when there was more than one editor on the page, and also unnecessary. * Add 'mobiledoc-selection-tether' class (escape hatch for styling by consumers) * (bugfix) Read the window's selection metrics before element insertion. When the yielded link-prompt component focuses its input field, that changes the window selection. Reading before insertion fixes this problem.
import Ember from 'ember'; import layout from './template'; let { Component } = Ember; const LEFT_PADDING = 0; const TOP_PADDING = 10; export default Component.extend({ layout, classNames: ['mobiledoc-selection-tether'], left: 0, top: 0, willInsertElement() { let selection = window.getSelection(); let range = selection && selection.rangeCount && selection.getRangeAt(0); Ember.assert('Should not render {{#tether-to-selection}} when there is no selection', !!range); if (range) { let rect = range.getBoundingClientRect(); this.set('left', rect.left); this.set('top', rect.top); } }, didInsertElement() { Ember.run.schedule('afterRender', () => { let myHeight = this.$().height(); let left = this.get('left') - LEFT_PADDING; let top = this.get('top') - TOP_PADDING - myHeight; this.$().css({ position: 'fixed', left: `${left}px`, top: `${top}px` }); }); } });
import jQuery from 'jquery'; import Ember from 'ember'; import layout from './template'; let { Component } = Ember; export default Component.extend({ layout, didInsertElement() { Ember.run.schedule('afterRender', () => { var selection = window.getSelection(); var range = selection && selection.rangeCount && selection.getRangeAt(0); if (range) { var rect = range.getBoundingClientRect(); let wrapperOffset = jQuery('.mobiledoc-editor').offset(); let myHeight = this.$().height(); this.$().css({ position: 'absolute', left: `${rect.left - wrapperOffset.left}px`, top: `${rect.top - wrapperOffset.top - myHeight - 10}px` }); } }); } });
Remove use of spread operator This is a temporary fix for the fact that the babel plugin for the spread operator calls a function called `_iterableToArray` which assumes the JavaScript runtime supports Symbols. IE11 doesn't support Symbols so this causes an error when it runs our JS. This swaps out use of the spread operator for a use of [apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply) to unpack the `arguments` object. Related issue on babel: https://github.com/babel/babel/issues/7597
(function(Modules) { "use strict"; var queues = {}; var dd = new diffDOM(); var getRenderer = $component => response => dd.apply( $component.get(0), dd.diff($component.get(0), $(response[$component.data('key')]).get(0)) ); var getQueue = resource => ( queues[resource] = queues[resource] || [] ); var flushQueue = function(queue, response) { while(queue.length) queue.shift()(response); }; var clearQueue = queue => (queue.length = 0); var poll = function(renderer, resource, queue, interval, form) { if (document.visibilityState !== "hidden" && queue.push(renderer) === 1) $.ajax( resource, { 'method': form ? 'post' : 'get', 'data': form ? $('#' + form).serialize() : {} } ).done( response => flushQueue(queue, response) ).fail( () => poll = function(){} ); setTimeout( () => poll.apply(window, arguments), interval ); }; Modules.UpdateContent = function() { this.start = component => poll( getRenderer($(component)), $(component).data('resource'), getQueue($(component).data('resource')), ($(component).data('interval-seconds') || 1.5) * 1000, $(component).data('form') ); }; })(window.GOVUK.Modules);
(function(Modules) { "use strict"; var queues = {}; var dd = new diffDOM(); var getRenderer = $component => response => dd.apply( $component.get(0), dd.diff($component.get(0), $(response[$component.data('key')]).get(0)) ); var getQueue = resource => ( queues[resource] = queues[resource] || [] ); var flushQueue = function(queue, response) { while(queue.length) queue.shift()(response); }; var clearQueue = queue => (queue.length = 0); var poll = function(renderer, resource, queue, interval, form) { if (document.visibilityState !== "hidden" && queue.push(renderer) === 1) $.ajax( resource, { 'method': form ? 'post' : 'get', 'data': form ? $('#' + form).serialize() : {} } ).done( response => flushQueue(queue, response) ).fail( () => poll = function(){} ); setTimeout( () => poll(...arguments), interval ); }; Modules.UpdateContent = function() { this.start = component => poll( getRenderer($(component)), $(component).data('resource'), getQueue($(component).data('resource')), ($(component).data('interval-seconds') || 1.5) * 1000, $(component).data('form') ); }; })(window.GOVUK.Modules);
Use c-version of the selective compilation
import _psyco _psyco.selective(1) # Argument is number of invocations before rebinding # import sys # ticks = 0 # depth = 10 # funcs = {} # def f(frame, event, arg): # if event != 'call': return # print type(frame.f_globals) # c = frame.f_code.co_code # fn = frame.f_code.co_name # g = frame.f_globals # if not funcs.has_key(c): # funcs[c] = 1 # if funcs[c] != None: # funcs[c] = funcs[c] + 1 # if funcs[c] > ticks and g.has_key(fn): # g[fn] = _psyco.proxy(g[fn], depth) # funcs[c] = None # print 'psyco rebinding function:', fn # sys.setprofile(f)
import _psyco import sys ticks = 0 depth = 10 funcs = {} def f(frame, event, arg): if event != 'call': return c = frame.f_code.co_code fn = frame.f_code.co_name g = frame.f_globals if not funcs.has_key(c): funcs[c] = 1 if funcs[c] != None: funcs[c] = funcs[c] + 1 if funcs[c] > ticks and g.has_key(fn): g[fn] = _psyco.proxy(g[fn], depth) funcs[c] = None print 'psyco rebinding function:', fn sys.setprofile(f)
Fix dependency to remove std print isr button
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - ISR inpayment slip (PVR/BVR/ESR)', 'summary': 'Print inpayment slip from your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com', 'license': 'AGPL-3', 'depends': [ 'account', 'account_invoicing', 'l10n_ch_base_bank', 'base_transaction_id', # OCA/account-reconcile 'web', 'l10n_ch', ], 'data': [ "views/report_xml_templates.xml", "views/bank.xml", "views/account_invoice.xml", "views/res_config_settings_views.xml", "wizard/isr_batch_print.xml", "report/report_declaration.xml", "security/ir.model.access.csv" ], 'demo': [], 'auto_install': False, 'installable': True, 'images': [], 'external_dependencies': { 'python': [ 'PyPDF2', ] } }
# Copyright 2012-2016 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). {'name': 'Switzerland - ISR inpayment slip (PVR/BVR/ESR)', 'summary': 'Print inpayment slip from your invoices', 'version': '10.0.1.1.1', 'author': "Camptocamp,Odoo Community Association (OCA)", 'category': 'Localization', 'website': 'http://www.camptocamp.com', 'license': 'AGPL-3', 'depends': [ 'account', 'account_invoicing', 'l10n_ch_base_bank', 'base_transaction_id', # OCA/bank-statement-reconcile 'web', ], 'data': [ "views/report_xml_templates.xml", "views/bank.xml", "views/account_invoice.xml", "views/res_config_settings_views.xml", "wizard/isr_batch_print.xml", "report/report_declaration.xml", "security/ir.model.access.csv" ], 'demo': [], 'auto_install': False, 'installable': True, 'images': [], 'external_dependencies': { 'python': [ 'PyPDF2', ] } }
Fix min_range option to stop numberofcpucores.php returning 0 The minimum options for filter_var() with FILTER_VALIDATE_INT should me min_range.
<?php $intOpts = array( 'options' => array( 'min_range' => 1, ), ); // get value via /proc/cpuinfo $numOfCores = shell_exec('/bin/grep -c ^processor /proc/cpuinfo'); $numOfCores = filter_var( $numOfCores[0], FILTER_VALIDATE_INT, $intOpts ); // If number of cores is not found, run fallback if ($numOfCores === false) { $numOfCores = filter_var( shell_exec('/usr/bin/nproc'), FILTER_VALIDATE_INT, $intOpts ); } if ($numOfCores === false) { $numOfCores = 'unknown'; } header('Content-Type: application/json; charset=UTF-8'); echo json_encode($numOfCores);
<?php $intOpts = array( 'options' => array( 'min' => 1, ), ); // get value via /proc/cpuinfo $numOfCores = shell_exec('/bin/grep -c ^processor /proc/cpuinfo'); $numOfCores = filter_var( $numOfCores[0], FILTER_VALIDATE_INT, $intOpts ); // If number of cores is not found, run fallback if ($numOfCores === false) { $numOfCores = filter_var( shell_exec('/usr/bin/nproc'), FILTER_VALIDATE_INT, $intOpts ); } if ($numOfCores === false) { $numOfCores = 'unknown'; } header('Content-Type: application/json; charset=UTF-8'); echo json_encode($numOfCores);
Update outdated design Target docstring
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min", or a scalar value (such as "5.0")) """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0") :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
from citrination_client.base.errors import CitrinationClientError class Target(object): """ The optimization target for a design run. Consists of the name of the output column to optimize and the objective (either "Max" or "Min") """ def __init__(self, name, objective): """ Constructor. :param name: The name of the target output column :type name: str :param objective: The optimization objective; "Min", "Max", or a scalar value (such as "5.0") :type objective: str """ try: self._objective = float(objective) except ValueError: if objective.lower() not in ["max", "min"]: raise CitrinationClientError( "Target objective must either be \"min\" or \"max\"" ) self._objective = objective self._name = name def to_dict(self): return { "descriptor": self._name, "objective": self._objective }
Add targetURL when printing error during Pipelines().
package api import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) const ( apiPrefix = "/api/v1" ) //go:generate counterfeiter . Client type Client interface { Pipelines() ([]Pipeline, error) } type client struct { target string } func NewClient(target string) Client { return &client{ target: target, } } func (c client) Pipelines() ([]Pipeline, error) { targetUrl := fmt.Sprintf( "%s%s/pipelines", c.target, apiPrefix, ) resp, err := http.Get(targetUrl) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unexpected response from %s - status code: %d, expected: %d", targetUrl, resp.StatusCode, http.StatusOK, ) } b, err := ioutil.ReadAll(resp.Body) if err != nil { // Untested as it is too hard to force ReadAll to return an error return nil, err } var pipelines []Pipeline err = json.Unmarshal(b, &pipelines) if err != nil { return nil, err } return pipelines, nil }
package api import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) const ( apiPrefix = "/api/v1" ) //go:generate counterfeiter . Client type Client interface { Pipelines() ([]Pipeline, error) } type client struct { target string } func NewClient(target string) Client { return &client{ target: target, } } func (c client) Pipelines() ([]Pipeline, error) { targetUrl := fmt.Sprintf( "%s%s/pipelines", c.target, apiPrefix, ) resp, err := http.Get(targetUrl) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("Unexpected response from - status code: %d, expected: %d", targetUrl, resp.StatusCode, http.StatusOK, ) } b, err := ioutil.ReadAll(resp.Body) if err != nil { // Untested as it is too hard to force ReadAll to return an error return nil, err } var pipelines []Pipeline err = json.Unmarshal(b, &pipelines) if err != nil { return nil, err } return pipelines, nil }
Update PropType description and change to a better name
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import WidgetBody from './WidgetBody'; import WidgetFooter from './WidgetFooter'; import WidgetHeader from './WidgetHeader'; import cx from 'classnames'; import theme from './theme.css'; const PADDINGS = { small: 3, medium: 4, large: 5, }; class Widget extends PureComponent { render() { const { children, size, ...others } = this.props; return ( <Box className={cx(theme['widget'])} {...others}> {React.Children.map(children, child => { return React.cloneElement(child, { padding: PADDINGS[size], ...child.props, }); })} </Box> ); } } Widget.propTypes = { /** The content to display inside the widget. */ children: PropTypes.node, /** The size wich controls the paddings passed down to our children. */ size: PropTypes.oneOf(Object.keys(PADDINGS)), }; Widget.defaultProps = { size: 'medium', }; Widget.WidgetBody = WidgetBody; Widget.WidgetFooter = WidgetFooter; Widget.WidgetHeader = WidgetHeader; export default Widget;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import Box from '../box'; import WidgetBody from './WidgetBody'; import WidgetFooter from './WidgetFooter'; import WidgetHeader from './WidgetHeader'; import cx from 'classnames'; import theme from './theme.css'; const SIZES = { small: 3, medium: 4, large: 5, }; class Widget extends PureComponent { render() { const { children, size, ...others } = this.props; return ( <Box className={cx(theme['widget'])} {...others}> {React.Children.map(children, child => { return React.cloneElement(child, { padding: SIZES[size], ...child.props, }); })} </Box> ); } } Widget.propTypes = { /** The content to display inside the widget. */ children: PropTypes.node, size: PropTypes.oneOf(Object.keys(SIZES)), }; Widget.defaultProps = { size: 'medium', }; Widget.WidgetBody = WidgetBody; Widget.WidgetFooter = WidgetFooter; Widget.WidgetHeader = WidgetHeader; export default Widget;
Fix echarts overflow on Android
import React, { Component } from 'react'; import { WebView, View, StyleSheet, Platform } from 'react-native'; import renderChart from './renderChart'; import echarts from './echarts.min'; export default class App extends Component { componentWillReceiveProps(nextProps) { if(nextProps.option !== this.props.option) { this.refs.chart.reload(); } } render() { return ( <View style={{flex: 1, height: this.props.height || 400,}}> <WebView ref="chart" scrollEnabled = {false} injectedJavaScript = {renderChart(this.props)} style={{ height: this.props.height || 400, backgroundColor: this.props.backgroundColor || 'transparent' }} scalesPageToFit={Platform.OS !== 'ios'} source={require('./tpl.html')} onMessage={event => this.props.onPress ? this.props.onPress(JSON.parse(event.nativeEvent.data)) : null} /> </View> ); } }
import React, { Component } from 'react'; import { WebView, View, StyleSheet } from 'react-native'; import renderChart from './renderChart'; import echarts from './echarts.min'; export default class App extends Component { componentWillReceiveProps(nextProps) { if(nextProps.option !== this.props.option) { this.refs.chart.reload(); } } render() { return ( <View style={{flex: 1, height: this.props.height || 400,}}> <WebView ref="chart" scrollEnabled = {false} injectedJavaScript = {renderChart(this.props)} style={{ height: this.props.height || 400, backgroundColor: this.props.backgroundColor || 'transparent' }} scalesPageToFit={true} source={require('./tpl.html')} onMessage={event => this.props.onPress ? this.props.onPress(JSON.parse(event.nativeEvent.data)) : null} /> </View> ); } }
Fix weird terminal output format Signed-off-by: Lei Jitang <9ac444d2b5df3db1f31aa1c6462ac8e9e2bde241@huawei.com>
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) newState.Oflag = newState.Oflag | C.OPOST if err := tcset(fd, &newState); err != 0 { return nil, err } return &oldState, nil } func tcget(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } func tcset(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 }
// +build linux,cgo package term import ( "syscall" "unsafe" ) // #include <termios.h> import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) if err := tcset(fd, &newState); err != 0 { return nil, err } return &oldState, nil } func tcget(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } func tcset(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 }
Add "bc" alias to /broadcast
package in.twizmwaz.cardinal.command; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandPermissions; import in.twizmwaz.cardinal.chat.ChatConstant; import in.twizmwaz.cardinal.chat.LocalizedChatMessage; import in.twizmwaz.cardinal.util.ChatUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; public class BroadcastCommands { @Command(aliases = {"say"}, desc = "Sends a message from the console.", min = 1) @CommandPermissions("cardinal.say") public static void say(final CommandContext cmd, CommandSender sender) throws CommandException { ChatUtils.getGlobalChannel().sendMessage(ChatColor.WHITE + "<" + ChatColor.GOLD + "\u2756" + ChatColor.DARK_AQUA + "Console" + ChatColor.WHITE + "> " + cmd.getJoinedStrings(0)); } @Command(aliases = {"broadcast", "bc"}, desc = "Broadcasts a message to all players.", min = 1) @CommandPermissions("cardinal.broadcast") public static void broadcast(final CommandContext cmd, CommandSender sender) throws CommandException { ChatUtils.getGlobalChannel().sendMessage(ChatColor.RED + "[Broadcast] " + cmd.getJoinedStrings(0)); } }
package in.twizmwaz.cardinal.command; import com.sk89q.minecraft.util.commands.Command; import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandException; import com.sk89q.minecraft.util.commands.CommandPermissions; import in.twizmwaz.cardinal.chat.ChatConstant; import in.twizmwaz.cardinal.chat.LocalizedChatMessage; import in.twizmwaz.cardinal.util.ChatUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; public class BroadcastCommands { @Command(aliases = {"say"}, desc = "Sends a message from the console.", min = 1) @CommandPermissions("cardinal.say") public static void say(final CommandContext cmd, CommandSender sender) throws CommandException { ChatUtils.getGlobalChannel().sendMessage(ChatColor.WHITE + "<" + ChatColor.GOLD + "\u2756" + ChatColor.DARK_AQUA + "Console" + ChatColor.WHITE + "> " + cmd.getJoinedStrings(0)); } @Command(aliases = {"broadcast"}, desc = "Broadcasts a message to all players.", min = 1) @CommandPermissions("cardinal.broadcast") public static void broadcast(final CommandContext cmd, CommandSender sender) throws CommandException { ChatUtils.getGlobalChannel().sendMessage(ChatColor.RED + "[Broadcast] " + cmd.getJoinedStrings(0)); } }
Add player inventory and basic fluid slots
package info.u_team.u_team_test.container; import info.u_team.u_team_core.container.UTileEntityContainer; import info.u_team.u_team_test.init.TestContainers; import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.network.PacketBuffer; public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> { // Client public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) { super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer); } // Server public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) { super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity); } @Override protected void init(boolean server) { appendInventory(tileEntity.getItemSlots(), 2, 9, 8, 41); appendPlayerInventory(playerInventory, 8, 91); } }
package info.u_team.u_team_test.container; import info.u_team.u_team_core.container.UTileEntityContainer; import info.u_team.u_team_test.init.TestContainers; import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.network.PacketBuffer; public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> { // Client public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) { super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer); } // Server public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) { super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity); } @Override protected void init(boolean server) { } }
ADD show env-value on build
const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const commonConfig = require('./webpack.config.common.js'); const AppCachePlugin = require('appcache-webpack-plugin'); const doUglify = true; module.exports = function(options) { const ENV = options.ENV || 'production'; console.log('ENV: ' + ENV); const plugins = []; plugins.push(new webpack.DefinePlugin({ 'ENV': JSON.stringify(ENV) })); plugins.push(new webpack.NoEmitOnErrorsPlugin()); plugins.push(new AppCachePlugin({ exclude: ['app.js', 'styles.css'], output: 'app.appcache' })); return webpackMerge(commonConfig, { plugins, optimization: { minimize: doUglify }, mode: ENV }); };
const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const commonConfig = require('./webpack.config.common.js'); const AppCachePlugin = require('appcache-webpack-plugin'); const doUglify = true; module.exports = function(options) { const ENV = options.ENV || 'production'; const plugins = []; plugins.push(new webpack.DefinePlugin({ 'ENV': JSON.stringify(ENV) })); plugins.push(new webpack.NoEmitOnErrorsPlugin()); plugins.push(new AppCachePlugin({ exclude: ['app.js', 'styles.css'], output: 'app.appcache' })); return webpackMerge(commonConfig, { plugins, optimization: { minimize: doUglify }, mode: ENV }); };
Use variable existence instead of length
"use strict" $(document).ready(function() { $('div.input-group.tempus-dominus-date').each(function() { var date_picker = $(this); var options = { format: 'DD/MM/YYYY', allowInputToggle: true, }; var maxDate = date_picker.children('input').data('maxDate'); if (maxDate) { options.maxDate = moment(new Date(maxDate)); } $(this).datetimepicker(options); }); $('div.input-group.tempus-dominus-date-time').each(function() { var date_picker = $(this); var maxDateTime = date_picker.children('input').data('maxDateTime'); var options = { format: 'DD/MM/YYYY HH:mm', allowInputToggle: true, sideBySide: true } if (maxDateTime.length) { options.maxDate = moment(new Date(maxDateTime)); } date_picker.datetimepicker(options); }); });
"use strict" $(document).ready(function() { $('div.input-group.tempus-dominus-date').each(function() { var date_picker = $(this); var options = { format: 'DD/MM/YYYY', allowInputToggle: true, }; var maxDate = date_picker.children('input').data('maxDate'); if (maxDate.length) { options.maxDate = moment(new Date(maxDate)); } $(this).datetimepicker(options); }); $('div.input-group.tempus-dominus-date-time').each(function() { var date_picker = $(this); var maxDateTime = date_picker.children('input').data('maxDateTime'); var options = { format: 'DD/MM/YYYY HH:mm', allowInputToggle: true, sideBySide: true } if (maxDateTime.length) { options.maxDate = moment(new Date(maxDateTime)); } date_picker.datetimepicker(options); }); });
Remove old docstring with link to old django docs
# flake8: noqa # newrelic.agent must be imported and initialized first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration import newrelic.agent newrelic.agent.initialize('newrelic.ini') import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from decouple import config IS_HTTPS = config('HTTPS', default='off', cast=bool) class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest if config('SENTRY_DSN', None): from raven.contrib.django.raven_compat.middleware.wsgi import Sentry application = Sentry(application) newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None) if newrelic_license_key: application = newrelic.agent.WSGIApplicationWrapper(application)
# flake8: noqa """ WSGI config for nucleus project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ # newrelic.agent must be imported and initialized first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration import newrelic.agent newrelic.agent.initialize('newrelic.ini') import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from decouple import config IS_HTTPS = config('HTTPS', default='off', cast=bool) class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest if config('SENTRY_DSN', None): from raven.contrib.django.raven_compat.middleware.wsgi import Sentry application = Sentry(application) newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None) if newrelic_license_key: application = newrelic.agent.WSGIApplicationWrapper(application)
Remove upper bound for packages oedialect requires sqlalchemy >= 1.2.0 which would make it incompatible with ego.io for no reason
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='ulf.p.mueller@hs-flensburg.de', description='ego input/output repository', version='0.4.5', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.1', 'sqlalchemy >= 1.2.0', 'keyring >= 4.0', 'keyrings.alt', 'psycopg2'], extras_require={ "sqlalchemy": 'postgresql'}, package_data={'tools': 'sqlacodegen_oedb.sh'} )
#! /usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup(name='egoio', author='NEXT ENERGY, Reiner Lemoine Institut gGmbH, ZNES', author_email='ulf.p.mueller@hs-flensburg.de', description='ego input/output repository', version='0.4.5', url='https://github.com/openego/ego.io', packages=find_packages(), license='GNU Affero General Public License v3.0', install_requires=[ 'geoalchemy2 >= 0.3.0, <= 0.4.1', 'sqlalchemy >= 1.0.11, <= 1.2.0', 'keyring >= 4.0', 'keyrings.alt', 'psycopg2'], extras_require={ "sqlalchemy": 'postgresql'}, package_data={'tools': 'sqlacodegen_oedb.sh'} )
[saturn] Increase time for gamma spectrum command
<?php namespace App\Sharp\Commands; use Code16\Sharp\EntityList\Commands\EntityCommand; use Code16\Sharp\EntityList\EntityListQueryParams; class SpaceshipSynchronize extends EntityCommand { /** * @return string */ public function label(): string { return "Synchronize the gamma-spectrum"; } /** * @param EntityListQueryParams $params * @param array $data * @return array */ public function execute(EntityListQueryParams $params, array $data=[]): array { sleep(2); return $this->info("Gamma spectrum synchronized!"); } public function confirmationText() { return "Sure, really?"; } public function authorize():bool { return sharp_user()->hasGroup("boss"); } }
<?php namespace App\Sharp\Commands; use Code16\Sharp\EntityList\Commands\EntityCommand; use Code16\Sharp\EntityList\EntityListQueryParams; class SpaceshipSynchronize extends EntityCommand { /** * @return string */ public function label(): string { return "Synchronize the gamma-spectrum"; } /** * @param EntityListQueryParams $params * @param array $data * @return array */ public function execute(EntityListQueryParams $params, array $data=[]): array { return $this->info("Gamma spectrum synchronized!"); } public function confirmationText() { return "Sure, really?"; } public function authorize():bool { return sharp_user()->hasGroup("boss"); } }
Add references to node and express typings grabbed with grab-typings (thanks bengreenier!)
/// <reference path="typings/node/node.d.ts" /> /// <reference path="typings/express/express.d.ts" /> var express = require('express'); var app = express(); var colors = [ "red", "yellow", "green" ]; var data = { color: colors[0], delay: 200 }; var chooseColor = function() { // Don't show the same color twice to make it obvious that something // is changing var filteredColors = colors.filter(function(x) { return x !== data.color; }); data.color = filteredColors[Math.floor(Math.random() * filteredColors.length)]; data.delay = Math.floor(Math.random() * 1900 + 100); console.log(data); }; setInterval(chooseColor, 10000); app.get('/', function(req, res) { res.json(data); }); var server = app.listen(3000, function() { console.log('Up and running at http://%s:%s', server.address().address, server.address().port); });
var express = require('express'); var app = express(); var colors = [ "red", "yellow", "green" ]; var data = { color: colors[0], delay: 200 }; var chooseColor = function() { // Don't show the same color twice to make it obvious that something // is changing var filteredColors = colors.filter(function(x) { return x !== data.color; }); data.color = filteredColors[Math.floor(Math.random() * filteredColors.length)]; data.delay = Math.floor(Math.random() * 1900 + 100); console.log(data); }; setInterval(chooseColor, 10000); app.get('/', function(req, res) { res.json(data); }); var server = app.listen(3000, function() { console.log('Up and running at http://%s:%s', server.address().address, server.address().port); });
Remove extra space from if statement
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if(typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if( typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
Increase entity size config limit. Default is too small. VAN API can return larger responses than will fit, which causes a 413 to OSDI clients even though the VAN api call was fine. Increased limit.
/*jslint nodejs: true*/ var express = require('express'), iefix = require('express-ie-cors'), bodyParser = require('body-parser'), cors = require('cors'), routes = require('./routes'), config = require('./config'), notSupported = require('./middleware/notSupported'), contentType = require('./middleware/contentType'), halParser = require('./middleware/halParser'), requireHttps = require('./middleware/requireHttps'), app = module.exports = express(); app.use(iefix({ contentType: 'application/x-www-form-urlencoded' })); app.use(bodyParser.text({ 'type': 'application/hal+json', 'limit' : '50mb' })); app.use(halParser); app.use(requireHttps); app.use(cors()); app.use(contentType); var key; for (key in routes) { if (routes.hasOwnProperty(key)) { routes[key](app); } } app.all('/api/v1/*', function (req, res) { return notSupported.send(req, res); }); app.all('/*', function (req, res) { res.sendStatus(404); }); if (!module.parent) { var port = config.get('port'); app.listen(port, function() { console.log('Listening on %d.', port); }); }
/*jslint nodejs: true*/ var express = require('express'), iefix = require('express-ie-cors'), bodyParser = require('body-parser'), cors = require('cors'), routes = require('./routes'), config = require('./config'), notSupported = require('./middleware/notSupported'), contentType = require('./middleware/contentType'), halParser = require('./middleware/halParser'), requireHttps = require('./middleware/requireHttps'), app = module.exports = express(); app.use(iefix({ contentType: 'application/x-www-form-urlencoded' })); app.use(bodyParser.text({ 'type': 'application/hal+json' })); app.use(halParser); app.use(requireHttps); app.use(cors()); app.use(contentType); var key; for (key in routes) { if (routes.hasOwnProperty(key)) { routes[key](app); } } app.all('/api/v1/*', function (req, res) { return notSupported.send(req, res); }); app.all('/*', function (req, res) { res.sendStatus(404); }); if (!module.parent) { var port = config.get('port'); app.listen(port, function() { console.log('Listening on %d.', port); }); }
[vigir_synthesis_manager] Remove prints from LTL compilation client
#!/usr/bin/env python import rospy from vigir_synthesis_msgs.srv import LTLCompilation # from vigir_synthesis_msgs.msg import LTLSpecification, BSErrorCodes def ltl_compilation_client(system, goals, initial_conditions, custom_ltl = None): '''Client''' rospy.wait_for_service('ltl_compilation') try: ltl_compilation_srv = rospy.ServiceProxy('ltl_compilation', LTLCompilation) response = ltl_compilation_srv(system, goals, initial_conditions) #DEBUG # print response.ltl_specification print 'LTL Compilation error code: ', response.error_code return response except rospy.ServiceException as e: print("Service call failed: %s" % e) if __name__ == "__main__": ltl_compilation_client('atlas', ['pickup'], ['stand'])
#!/usr/bin/env python import rospy from vigir_synthesis_msgs.srv import LTLCompilation # from vigir_synthesis_msgs.msg import LTLSpecification, BSErrorCodes def ltl_compilation_client(system, goals, initial_conditions, custom_ltl = None): '''Client''' rospy.wait_for_service('ltl_compilation') try: ltl_compilation_srv = rospy.ServiceProxy('ltl_compilation', LTLCompilation) response = ltl_compilation_srv(system, goals, initial_conditions) #DEBUG print response.ltl_specification.sys_init print response.ltl_specification.env_init print response.ltl_specification.sys_trans print response.ltl_specification.env_trans print response.ltl_specification.sys_liveness print response.ltl_specification.env_liveness print 'LTL Compilation error code: ', response.error_code return response except rospy.ServiceException as e: print("Service call failed: %s" % e) if __name__ == "__main__": ltl_compilation_client('atlas', ['pickup'], ['stand'])
Add method finding all widgets by project id
/* * Copyright 2017 EPAM Systems * * * This file is part of EPAM Report Portal. * https://github.com/reportportal/service-api * * Report Portal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Report Portal is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Report Portal. If not, see <http://www.gnu.org/licenses/>. */ package com.epam.ta.reportportal.dao; import com.epam.ta.reportportal.entity.widget.Widget; import java.util.List; /** * @author Pavel Bortnik */ public interface WidgetRepository extends ReportPortalRepository<Widget, Long> { List<Widget> findAllByProjectId(Long projectId); }
/* * Copyright 2017 EPAM Systems * * * This file is part of EPAM Report Portal. * https://github.com/reportportal/service-api * * Report Portal is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Report Portal is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Report Portal. If not, see <http://www.gnu.org/licenses/>. */ package com.epam.ta.reportportal.dao; import com.epam.ta.reportportal.entity.widget.Widget; /** * @author Pavel Bortnik */ public interface WidgetRepository extends ReportPortalRepository<Widget, Long> { }
Remove setters in character and use constructor instead
<?php /** * This file is part of the PierstovalCharacterManagerBundle package. * * (c) Alexandre Rock Ancelet <pierstoval@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pierstoval\Bundle\CharacterManagerBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Pierstoval\Bundle\CharacterManagerBundle\Model\CharacterInterface; abstract class Character implements CharacterInterface { /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=false) */ protected $name; /** * @var string * * @ORM\Column(name="name_slug", type="string", length=255, nullable=false) */ protected $nameSlug; public function __construct(string $name, string $nameSlug) { $this->name = $name; $this->nameSlug = $nameSlug; } public function getName(): string { return $this->name ?: ''; } public function getNameSlug(): string { return $this->nameSlug ?: ''; } }
<?php /** * This file is part of the PierstovalCharacterManagerBundle package. * * (c) Alexandre Rock Ancelet <pierstoval@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pierstoval\Bundle\CharacterManagerBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Pierstoval\Bundle\CharacterManagerBundle\Model\CharacterInterface; abstract class Character implements CharacterInterface { /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=false) */ protected $name; /** * @var string * * @ORM\Column(name="name_slug", type="string", length=255, nullable=false) */ protected $nameSlug; public function getName(): string { return $this->name ?: ''; } public function setName(string $name): self { $this->name = $name; return $this; } public function getNameSlug(): string { return $this->nameSlug ?: ''; } public function setNameSlug(string $nameSlug): self { $this->nameSlug = $nameSlug; return $this; } }
Fix tests on PHP 5.6
<?php namespace LaravelProfaneTests; use LaravelProfane\ProfaneValidator; class ProfaneValidatorBuilder { /** * [$profaneValidator description] * @var [type] */ protected $profaneValidator; /** * [__construct description] * @param [type] $dictionary [description] */ public function __construct($dictionary = null) { $this->profaneValidator = new ProfaneValidator; if ($dictionary) { $this->profaneValidator->setDictionary($dictionary); } } /** * [validate description] * @param array $parameters [description] * @return [type] [description] */ public function validate(array $parameters) { list($attribute, $text, $dictionaries) = $parameters; return $this->build()->validate($attribute, $text, $dictionaries); } /** * [build description] * @return LaravelProfane\ProfaneValidator */ public function build() { return $this->profaneValidator; } }
<?php namespace LaravelProfaneTests; use LaravelProfane\ProfaneValidator; class ProfaneValidatorBuilder { /** * [$profaneValidator description] * @var [type] */ protected $profaneValidator; /** * [__construct description] * @param [type] $dictionary [description] */ public function __construct($dictionary = null) { $this->profaneValidator = new ProfaneValidator; if ($dictionary) { $this->profaneValidator->setDictionary($dictionary); } } /** * [validate description] * @param array $parameters [description] * @return [type] [description] */ public function validate(array $parameters) { list($attribute, $text, $parameters) = $parameters; return $this->build()->validate($attribute, $text, $parameters); } /** * [build description] * @return LaravelProfane\ProfaneValidator */ public function build() { return $this->profaneValidator; } }
Convert Twilio URL to IDN.
from flask import abort, current_app, request from functools import wraps from twilio.util import RequestValidator from config import * def validate_twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) request_valid = validator.validate( request.url.encode("idna"), request.form, request.headers.get("X-TWILIO-SIGNATURE", "")) if request_valid or current_app.debug: return f(*args, **kwargs) else: return abort(403) return decorated_function
from flask import abort, current_app, request from functools import wraps from twilio.util import RequestValidator from config import * def validate_twilio_request(f): @wraps(f) def decorated_function(*args, **kwargs): validator = RequestValidator(TWILIO_SECRET) request_valid = validator.validate( request.url, request.form, request.headers.get("X-TWILIO-SIGNATURE", "")) if request_valid or current_app.debug: return f(*args, **kwargs) else: return abort(403) return decorated_function
Update Layer to use ResourceInfo support class
from urllib2 import HTTPError from geoserver.support import ResourceInfo, atom_link, get_xml from geoserver.style import Style from geoserver.resource import FeatureType, Coverage class Layer(ResourceInfo): resource_type = "layers" def __init__(self, node): self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): ResourceInfo.update(self) name = self.metadata.find("name") attribution = self.metadata.find("attribution") enabled = self.metadata.find("enabled") default_style = self.metadata.find("defaultStyle") if name is not None: self.name = name.text else: self.name = None if attribution is not None: self.attribution = attribution.text else: self.attribution = None if enabled is not None and enabled.text == "true": self.enabled = True else: self.enabled = False if default_style is not None: self.default_style = Style(default_style) else: self.default_style = None resource = self.metadata.find("resource") if resource and "class" in resource.attrib: if resource.attrib["class"] == "featureType": self.resource = FeatureType(resource) elif resource.attrib["class"] == "coverage": self.resource = Coverage(resource) def __repr__(self): return "Layer[%s]" % self.name
from urllib2 import HTTPError from geoserver.support import atom_link, get_xml from geoserver.style import Style from geoserver.resource import FeatureType, Coverage class Layer: def __init__(self, node): self.name = node.find("name").text self.href = atom_link(node) self.update() def update(self): try: layer = get_xml(self.href) self.name = layer.find("name").text self.attribution = layer.find("attribution").text self.enabled = layer.find("enabled").text == "true" self.default_style = Style(layer.find("defaultStyle")) resource = layer.find("resource") if resource and "class" in resource.attrib: if resource.attrib["class"] == "featureType": self.resource = FeatureType(resource) elif resource.attrib["class"] == "coverage": self.resource = Coverage(resource) except HTTPError, e: print e.geturl() def __repr__(self): return "Layer[%s]" % self.name
Update "Active Records" PDF URL
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/file-repository/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
#!/usr/bin/env python import pandas as pd import pdfplumber import requests import datetime import re from io import BytesIO def parse_date(pdf): text = pdf.pages[0].extract_text(x_tolerance=5) date_pat = r"UPDATED:\s+As of (.+)\n" updated_date = re.search(date_pat, text).group(1) d = datetime.datetime.strptime(updated_date, "%B %d, %Y") return d if __name__ == "__main__": URL = "https://www.fbi.gov/about-us/cjis/nics/reports/active_records_in_the_nics-index.pdf" raw = requests.get(URL).content pdf = pdfplumber.load(BytesIO(raw)) d = parse_date(pdf) print(d.strftime("%Y-%m"))
Fix issue with loading error templates for specific error codes.
package com.mitchellbosecke.pebble.boot.autoconfigure; import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import org.springframework.core.io.ResourceLoader; import org.springframework.util.ClassUtils; public class PebbleTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("com.mitchellbosecke.pebble.PebbleEngine", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "pebble."); String prefix = resolver.getProperty("prefix", PebbleProperties.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", PebbleProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + prefix + view + suffix).exists(); } else { return false; } } }
package com.mitchellbosecke.pebble.boot.autoconfigure; import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider; import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import org.springframework.core.io.ResourceLoader; import org.springframework.util.ClassUtils; public class PebbleTemplateAvailabilityProvider implements TemplateAvailabilityProvider { @Override public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) { if (ClassUtils.isPresent("com.mitchellbosecke.pebble.PebbleEngine", classLoader)) { PropertyResolver resolver = new RelaxedPropertyResolver(environment, "pebble."); String prefix = resolver.getProperty("prefix", PebbleProperties.DEFAULT_PREFIX); String suffix = resolver.getProperty("suffix", PebbleProperties.DEFAULT_SUFFIX); return resourceLoader.getResource(prefix + view + suffix).exists(); } else { return false; } } }
Fix query for active tickets on incorrect model
import bookshelf from 'server/lib/db'; import Ticket from 'server/models/ticket'; const User = bookshelf.Model.extend({ tableName: 'users', opened() { return this.hasMany('Ticket', 'studentId'); }, claimed() { return this.hasMany('Ticket', 'assistantId'); }, toJSON() { return this.omit(this.serialize(), 'googleId'); }, async activeTickets() { const id = this.get('id'); const tickets = await Ticket .query(function getActiveTickets(qb) { return qb.where('studentId', id) .orWhere('assistantId', id) .whereIn('status', ['open', 'claimed']); }) .fetchAll(); return tickets.models; }, }); module.exports = bookshelf.model('User', User);
import bookshelf from 'server/lib/db'; const User = bookshelf.Model.extend({ tableName: 'users', opened() { return this.hasMany('Ticket', 'studentId'); }, claimed() { return this.hasMany('Ticket', 'assistantId'); }, toJSON() { return this.omit(this.serialize(), 'googleId'); }, async activeTickets() { const id = this.get('id'); const tickets = await this .query(function getActiveTickets(qb) { return qb.where('studentId', id) .orWhere('assistantId', id) .whereIn('status', ['open', 'claimed']); }) .fetchAll(); return tickets.models; }, }); module.exports = bookshelf.model('User', User);
Use SIGINT instead of SIGHUP to kill child `kill("SIGHUP")` does not work on Windows: Error: kill ENOSYS at exports._errnoException (util.js:870:11) at ChildProcess.kill (internal/child_process.js:374:13) at Worker.terminate (C:\Users\xkr47\project\node_modules\tiny-worker\lib\index.js:55:15) SIGINT works however, and fix confirmed elsewhere also: https://github.com/balderdashy/sails/issues/846#issuecomment-25187082
const path = require("path"); const fork = require("child_process").fork; const worker = path.join(__dirname, "worker.js"); const events = /^(error|message)$/; class Worker { constructor (arg) { let isfn = typeof arg === "function", input = isfn ? arg.toString() : arg; this.child = fork(worker); this.onerror = undefined; this.onmessage = undefined; this.child.on("error", e => { if (this.onerror) { this.onerror.call(this, e); } }); this.child.on("message", msg => { if (this.onmessage) { this.onmessage.call(this, JSON.parse(msg)); } }); this.child.send({input: input, isfn: isfn}); } addEventListener (event, fn) { if (events.test(event)) { this["on" + event] = fn; } } postMessage (msg) { this.child.send(JSON.stringify({data: msg})); } terminate () { this.child.kill("SIGINT"); } } module.exports = Worker;
const path = require("path"); const fork = require("child_process").fork; const worker = path.join(__dirname, "worker.js"); const events = /^(error|message)$/; class Worker { constructor (arg) { let isfn = typeof arg === "function", input = isfn ? arg.toString() : arg; this.child = fork(worker); this.onerror = undefined; this.onmessage = undefined; this.child.on("error", e => { if (this.onerror) { this.onerror.call(this, e); } }); this.child.on("message", msg => { if (this.onmessage) { this.onmessage.call(this, JSON.parse(msg)); } }); this.child.send({input: input, isfn: isfn}); } addEventListener (event, fn) { if (events.test(event)) { this["on" + event] = fn; } } postMessage (msg) { this.child.send(JSON.stringify({data: msg})); } terminate () { this.child.kill("SIGHUP"); } } module.exports = Worker;
Change color of reload commands message to green
package io.github.aquerr.eaglefactions.common.commands; import io.github.aquerr.eaglefactions.api.EagleFactions; import io.github.aquerr.eaglefactions.common.PluginInfo; import io.github.aquerr.eaglefactions.common.messaging.Messages; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; public class ReloadCommand extends AbstractCommand { public ReloadCommand(EagleFactions plugin) { super(plugin); } @Override public CommandResult execute(CommandSource source, CommandContext context) throws CommandException { try { super.getPlugin().getConfiguration().reloadConfiguration(); super.getPlugin().getStorageManager().reloadStorage(); source.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, TextColors.GREEN, Messages.CONFIG_HAS_BEEN_RELOADED)); } catch (Exception exception) { exception.printStackTrace(); } return CommandResult.success(); } }
package io.github.aquerr.eaglefactions.common.commands; import io.github.aquerr.eaglefactions.api.EagleFactions; import io.github.aquerr.eaglefactions.common.PluginInfo; import io.github.aquerr.eaglefactions.common.messaging.Messages; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.text.Text; public class ReloadCommand extends AbstractCommand { public ReloadCommand(EagleFactions plugin) { super(plugin); } @Override public CommandResult execute(CommandSource source, CommandContext context) throws CommandException { try { super.getPlugin().getConfiguration().reloadConfiguration(); super.getPlugin().getStorageManager().reloadStorage(); source.sendMessage(Text.of(PluginInfo.PLUGIN_PREFIX, Messages.CONFIG_HAS_BEEN_RELOADED)); } catch (Exception exception) { exception.printStackTrace(); } return CommandResult.success(); } }
Add complete field to task and timesheet api
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import serializers from core.models import Timesheet, Task, Entry class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'url', 'username',) class TimesheetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Timesheet fields = ('id', 'url', 'name', 'complete',) class TaskSerializer(serializers.HyperlinkedModelSerializer): timesheet_details = TimesheetSerializer(source='timesheet', read_only=True) class Meta: model = Task fields = ('id', 'url', 'timesheet', 'timesheet_details', 'name', 'complete',) class EntrySerializer(serializers.HyperlinkedModelSerializer): task_details = TaskSerializer(source='task', read_only=True) user_details = UserSerializer(source='user', read_only=True) class Meta: model = Entry fields = ('id', 'url', 'task', 'task_details', 'user', 'user_details', 'date', 'duration', 'note',)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import User from rest_framework import serializers from core.models import Timesheet, Task, Entry class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'url', 'username',) class TimesheetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Timesheet fields = ('id', 'url', 'name',) class TaskSerializer(serializers.HyperlinkedModelSerializer): timesheet_details = TimesheetSerializer(source='timesheet', read_only=True) class Meta: model = Task fields = ('id', 'url', 'timesheet', 'timesheet_details', 'name',) class EntrySerializer(serializers.HyperlinkedModelSerializer): task_details = TaskSerializer(source='task', read_only=True) user_details = UserSerializer(source='user', read_only=True) class Meta: model = Entry fields = ('id', 'url', 'task', 'task_details', 'user', 'user_details', 'date', 'duration', 'note',)
Fix bug in write project.
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) if not isinstance(ids, list): ids = [ids] gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp.osv import orm from . import gp_connector class project_compassion(orm.Model): _inherit = 'compassion.project' def write(self, cr, uid, ids, vals, context=None): """Update Project in GP.""" res = super(project_compassion, self).write(cr, uid, ids, vals, context) gp_connect = gp_connector.GPConnect() for project in self.browse(cr, uid, ids, context): gp_connect.upsert_project(uid, project) return res
Fix crash error, send exceptions to loggly
var winston = require('winston'); var mkdirp = require('mkdirp'); // Init log path if (!process.env.LOGPATH) { process.env.LOGPATH = './logs'; } mkdirp(process.env.LOGPATH); // Init Winston file logging module.exports = new winston.Logger({ transports: [ new winston.transports.Console(), new winston.transports.File({ filename: process.env.logpath + '/all.log' }), ], exceptionHandlers: [ new winston.transports.File({ filename: process.env.logpath + '/exceptions.log', }) ] }) if (process.env.LOGGLY_TOKEN) { require('winston-loggly'); module.exports.add(winston.transports.Loggly, { token: process.env.LOGGLY_TOKEN, subdomain: process.env.LOGGLY_DOMAIN, handleExceptions: true, humanReadableUnhandledException: true, json: true }); }
var winston = require('winston'); var mkdirp = require('mkdirp'); // Init log path if (!process.env.LOGPATH) { process.env.LOGPATH = './logs'; } mkdirp(process.env.LOGPATH); // Init Winston file logging module.exports = new winston.Logger({ transports: [ new winston.transports.Console(), new winston.transports.File({ filename: process.env.logpath + '/all.log' }), ], exceptionHandlers: [ new winston.transports.File({ filename: process.env.logpath + '/exceptions.log', }) ] }) if (process.env.LOGGLY_TOKEN) { require('winston-loggly'); logger.add(winston.transports.Loggly, { token: process.env.LOGGLY_TOKEN, subdomain: process.env.LOGGLY_DOMAIN, json: true }); }
Save comment with username instead of user id
import { Mongo } from 'meteor/mongo'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; export const Messages = new Mongo.Collection('messages'); Messages.deny({ insert() { return true; }, update() { return true; }, remove() { return true; } }); export const newMessage = new ValidatedMethod({ name: 'messages.new', validate: new SimpleSchema({ event: { type: String }, text: { type: String } }).validator(), run({ event, text }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } return Messages.insert({ event, user: Meteor.user().username, time: new Date(), text }); } }); export const removeMessage = new ValidatedMethod({ name: 'messages.remove', validate: new SimpleSchema({ id: { type: String } }).validator(), run({ id }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } Messages.remove({ '_id': id }); } }); if (Meteor.isServer) { // This code only runs on the server Meteor.publish('messages', function msgsPublication() { return Messages.find({}); }); }
import { Mongo } from 'meteor/mongo'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { SimpleSchema } from 'meteor/aldeed:simple-schema'; export const Messages = new Mongo.Collection('messages'); Messages.deny({ insert() { return true; }, update() { return true; }, remove() { return true; } }); export const newMessage = new ValidatedMethod({ name: 'messages.new', validate: new SimpleSchema({ event: { type: String }, text: { type: String } }).validator(), run({ event, text }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } return Messages.insert({ event, user: this.userId, time: new Date(), text }); } }); export const removeMessage = new ValidatedMethod({ name: 'messages.remove', validate: new SimpleSchema({ id: { type: String } }).validator(), run({ id }) { if (!this.userId) { throw new Meteor.Error('not-authorized'); } Messages.remove({ '_id': id }); } }); if (Meteor.isServer) { // This code only runs on the server Meteor.publish('messages', function msgsPublication() { return Messages.find({}); }); }
Set default argv to None
#!/usr/bin/env python import os import subprocess import sys def main(argv=None): if argv is None or len(argv) == 0 or len(argv) > 2: print("Usage: databaker_process.py <notebook_file> <input_file>") print() print("<input_file> is optional; it replaces DATABAKER_INPUT_FILE") print("in the notebook.") print("The input file should also be in the same directory as the") print("notebook.") sys.exit(1) process_env = os.environ.copy() if len(argv) == 2: process_env['DATABAKER_INPUT_FILE'] = argv[1] # TODO get custom templates working; according to this: # https://github.com/jupyter/nbconvert/issues/391 # they should work, but I get TemplateNotFound when using absolute path # for template. cmd_line = ['jupyter', 'nbconvert', '--to', 'html', '--execute', argv[0]] print("Running:", ' '.join(cmd_line)) subprocess.call(args=cmd_line, env=process_env) if __name__ == '__main__': main(sys.argv[1:])
#!/usr/bin/env python import os import subprocess import sys def main(argv): if len(argv) == 0 or len(argv) > 2: print("Usage: databaker_process.py <notebook_file> <input_file>") print() print("<input_file> is optional; it replaces DATABAKER_INPUT_FILE") print("in the notebook.") print("The input file should also be in the same directory as the") print("notebook.") sys.exit(1) process_env = os.environ.copy() if len(argv) == 2: process_env['DATABAKER_INPUT_FILE'] = argv[1] # TODO get custom templates working; according to this: # https://github.com/jupyter/nbconvert/issues/391 # they should work, but I get TemplateNotFound when using absolute path # for template. cmd_line = ['jupyter', 'nbconvert', '--to', 'html', '--execute', argv[0]] print("Running:", ' '.join(cmd_line)) subprocess.call(args=cmd_line, env=process_env) if __name__ == '__main__': main(sys.argv[1:])
Declare js variables and remove seconds
var qwait = angular.module('qwait', []); qwait.config(function ($sceProvider) { // TODO: This is a security issue! Remove in final version and do sane interpolation $sceProvider.enabled(false); }); qwait.filter('timestamp', function() { return function (milliseconds) { return new Date(milliseconds); } }); qwait.filter('queuetime', function() { return function (milliseconds) { var p = Math.floor((new Date() - milliseconds)/1000); var x = Math.floor(p/60); var m = x % 60; x = Math.floor(x/60); var h = x % 24; return p < 86400 ? h + 'h ' + m + 'm' : 'Over a day'; } });
var qwait = angular.module('qwait', []); qwait.config(function ($sceProvider) { // TODO: This is a security issue! Remove in final version and do sane interpolation $sceProvider.enabled(false); }); qwait.filter('timestamp', function() { return function (milliseconds) { return new Date(milliseconds); } }); qwait.filter('queuetime', function() { return function (milliseconds) { p = Math.floor((new Date() - milliseconds)/1000); x = p; s = x % 60; x = Math.floor(x/60) m = x % 60; x = Math.floor(x/60) h = x % 24; return p < 86400 ? h + 'h ' + m + 'm ' + s + 's' : 'Over a day'; } });
Revert "lets try with firefox" This reverts commit 8bcd8d6d41561d53ac66e371785a2608ba2ba266.
var config = { allScriptsTimeout: 11000, specs: [ 'e2e/**/*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://localhost:8080/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 }, onPrepare: function() { browser.driver.manage().window().maximize(); browser.driver.executeScript("window.name='PROTRACTOR';"); } }; if (process.env.TRAVIS) { config.sauceUser = process.env.SAUCE_USERNAME; config.sauceKey = process.env.SAUCE_ACCESS_KEY; config.capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; config.capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER; config.capabilities['name'] = "coopr-ngui build#"+process.env.TRAVIS_BUILD_NUMBER; } module.exports.config = config;
var config = { allScriptsTimeout: 11000, specs: [ 'e2e/**/*.js' ], capabilities: { 'browserName': 'firefox' }, baseUrl: 'http://localhost:8080/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 }, onPrepare: function() { browser.driver.manage().window().maximize(); browser.driver.executeScript("window.name='PROTRACTOR';"); } }; if (process.env.TRAVIS) { config.sauceUser = process.env.SAUCE_USERNAME; config.sauceKey = process.env.SAUCE_ACCESS_KEY; config.capabilities['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER; config.capabilities['build'] = process.env.TRAVIS_BUILD_NUMBER; config.capabilities['name'] = "coopr-ngui build#"+process.env.TRAVIS_BUILD_NUMBER; } module.exports.config = config;
Fix a bug in loaded that saved not-normalized var We need to copy & paste setEnvironmentVariable() because there's no other way to access normalized variable name. - See #14
<?php /* * This file is part of the wpstarter package. * * (c) Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WCM\WPStarter\Env; use Dotenv\Loader as DotenvLoader; /** * @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com> * @license http://opensource.org/licenses/MIT MIT * @package wpstarter */ final class Loader extends DotenvLoader { private $allVars = array(); /** * Set variable using Dotenv loader and store the name in class var * * @param string $name * @param mixed $value */ public function setEnvironmentVariable($name, $value = null) { list($name, $value) = $this->normaliseEnvironmentVariable($name, $value); if ($this->immutable === true && ! is_null($this->getEnvironmentVariable($name))) { return; } putenv("$name=$value"); $_ENV[$name] = $value; $_SERVER[$name] = $value; $this->allVars[] = $name; } /** * @return array */ public function allVarNames() { return $this->allVars; } }
<?php /* * This file is part of the wpstarter package. * * (c) Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WCM\WPStarter\Env; use Dotenv\Loader as DotenvLoader; /** * @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com> * @license http://opensource.org/licenses/MIT MIT * @package wpstarter */ final class Loader extends DotenvLoader { private $allVars = array(); /** * Set variable using Dotenv loader and store the name in class var * * @param string $name * @param mixed $value */ public function setEnvironmentVariable($name, $value = null) { parent::setEnvironmentVariable($name, $value); $this->allVars[] = $name; } /** * @return array */ public function allVarNames() { return $this->allVars; } }
Make plugin work in python 3 Python 3 doesn't have itertools.izip, just the builtin, zip. This logic allows us to pull out either one depending on python version
from isort import SortImports import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def get_status(had_changes): return mothermayi.colors.red('unsorted') if had_changes else mothermayi.colors.green('sorted') def pre_commit(config, staged): changes = [do_sort(filename) for filename in staged] messages = [get_status(had_change) for had_change in changes] lines = [" {0:<30} ... {1:<10}".format(filename, message) for filename, message in zip(staged, messages)] result = "\n".join(lines) if any(changes): raise mothermayi.errors.FailHook(result) return result
from isort import SortImports import itertools import mothermayi.colors import mothermayi.errors def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return results.in_lines != results.out_lines def get_status(had_changes): return mothermayi.colors.red('unsorted') if had_changes else mothermayi.colors.green('sorted') def pre_commit(config, staged): changes = [do_sort(filename) for filename in staged] messages = [get_status(had_change) for had_change in changes] lines = [" {0:<30} ... {1:<10}".format(filename, message) for filename, message in itertools.izip(staged, messages)] result = "\n".join(lines) if any(changes): raise mothermayi.errors.FailHook(result) return result
Add a wan simulator to reproduce timing sensitive issues with a random 0.5 ms delay.
package net.openhft.chronicle.network; import net.openhft.chronicle.core.Jvm; import java.util.Random; /** * Created by peter.lawrey on 16/07/2015. */ public enum WanSimulator { ; private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0); private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000; private static final Random RANDOM = new Random(); private static long totalRead = 0; public static void dataRead(int bytes) { if (NET_BANDWIDTH <= 0) return; totalRead += bytes + RANDOM.nextInt(BYTES_PER_MS / 2); int delay = (int) (totalRead / BYTES_PER_MS); if (delay > 0) { Jvm.pause(delay); totalRead = 0; } } }
package net.openhft.chronicle.network; import net.openhft.chronicle.core.Jvm; import java.util.Random; /** * Created by peter.lawrey on 16/07/2015. */ public enum WanSimulator { ; private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0); private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000; private static final Random RANDOM = new Random(); private static long totalRead = 0; public static void dataRead(int bytes) { if (NET_BANDWIDTH <= 0) return; totalRead += bytes + RANDOM.nextInt(BYTES_PER_MS); int delay = (int) (totalRead / BYTES_PER_MS); if (delay > 0) { Jvm.pause(delay); totalRead = 0; } } }
Add RSS & Atom autodiscovery URLs
<!DOCTYPE HTML> <!--[if IEMobile 7 ]><html class="no-js iem7" manifest="default.appcache?v=1"><![endif]--> <!--[if lt IE 7 ]><html class="no-js ie6" lang="en"><![endif]--> <!--[if IE 7 ]><html class="no-js ie7" lang="en"><![endif]--> <!--[if IE 8 ]><html class="no-js ie8" lang="en"><![endif]--> <!--[if (gte IE 9)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]--> <head> <title><?php wp_title(''); ?></title> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"><!-- Remove if you're not building a responsive site. (But then why would you do such a thing?) --> <link rel="alternate" type="application/rss+xml" title="Hypothes.is Blog (RSS)" href="<?php bloginfo('rss2_url'); ?>" /> <link rel="alternate" type="application/atom+xml" title="Hypothes.is Blog (Atom)" href="<?php bloginfo('atom_url'); ?>" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico"/> <?php wp_head(); ?> </head> <body id="pagetainer">
<!DOCTYPE HTML> <!--[if IEMobile 7 ]><html class="no-js iem7" manifest="default.appcache?v=1"><![endif]--> <!--[if lt IE 7 ]><html class="no-js ie6" lang="en"><![endif]--> <!--[if IE 7 ]><html class="no-js ie7" lang="en"><![endif]--> <!--[if IE 8 ]><html class="no-js ie8" lang="en"><![endif]--> <!--[if (gte IE 9)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]--> <head> <title><?php wp_title(''); ?></title> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"><!-- Remove if you're not building a responsive site. (But then why would you do such a thing?) --> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico"/> <?php wp_head(); ?> </head> <body id="pagetainer">
Add third-party and CC-BY license URLs for 'de' locale
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ // Relative to the samples folder "GETTING_STARTED" : "de/Erste Schritte", "ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty_de/", "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.de" });
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ // Relative to the samples folder "GETTING_STARTED" : "de/Erste Schritte" });
Include context in RSVP handler.
/** * Ember.js plugin * * Patches event handler callbacks and ajax callbacks. */ ;(function(window, Raven, Ember) { 'use strict'; // quit if Ember isn't on the page if (!Ember) { return; } var _oldOnError = Ember.onerror; Ember.onerror = function EmberOnError(error) { Raven.captureException(error); if (typeof _oldOnError === 'function') { _oldOnError.call(this, error); } }; Ember.RSVP.on('error', function (reason) { if (reason instanceof Error) { Raven.captureException(reason, {extra: {context: 'Unhandled RSVP error'}}); } else { try { throw new Error('Unhandled Promise error detected'); } catch (err) { Raven.captureException(err, {extra: {reason: reason}}); } } }); }(window, window.Raven, window.Ember));
/** * Ember.js plugin * * Patches event handler callbacks and ajax callbacks. */ ;(function(window, Raven, Ember) { 'use strict'; // quit if Ember isn't on the page if (!Ember) { return; } var _oldOnError = Ember.onerror; Ember.onerror = function EmberOnError(error) { Raven.captureException(error); if (typeof _oldOnError === 'function') { _oldOnError.call(this, error); } }; Ember.RSVP.on('error', function (reason) { if (reason instanceof Error) { Raven.captureException(reason); } else { try { throw new Error('Unhandled Promise error detected'); } catch (err) { Raven.captureException(err, {extra: {reason: reason}}); } } }); }(window, window.Raven, window.Ember));
Add splitlines method to substitute_keywords
import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = '' for line in text.splitlines(keepends=True): for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
import logging import subprocess import re def substitute_keywords(text, repo_folder, commit): substitutions = { 'version': commit, 'date': subprocess.check_output( ['git', '-C', repo_folder, 'show', '-s', '--format=%ci', commit], stderr=subprocess.STDOUT), } new_text = None for line in text: for key, value in substitutions.items(): rexp = '%s:.*' % key line = re.sub(rexp, '%s: %s' % (key, value), line) new_text += line return new_text class DeploymentCommand(object): def __init__(self, *args): self._logger = logging.getLogger(__name__) self.args = args self._execute() def _execute(self): raise NotImplementedError
Change the min feature to a parameter as ?min=true to get data form joiner.
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.query.min) ? req.query.min : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });
/* * Module dependencies */ var app = module.parent.exports, Joiner = require('../libs/joiner').Joiner; /* * Middlewares */ function isAnotherFile (req, res, next) { var folder = req.params.version; if (folder === 'assets' || folder === 'vendor' || folder === 'test' || folder === 'libs') { next('route'); } else { next(); } }; function isView (req, res, next) { if (req.params.type === undefined) { res.render(req.params.version + '.html'); } else { next(); } }; /* * Views */ app.get('/:version/:type?/:min?', isAnotherFile, isView, function (req, res, next) { var name = req.params.version + req.params.type.toUpperCase(), min = ((req.params.min) ? true : false), joiner = new Joiner(); joiner.on('joined', function (data) { res.set('Content-Type', 'text/' + (req.params.type === 'js' ? 'javascript' : 'css')); res.send(data.raw); }); joiner.run(name, min); }); /* * Index */ app.get('/', function (req, res, next) { res.redirect('/ui') });