text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Set property in case it has been set wrong previously git-svn-id: 7abf240ce0ec4644a9bf59262a41ad5796234f37@372 43379f7c-b030-0410-81db-e0b70742847c
package org.jaxen.javabean; import junit.framework.TestCase; import org.jaxen.saxpath.helpers.XPathReaderFactory; public class DocumentNavigatorTest extends TestCase { protected void setUp() throws Exception { System.setProperty( XPathReaderFactory.DRIVER_PROPERTY, "" ); } public void testNothing() throws Exception { JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" ); Person bob = new Person( "bob", 30 ); bob.addBrother( new Person( "billy", 34 ) ); bob.addBrother( new Person( "seth", 29 ) ); bob.addBrother( new Person( "dave", 32 ) ); bob.addBrother( new Person( "jim", 29 ) ); bob.addBrother( new Person( "larry", 42 ) ); bob.addBrother( new Person( "ted", 22 ) ); System.err.println( xpath.evaluate( bob ) ); } }
package org.jaxen.javabean; import junit.framework.TestCase; public class DocumentNavigatorTest extends TestCase { public void testNothing() throws Exception { JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" ); Person bob = new Person( "bob", 30 ); bob.addBrother( new Person( "billy", 34 ) ); bob.addBrother( new Person( "seth", 29 ) ); bob.addBrother( new Person( "dave", 32 ) ); bob.addBrother( new Person( "jim", 29 ) ); bob.addBrother( new Person( "larry", 42 ) ); bob.addBrother( new Person( "ted", 22 ) ); System.err.println( xpath.evaluate( bob ) ); } }
Update code to follow standard style
/** * Comma number formatter * @param {Number} number Number to format * @param {String} [separator=','] Value used to separate numbers * @returns {String} Comma formatted number */ module.exports = function commaNumber (number, separator) { separator = typeof separator === 'undefined' ? ',' : ('' + separator) // Convert to number if it's a non-numeric value if (typeof number !== 'number') { number = Number(number) } // NaN => 0 if (isNaN(number)) { number = 0 } // Return Infinity immediately if (!isFinite(number)) { return '' + number } var stringNumber = ('' + Math.abs(number)) .split('') .reverse() var result = [] for (var i = 0; i < stringNumber.length; i++) { if (i && i % 3 === 0) { result.push(separator) } result.push(stringNumber[i]) } // Handle negative numbers if (number < 0) { result.push('-') } return result .reverse() .join('') }
/** * Comma number formatter * @param {Number} number Number to format * @param {String} [separator=','] Value used to separate numbers * @returns {String} Comma formatted number */ module.exports = function commaNumber (number, separator) { separator = typeof separator === 'undefined' ? ',' : ('' + separator) // Convert to number if it's a non-numeric value if (typeof number !== 'number') number = Number(number) // NaN => 0 if (isNaN(number)) number = 0 // Return Infinity immediately if (!isFinite(number)) return '' + number var stringNumber = ('' + Math.abs(number)) .split('') .reverse() var result = [] for (var i = 0; i < stringNumber.length; i++) { if (i && i % 3 === 0) result.push(separator) result.push(stringNumber[i]) } // Handle negative numbers if (number < 0) result.push('-') return result .reverse() .join('') }
daemon: Raise timeout for test to 1s.
package daemon import ( "testing" "time" "github.com/elves/elvish/util" ) func TestDaemon(t *testing.T) { util.InTempDir(func(string) { serverDone := make(chan struct{}) go func() { Serve("sock", "db") close(serverDone) }() client := NewClient("sock") for i := 0; i < 100; i++ { client.ResetConn() _, err := client.Version() if err == nil { break } else if i == 99 { t.Fatal("Failed to connect after 1s") } time.Sleep(10 * time.Millisecond) } _, err := client.AddCmd("test cmd") if err != nil { t.Errorf("client.AddCmd -> error %v", err) } client.Close() // Wait for server to quit before returning <-serverDone }) }
package daemon import ( "testing" "time" "github.com/elves/elvish/util" ) func TestDaemon(t *testing.T) { util.InTempDir(func(string) { serverDone := make(chan struct{}) go func() { Serve("sock", "db") close(serverDone) }() client := NewClient("sock") for i := 0; i < 10; i++ { client.ResetConn() _, err := client.Version() if err == nil { break } else if i == 9 { t.Fatal("Failed to connect after 100ms") } time.Sleep(10 * time.Millisecond) } _, err := client.AddCmd("test cmd") if err != nil { t.Errorf("client.AddCmd -> error %v", err) } client.Close() // Wait for server to quit before returning <-serverDone }) }
Use JSON for other than GET request Because internal dict parameters is not handled as expected. >>> payload = {'key1': 'value1', 'key2': 'value2', 'set': {'a': 'x', 'b': 'y'}} >>> r = requests.post("http://httpbin.org/post", data=payload) >>> r.json() {... 'form': {'key2': 'value2', 'key1': 'value1', 'set': ['a', 'b']} ...}
from .api import Account, Charges, Customers import requests import json class WebPay: def __init__(self, key, api_base = 'https://api.webpay.jp/v1'): self.key = key self.api_base = api_base self.account = Account(self) self.charges = Charges(self) self.customers = Customers(self) def post(self, path, params): r = requests.post(self.api_base + path, auth = (self.key, ''), data = json.dumps(params)) return r.json() def get(self, path, params = {}): r = requests.get(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def delete(self, path, params = {}): r = requests.delete(self.api_base + path, auth = (self.key, ''), data = json.dumps(params)) return r.json()
from .api import Account, Charges, Customers import requests class WebPay: def __init__(self, key, api_base = 'https://api.webpay.jp/v1'): self.key = key self.api_base = api_base self.account = Account(self) self.charges = Charges(self) self.customers = Customers(self) def post(self, path, params): r = requests.post(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def get(self, path, params = {}): r = requests.get(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def delete(self, path, params = {}): r = requests.delete(self.api_base + path, auth = (self.key, ''), params = params) return r.json()
Change test for multiple rooms to use test set-up
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3)
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): my_class_instance = Dojo() initial_room_count = len(my_class_instance.all_rooms) offices = my_class_instance.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(my_class_instance.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3)
Make wrapAsync support wrapping async functions that return a promise
var Fiber = require('fibers'); var Future = require('fibers/future'); var _ = require('underscore'); var assert = require('assert'); // Makes a function that returns a promise or takes a callback synchronous exports.wrapAsync = function (fn, context) { return function (/* arguments */) { var self = context || this; var newArgs = _.toArray(arguments); var callback; for (var i = newArgs.length - 1; i >= 0; --i) { var arg = newArgs[i]; var type = typeof arg; if (type !== "undefined") { if (type === "function") { callback = arg; } break; } } if (!callback) { var future = new Future(); callback = _.once(future.resolver()); ++i; // Insert the callback just after arg. } newArgs[i] = callback; var result = fn.apply(self, newArgs); if (result && _.isFunction(result.then)) { result.then( function (result) { callback(null, result); }, function (error) { callback(error); } ); } return future ? future.wait() : result; }; };
var Fiber = require('fibers'); var Future = require('fibers/future'); var _ = require('underscore'); var assert = require('assert'); // Makes a function that returns a promise or takes a callback synchronous exports.wrapAsync = function (fn, context) { return function (/* arguments */) { var self = context || this; var newArgs = _.toArray(arguments); var callback; for (var i = newArgs.length - 1; i >= 0; --i) { var arg = newArgs[i]; var type = typeof arg; if (type !== "undefined") { if (type === "function") { callback = arg; } break; } } if (!callback) { var future = new Future(); callback = future.resolver(); ++i; // Insert the callback just after arg. } newArgs[i] = callback; var result = fn.apply(self, newArgs); return future ? future.wait() : result; }; };
Fix typo 'ploadedAt' => 'uploadedAt'
import React from 'react'; class ImageCardComponent extends React.Component { static propTypes = { uri: React.PropTypes.string.isRequired, uploadedAt: React.PropTypes.string.isRequired }; render() { return ( <div className='ImageCardComponent'> <div className='card'> <a href={this.props.uri}> <img className='card-image-top img-responsive' src={this.props.uri}/> </a> <div className='card-block hidden-xs-down'> <a href={this.props.uri} style={{ wordBreak: 'break-all', wordWrap: 'break-word' }}>{this.props.uri}</a> </div> <footer className='card-footer text-muted text-right'> <span className='uploaded-at'> <time dateTime={this.props.uploadedAt}>{this.props.uploadedAt}</time> </span> </footer> </div> </div> ); } } export default ImageCardComponent;
import React from 'react'; class ImageCardComponent extends React.Component { static propTypes = { uri: React.PropTypes.string.isRequired, uploadedAt: React.PropTypes.string.isRequired }; render() { return ( <div className='ImageCardComponent'> <div className='card'> <a href={this.props.uri}> <img className='card-image-top img-responsive' src={this.props.uri}/> </a> <div className='card-block hidden-xs-down'> <a href={this.props.uri} style={{ wordBreak: 'break-all', wordWrap: 'break-word' }}>{this.props.uri}</a> </div> <footer className='card-footer text-muted text-right'> <span className='uploaded-at'> <time dateTime={this.props.uploadedAt}>{this.props.ploadedAt}</time> </span> </footer> </div> </div> ); } } export default ImageCardComponent;
Fix dependency injection in angular
angular.module("currencyJa", []) .controller("TradersCtrl", ["$scope", "traderService", function ($scope, traderService) { $scope.currency = "USD"; $scope.traders = traderService.findByCurrency($scope.currency); $scope.multiplyByBase = function(amount) { var base = parseFloat($scope.base) ? parseFloat($scope.base) : 1 return amount * base } $scope.changeCurrency = function(currency) { $scope.currency = currency; $scope.traders = traderService.findByCurrency($scope.currency); } }]) .service('traderService', function() { this.findByCurrency = function(currency) { var traders = [] angular.forEach(gon.traders, function(trader, key) { traders.push({ name: trader.name, shortName: trader.short_name, buyCash: trader.currencies[currency]['buy_cash'], buyDraft: trader.currencies[currency]['buy_draft'], sellCash: trader.currencies[currency]['sell_cash'], sellDraft: trader.currencies[currency]['sell_draft'] }); }); return traders; }; });
angular.module("currencyJa", []) .controller("TradersCtrl", function ($scope, traderService) { $scope.currency = "USD"; $scope.traders = traderService.findByCurrency($scope.currency); $scope.multiplyByBase = function(amount) { var base = parseFloat($scope.base) ? parseFloat($scope.base) : 1 return amount * base } $scope.changeCurrency = function(currency) { $scope.currency = currency; $scope.traders = traderService.findByCurrency($scope.currency); } }) .service('traderService', function() { this.findByCurrency = function(currency) { var traders = [] angular.forEach(gon.traders, function(trader, key) { traders.push({ name: trader.name, shortName: trader.short_name, buyCash: trader.currencies[currency]['buy_cash'], buyDraft: trader.currencies[currency]['buy_draft'], sellCash: trader.currencies[currency]['sell_cash'], sellDraft: trader.currencies[currency]['sell_draft'] }); }); return traders; }; });
Allow settings to override default lengths.
from django.utils.translation import ugettext_lazy as _ from django.conf import settings KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_KEY_SIZE', 16) SECRET_SIZE = getattr(settings, 'OAUTH_PROVIDER_SECRET_SIZE', 16) VERIFIER_SIZE = getattr(settings, 'OAUTH_PROVIDER_VERIFIER_SIZE', 10) CONSUMER_KEY_SIZE = getattr(settings, 'OAUTH_PROVIDER_CONSUMER_KEY_SIZE', 256) MAX_URL_LENGTH = 2083 # http://www.boutell.com/newfaq/misc/urllength.html PENDING = 1 ACCEPTED = 2 CANCELED = 3 REJECTED = 4 CONSUMER_STATES = ( (PENDING, _('Pending')), (ACCEPTED, _('Accepted')), (CANCELED, _('Canceled')), (REJECTED, _('Rejected')), ) PARAMETERS_NAMES = ('consumer_key', 'token', 'signature', 'signature_method', 'timestamp', 'nonce') OAUTH_PARAMETERS_NAMES = ['oauth_'+s for s in PARAMETERS_NAMES] OUT_OF_BAND = 'oob'
from django.utils.translation import ugettext_lazy as _ KEY_SIZE = 16 SECRET_SIZE = 16 VERIFIER_SIZE = 10 CONSUMER_KEY_SIZE = 256 MAX_URL_LENGTH = 2083 # http://www.boutell.com/newfaq/misc/urllength.html PENDING = 1 ACCEPTED = 2 CANCELED = 3 REJECTED = 4 CONSUMER_STATES = ( (PENDING, _('Pending')), (ACCEPTED, _('Accepted')), (CANCELED, _('Canceled')), (REJECTED, _('Rejected')), ) PARAMETERS_NAMES = ('consumer_key', 'token', 'signature', 'signature_method', 'timestamp', 'nonce') OAUTH_PARAMETERS_NAMES = ['oauth_'+s for s in PARAMETERS_NAMES] OUT_OF_BAND = 'oob'
Make sure to not handle errors if error_reporting is 0, to have the same behavior as in Cake\Error\BaseErrorHandler
<?php namespace Monitor\Error; use Cake\Core\Configure; use Exception; class SentryHandler { /** * Constructor * */ public function __construct() { } /** * Exception Handler * * @param Exception $exception Exception to handle * @return void */ public function handle(Exception $exception) { if (!Configure::read('CakeMonitor.Sentry.enabled') || error_reporting() === 0) { return false; } $client = new \Raven_Client(Configure::read('CakeMonitor.Sentry.dsn'), [ 'processorOptions' => [ 'Raven_SanitizeDataProcessor' => [ 'fields_re' => '/(' . implode('|', Configure::read('CakeMonitor.Sentry.sanitizeFields')) . ')/i' ] ] ]); $errorHandler = new \Raven_ErrorHandler($client); $errorHandler->registerShutdownFunction(); $errorHandler->handleException($exception); } }
<?php namespace Monitor\Error; use Cake\Core\Configure; use Exception; class SentryHandler { /** * Constructor * */ public function __construct() { } /** * Exception Handler * * @param Exception $exception Exception to handle * @return void */ public function handle(Exception $exception) { if (!Configure::read('CakeMonitor.Sentry.enabled')) { return; } $client = new \Raven_Client(Configure::read('CakeMonitor.Sentry.dsn'), [ 'processorOptions' => [ 'Raven_SanitizeDataProcessor' => [ 'fields_re' => '/(' . implode('|', Configure::read('CakeMonitor.Sentry.sanitizeFields')) . ')/i' ] ] ]); $errorHandler = new \Raven_ErrorHandler($client); $errorHandler->registerShutdownFunction(); $errorHandler->handleException($exception); } }
[MOD] Apply batch to all users git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@52510 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ namespace Tiki\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Tiki\Recommendation\Input\UserInput; use TikiLib; class RecommendationBatchCommand extends Command { protected function configure() { $this ->setName('recommendation:batch') ->setDescription('Identify and send recommendations'); } protected function execute(InputInterface $input, OutputInterface $output) { $batch = TikiLib::lib('recommendationcontentbatch'); $userlib = TikiLib::lib('user'); $list = array_map(function ($user) { return new UserInput($user); }, $userlib->get_users_names()); $batch->process($list); } }
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ namespace Tiki\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Tiki\Recommendation\Input\UserInput; use TikiLib; class RecommendationBatchCommand extends Command { protected function configure() { $this ->setName('recommendation:batch') ->setDescription('Identify and send recommendations'); } protected function execute(InputInterface $input, OutputInterface $output) { $batch = TikiLib::lib('recommendationcontentbatch'); $batch->process([new UserInput('user1')]); } }
Read the README file with UTF-8 encoding. This commit fixes an install issue in Python 3.5 where the read() function raises an encoding error. It uses the open function from the io module so that the code will be compatible with both Python 2 and 3.
#!/usr/bin/python3 import os from distutils.core import setup from io import open here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst'), encoding='utf8').read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() except IOError: README = CHANGES = '' setup( name="rpdb", version="0.1.6", description="pdb wrapper with remote access via tcp socket", long_description=README + "\n\n" + CHANGES, author="Bertrand Janin", author_email="b@janin.com", url="http://tamentis.com/projects/rpdb", packages=["rpdb"], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: ISC License (ISCL)", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.0", "Programming Language :: Python :: 3.1", "Topic :: Software Development :: Debuggers", ] )
#!/usr/bin/python import os from distutils.core import setup here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() except IOError: README = CHANGES = '' setup( name="rpdb", version="0.1.6", description="pdb wrapper with remote access via tcp socket", long_description=README + "\n\n" + CHANGES, author="Bertrand Janin", author_email="b@janin.com", url="http://tamentis.com/projects/rpdb", packages=["rpdb"], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "License :: OSI Approved :: ISC License (ISCL)", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.0", "Programming Language :: Python :: 3.1", "Topic :: Software Development :: Debuggers", ] )
Use promise-form of less call and improve error reporting
'use strict'; var Filter = require('broccoli-filter'); var RSVP = require('rsvp'); var less = require('less'); function LessFilter(inputTree, options) { if (!(this instanceof LessFilter)) { return new LessFilter(inputTree, options); } this.inputTree = inputTree; this.options = options || {}; } LessFilter.prototype = Object.create(Filter.prototype); LessFilter.prototype.constructor = LessFilter; LessFilter.prototype.extensions = ['less']; LessFilter.prototype.targetExtension = 'css'; LessFilter.prototype.processString = function (str, relativePath) { this.options.filename = this.options.filename || relativePath; return less.render(str, this.options).then(function(output) { return output.css; }).catch(function(error) { console.error("Error processing file ", error.filename, "at line ", error.line); console.error(error.message); console.error("Near:"); console.error(error.extract.join('\n')); }); }; module.exports = LessFilter;
'use strict'; var Filter = require('broccoli-filter'); var RSVP = require('rsvp'); var less = require('less'); function LessFilter(inputTree, options) { if (!(this instanceof LessFilter)) { return new LessFilter(inputTree, options); } this.inputTree = inputTree; this.options = options || {}; } LessFilter.prototype = Object.create(Filter.prototype); LessFilter.prototype.constructor = LessFilter; LessFilter.prototype.extensions = ['less']; LessFilter.prototype.targetExtension = 'css'; LessFilter.prototype.processString = function (str) { return new RSVP.Promise(function(resolve, reject) { less.render(str, this.options, function (err, data) { if (err) { reject(err); return; } resolve(data.css); }); }.bind(this)); }; module.exports = LessFilter;
Set default thumbs width to 250
/* * Copyright (c) 2014 Giovanni Capuano <webmaster@giovannicapuano.net> * Released under the MIT License * http://opensource.org/licenses/MIT */ var config = {}; // Images configuration config.images = { path: '../images', url : '/images' }; // Set the following line to false if you have a webserver that serves you static resources or you have just put your images folder in public/. // Your images will be available to /dirname/ (where dirname is the name of your images folder). config.serve = true; // The image extensions to show config.exts = [ '.jpg', '.jpeg', '.bmp', '.png', '.gif' ]; // Sort images and folders config.sort = { mode: 'DESC', // ASC DESC by : 'lastModify' // name lastModify }; // Image served by Vasilij will be put in browser cache for 30 days config.maxAge = '2592000'; // Thumbnails configuration config.thumbs = { path : '../thumbs', url : '/thumbs', width : 250, cpu : 8 }; module.exports = config;
/* * Copyright (c) 2014 Giovanni Capuano <webmaster@giovannicapuano.net> * Released under the MIT License * http://opensource.org/licenses/MIT */ var config = {}; // Images configuration config.images = { path: '../images', url : '/images' }; // Set the following line to false if you have a webserver that serves you static resources or you have just put your images folder in public/. // Your images will be available to /dirname/ (where dirname is the name of your images folder). config.serve = true; // The image extensions to show config.exts = [ '.jpg', '.jpeg', '.bmp', '.png', '.gif' ]; // Sort images and folders config.sort = { mode: 'DESC', // ASC DESC by : 'lastModify' // name lastModify }; // Image served by Vasilij will be put in browser cache for 30 days config.maxAge = '2592000'; // Thumbnails configuration config.thumbs = { path : '../thumbs', url : '/thumbs', width : 500, cpu : 8 }; module.exports = config;
Sort child entries by its name
package yang import ( "sort" "github.com/openconfig/goyang/pkg/yang" ) type entry struct { *yang.Entry } func (e entry) rpcs() []entry { var names []string for name, child := range e.Dir { if child.RPC != nil { names = append(names, name) } } sort.Strings(names) rpcs := []entry{} for _, name := range names { rpcs = append(rpcs, entry{e.Dir[name]}) } return rpcs } func (e entry) notifications() []entry { var names []string for name, child := range e.Dir { if child.Kind == yang.NotificationEntry { names = append(names, name) } } sort.Strings(names) ns := []entry{} for _, name := range names { ns = append(ns, entry{e.Dir[name]}) } return ns } func (e entry) children() []entry { var names []string for name, child := range e.Dir { if child.RPC != nil || child.Kind == yang.NotificationEntry { continue } names = append(names, name) } sort.Strings(names) children := []entry{} for _, name := range names { children = append(children, entry{e.Dir[name]}) } return children }
package yang import "github.com/openconfig/goyang/pkg/yang" type entry struct { *yang.Entry } func (e entry) rpcs() []entry { rpcs := []entry{} for _, child := range e.Dir { if child.RPC != nil { rpcs = append(rpcs, entry{child}) } } return rpcs } func (e entry) notifications() []entry { ns := []entry{} for _, child := range e.Dir { if child.Kind == yang.NotificationEntry { ns = append(ns, entry{child}) } } return ns } func (e entry) children() []entry { children := []entry{} for _, child := range e.Dir { if child.RPC != nil || child.Kind == yang.NotificationEntry { continue } children = append(children, entry{child}) } return children }
Fix line endings in file
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_y(): result = util.rotation_matrix(0.218, 1) expected = np.array( [[0.97633196, 0.0, 0.21627739], [0.0, 1.0, 0.0], [0.21627739, 0.0, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_z(): result = util.rotation_matrix(0.218, 2) expected = np.array( [[0.97633196, -0.21627739, 0.0], [0.21627739, 0.97633196, 0.0], [0.0, 0.0, 1.0]] ) assert np.allclose(expected, result)
import numpy as np from poliastro.core import util def test_rotation_matrix_x(): result = util.rotation_matrix(0.218, 0) expected = np.array( [[1.0, 0.0, 0.0], [0.0, 0.97633196, -0.21627739], [0.0, 0.21627739, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_y(): result = util.rotation_matrix(0.218, 1) expected = np.array( [[0.97633196, 0.0, 0.21627739], [0.0, 1.0, 0.0], [0.21627739, 0.0, 0.97633196]] ) assert np.allclose(expected, result) def test_rotation_matrix_z(): result = util.rotation_matrix(0.218, 2) expected = np.array( [[0.97633196, -0.21627739, 0.0], [0.21627739, 0.97633196, 0.0], [0.0, 0.0, 1.0]] ) assert np.allclose(expected, result)
Add Error Message To Server
# Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable # law or agreed to in writing, software distributed under the License is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and # limitations under the License. import urllib2 import json from google.appengine.ext import vendor vendor.add('lib') from flask import Flask app = Flask(__name__) from api_key import key @app.route('/get_author/<title>') def get_author(title): host = 'https://www.googleapis.com/books/v1/volumes?q={}&key={}&country=US'.format(title, key) request = urllib2.Request(host) try: response = urllib2.urlopen(request) except urllib2.HTTPError, error: contents = error.read() print ('Received error from Books API {}'.format(contents)) return str(contents) html = response.read() author = json.loads(html)['items'][0]['volumeInfo']['authors'][0] return author if __name__ == '__main__': app.run(debug=True)
# Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy of the # License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable # law or agreed to in writing, software distributed under the License is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and # limitations under the License. import urllib2 import json from google.appengine.ext import vendor vendor.add('lib') from flask import Flask app = Flask(__name__) from api_key import key @app.route('/get_author/<title>') def get_author(title): host = 'https://www.googleapis.com/books/v1/volumes?q={}&key={}&country=US'.format(title, key) request = urllib2.Request(host) try: response = urllib2.urlopen(request) except urllib2.HTTPError, error: contents = error.read() return str(contents) html = response.read() author = json.loads(html)['items'][0]['volumeInfo']['authors'][0] return author if __name__ == '__main__': app.run(debug=True)
Make sure git up to date
var insertWrapper = function(wrapper) { var cursor = $('.cursor'); if (cursor.length > 0) { var container = cursor.parent().data('eqObject'); if (cursor.parent().hasClass('squareEmptyContainer')) { container = container.parent.parent; container.removeWrappers(0); } if (cursor.siblings('.topLevelEmptyContainerWrapper').length > 0) { container.removeWrappers(0); } container.addWrappers([highlightStartIndex, wrapper]); wrapper.updateAll(); removeCursor(); if (wrapper.childContainers.length > 0) { addCursorAtIndex(wrapper.childContainers[0].wrappers[0].childContainers[0], 0); container = wrapper.childContainers[0].wrappers[0].childContainers[0]; } else { addCursorAtIndex(container, (++highlightStartIndex)); } $('.activeContainer').removeClass('activeContainer'); container.domObj.value.addClass('activeContainer'); } };
var insertWrapper = function(wrapper) { var cursor = $('.cursor'); if (cursor.length > 0) { var container = cursor.parent().data('eqObject'); if (cursor.parent().hasClass('squareEmptyContainer')) { container = container.parent.parent; container.removeWrappers(0); } if (cursor.siblings('.topLevelEmptyContainerWrapper').length > 0) { container.removeWrappers(0); } container.addWrappers([highlightStartIndex, wrapper]); wrapper.updateAll(); removeCursor(); if (wrapper.childContainers.length > 0) { addCursorAtIndex(wrapper.childContainers[0].wrappers[0].childContainers[0], 0); container = wrapper.childContainers[0].wrappers[0].childContainers[0]; } else { addCursorAtIndex(container, (++highlightStartIndex)); } $('.activeContainer').removeClass('activeContainer'); container.domObj.value.addClass('activeContainer'); } }
Update deps, fix Espresso, add test
<?php namespace React\Espresso; use React\Http\Request; use React\Http\Response; use Silex\Application as BaseApplication; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class Application extends BaseApplication { public function __construct() { parent::__construct(); $app = $this; $this['controllers_factory'] = function () use ($app) { return new ControllerCollection($app['route_factory']); }; } public function __invoke(Request $request, Response $response) { $sfRequest = $this->buildSymfonyRequest($request, $response); $this->handle($sfRequest); } private function buildSymfonyRequest(Request $request, Response $response) { $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod()); $sfRequest->attributes->set('react.espresso.request', $request); $sfRequest->attributes->set('react.espresso.response', $response); return $sfRequest; } }
<?php namespace React\Espresso; use React\Http\Request; use React\Http\Response; use Silex\Application as BaseApplication; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class Application extends BaseApplication { public function __construct() { parent::__construct(); $this['controllers'] = $this->share(function () { return new ControllerCollection(); }); } public function __invoke(Request $request, Response $response) { $sfRequest = $this->buildSymfonyRequest($request, $response); $this->handle($sfRequest); } private function buildSymfonyRequest(Request $request, Response $response) { $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod()); $sfRequest->attributes->set('react.espresso.request', $request); $sfRequest->attributes->set('react.espresso.response', $response); return $sfRequest; } }
Refactor Partitioner class: add class hierarchy.
var util = require('util'); var _ = require('lodash'); 'use strict'; var Partitioner = function () { } var DefaultPartitioner = function () { } util.inherits(DefaultPartitioner, Partitioner); DefaultPartitioner.prototype.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } var RandomPartitioner = function () { } util.inherits(RandomPartitioner, Partitioner); RandomPartitioner.prototype.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } var KeyedPartitioner = function () { } util.inherits(KeyedPartitioner, Partitioner); // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. KeyedPartitioner.prototype.hashCode = function(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } KeyedPartitioner.prototype.getPartition = function (partitions, key) { key = key || '' var index = this.hashCode(key) % partitions.length; return partitions[index]; } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
var _ = require('lodash'); 'use strict'; function DefaultPartitioner() { this.getPartition = function (partitions) { if (partitions && _.isArray(partitions) && partitions.length > 0) { return partitions[0]; } else { return 0; } } } function RandomPartitioner() { this.getPartition = function (partitions) { return partitions[Math.floor(Math.random() * partitions.length)]; } } function KeyedPartitioner() { // Taken from oid package (Dan Bornstein) // Copyright The Obvious Corporation. function hashCode(string) { var hash = 0; var length = string.length; for (var i = 0; i < length; i++) { hash = ((hash * 31) + string.charCodeAt(i)) & 0x7fffffff; } return (hash === 0) ? 1 : hash; } this.getPartition = function (partitions, key) { key = key || '' var index = hashCode(key) % partitions.length; return partitions[index]; } } exports.DefaultPartitioner = DefaultPartitioner; exports.RandomPartitioner = RandomPartitioner; exports.KeyedPartitioner = KeyedPartitioner;
Clean up import auto mappings tests
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from integration.ggrc.converters import TestCase from integration.ggrc.generator import ObjectGenerator class TestBasicCsvImport(TestCase): def setUp(self): TestCase.setUp(self) self.generator = ObjectGenerator() self.client.get("/login") def test_basic_automappings(self): filename = "automappings.csv" response = self.import_file(filename) data = [{ "object_name": "Program", "filters": { "expression": { "left": "title", "op": {"name": "="}, "right": "program 1", }, }, "fields": "all", }] response = self.export_csv(data) for i in range(1, 8): self.assertIn("reg-{}".format(i), response.data) self.assertIn("control-{}".format(i), response.data)
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> from ggrc.models import Relationship from ggrc.converters import errors from integration.ggrc.converters import TestCase from integration.ggrc.generator import ObjectGenerator class TestBasicCsvImport(TestCase): def setUp(self): TestCase.setUp(self) self.generator = ObjectGenerator() self.client.get("/login") def test_basic_automappings(self): filename = "automappings.csv" response = self.import_file(filename) data = [{ "object_name": "Program", "filters": { "expression": { "left": "title", "op": {"name": "="}, "right": "program 1", }, }, "fields": "all", }] response = self.export_csv(data) for i in range(1, 8): self.assertIn("reg-{}".format(i), response.data) self.assertIn("control-{}".format(i), response.data)
Fix in award complaint view
# -*- coding: utf-8 -*- from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.openeu.views.award_complaint import TenderEUAwardComplaintResource @optendersresource(name='esco.EU:Tender Award Complaints', collection_path='/tenders/{tender_id}/awards/{award_id}/complaints', path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}', procurementMethodType='esco.EU', description="Tender ESCO EU Award complaints") class TenderESCOEUAwardComplaintResource(TenderEUAwardComplaintResource): """ Tender ESCO EU Award Complaint Resource """
# -*- coding: utf-8 -*- from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.openeu.views.award_complaint import TenderEUAwardComplaintResource @optendersresource(name='esco.EU:TenderAward Complaints', collection_path='/tenders/{tender_id}/awards/{award_id}/complaints', path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}', procurementMethodType='esco.EU', description="Tender ESCO EU Award complaints") class TenderESCOEUAwardComplaintResource(TenderEUAwardComplaintResource): """ Tender ESCO EU Award Complaint Resource """
Clean up all subscriptions when socket closes
package socket import ( "time" "net/http" "github.com/gorilla/websocket" "app/hub" "app/message" ) var upgrader = websocket.Upgrader{} func writeSocket(socket *websocket.Conn, c hub.Connection) { defer socket.Close() for { m := <- c.Out socket.WriteJSON(&m) } } // Handler handles websocket connections at /ws func Handler(w http.ResponseWriter, r *http.Request) { socket, err := upgrader.Upgrade(w, r, nil) if err != nil { panic(err) } defer socket.Close() c := hub.NewConnection() defer hub.UnsubscribeAll(c) go writeSocket(socket, c) for { m := message.SocketMessage{} m.CreatedAt = time.Now().UTC() socket.ReadJSON(&m) switch m.Action { case "publish": hub.Publish(m) case "subscribe": hub.Subscribe(m.Event, c) case "unsubscribe": hub.Unsubscribe(m.Event, c) case "unsubscribe:all": hub.UnsubscribeAll(c) } } }
package socket import ( "time" "net/http" "github.com/gorilla/websocket" "app/hub" "app/message" ) var upgrader = websocket.Upgrader{} func writeSocket(socket *websocket.Conn, c hub.Connection) { defer socket.Close() for { m := <- c.Out socket.WriteJSON(&m) } } // Handler handles websocket connections at /ws func Handler(w http.ResponseWriter, r *http.Request) { socket, err := upgrader.Upgrade(w, r, nil) if err != nil { panic(err) } defer socket.Close() c := hub.NewConnection() go writeSocket(socket, c) for { m := message.SocketMessage{} m.CreatedAt = time.Now().UTC() socket.ReadJSON(&m) switch m.Action { case "publish": hub.Publish(m) case "subscribe": hub.Subscribe(m.Event, c) case "unsubscribe": hub.Unsubscribe(m.Event, c) case "unsubscribe:all": hub.UnsubscribeAll(c) } } }
Add support for Webpack dev server
var fse = require("fs-extra"); function WebpackCopyAfterBuildPlugin(mappings) { this._mappings = mappings || {}; } WebpackCopyAfterBuildPlugin.prototype.apply = function(compiler) { var mappings = this._mappings; compiler.plugin("done", function(stats) { var statsJson = stats.toJson(); var chunks = statsJson.chunks; chunks.forEach(function(chunk) { var bundleName = chunk.names[0]; var mapping = mappings[bundleName]; if (mapping) { var devServer = compiler.options.devServer; var outputPath; if (devServer && devServer.contentBase) { outputPath = devServer.contentBase; } else { outputPath = compiler.options.output.path; } var webpackContext = compiler.options.context; var chunkHashFileName = chunk.files[0]; var from = webpackContext + "/" + outputPath + "/" + chunkHashFileName; var to = webpackContext + "/" + outputPath + "/" + mapping; fse.copySync(from, to); } }); }); }; module.exports = WebpackCopyAfterBuildPlugin;
var fse = require("fs-extra"); function WebpackCopyAfterBuildPlugin(mappings) { this._mappings = mappings || {}; } WebpackCopyAfterBuildPlugin.prototype.apply = function(compiler) { var mappings = this._mappings; compiler.plugin("done", function(stats) { var statsJson = stats.toJson(); var chunks = statsJson.chunks; chunks.forEach(function(chunk) { var bundleName = chunk.names[0]; var mapping = mappings[bundleName]; if (mapping) { var outputPath = compiler.options.output.path; var webpackContext = compiler.options.context; var chunkHashFileName = chunk.files[0]; var from = webpackContext + "/" + outputPath + "/" + chunkHashFileName; var to = webpackContext + "/" + outputPath + "/" + mapping; fse.copySync(from, to); } }); }); }; module.exports = WebpackCopyAfterBuildPlugin;
refactor: Remove added code to go back to the simpler approach for now, at least for this PR.
import { name as $name } from '../util/symbols'; import Component from './component'; import uniqueId from '../util/unique-id'; export default function (name, opts) { const { customElements } = window; if (!customElements) { throw new Error('Skate requires native custom element support or a polyfill.'); } // Unique IDs. if (!name || customElements.get(name)) { name = uniqueId(name); } // Object literals. if (typeof opts === 'object') { opts = Component.extend(opts); } // This allows us to check this before instantiating the custom element to // find its name from the constructor in the vdom module, thus improving // performance but still falling back to a robust method. opts[$name] = name; customElements.define(name, opts, opts.extends ? { extends: opts.extends } : null); return opts; }
import { name as $name } from '../util/symbols'; import Component from './component'; import uniqueId from '../util/unique-id'; export default function (name, opts) { const { customElements } = window; if (!customElements) { throw new Error('Skate requires native custom element support or a polyfill.'); } // DEPRECATED // // The recommended way now is to pass a class that defines the "id" prop. if (typeof name === 'string') { opts.id = name; } // Once we remove the passing of a name we can remove the check for it here. if (!opts.id || customElements.get(opts.id)) { opts.id = uniqueId(opts.id); } // DEPRECATED // // Object literals. if (typeof opts === 'object') { opts = Component.extend(opts); } // This allows us to check this before instantiating the custom element to // find its name from the constructor in the vdom module, thus improving // performance but still falling back to a robust method. opts[$name] = opts.id; customElements.define(opts.id, opts, opts.extends ? { extends: opts.extends } : null); return opts; }
[IMP] Rename Objects to Models in module description
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program 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. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Models Graph", "version": "0.1", "depends": ["base"], "author": "Smile", "license": 'AGPL-3', "description": """ Generate Models Graph Suggestions & Feedback to: corentin.pouhet-brunerie@smile.fr """, "website": "http://www.smile.fr", "category": "Hidden", "sequence": 32, "data": [ "wizard/ir_model_graph_wizard_view.xml", ], "demo": [], 'test': [], "auto_install": True, "installable": True, "application": False, }
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program 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. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Objects Graph", "version": "0.1", "depends": ["base"], "author": "Smile", "license": 'AGPL-3', "description": """ Generate Objects Graph Suggestions & Feedback to: corentin.pouhet-brunerie@smile.fr """, "website": "http://www.smile.fr", "category": "Hidden", "sequence": 32, "data": [ "wizard/ir_model_graph_wizard_view.xml", ], "demo": [], 'test': [], "auto_install": True, "installable": True, "application": False, }
Fix duplicate absolute path names for resources
<?php namespace Mw\Metamorph\Step; use Mw\Metamorph\Domain\Model\MorphConfiguration; use Mw\Metamorph\Domain\Service\MorphExecutionState; use Mw\Metamorph\Transformation\AbstractTransformation; use Mw\Metamorph\Transformation\Progressible; use Mw\Metamorph\Transformation\ProgressibleTrait; use TYPO3\Flow\Annotations as Flow; use TYPO3\Flow\Package\PackageManagerInterface; use TYPO3\Flow\Utility\Files; class CreateResources extends AbstractTransformation implements Progressible { use ProgressibleTrait; /** * @var PackageManagerInterface * @Flow\Inject */ protected $packageManager; public function execute(MorphConfiguration $configuration, MorphExecutionState $state) { $this->startProgress( 'Migrating resources', count($configuration->getResourceMappingContainer()->getResourceMappings()) ); foreach ($configuration->getResourceMappingContainer()->getResourceMappings() as $resourceMapping) { $targetFilePath = $resourceMapping->getTargetFile(); $targetDirectory = dirname($targetFilePath); Files::createDirectoryRecursively($targetDirectory); copy($resourceMapping->getSourceFile(), $targetFilePath); $this->advanceProgress(); } $this->finishProgress(); } }
<?php namespace Mw\Metamorph\Step; use Mw\Metamorph\Domain\Model\MorphConfiguration; use Mw\Metamorph\Domain\Service\MorphExecutionState; use Mw\Metamorph\Transformation\AbstractTransformation; use Mw\Metamorph\Transformation\Progressible; use Mw\Metamorph\Transformation\ProgressibleTrait; use TYPO3\Flow\Annotations as Flow; use TYPO3\Flow\Package\PackageManagerInterface; use TYPO3\Flow\Utility\Files; class CreateResources extends AbstractTransformation implements Progressible { use ProgressibleTrait; /** * @var PackageManagerInterface * @Flow\Inject */ protected $packageManager; public function execute(MorphConfiguration $configuration, MorphExecutionState $state) { $this->startProgress( 'Migrating resources', count($configuration->getResourceMappingContainer()->getResourceMappings()) ); foreach ($configuration->getResourceMappingContainer()->getResourceMappings() as $resourceMapping) { $package = $this->packageManager->getPackage($resourceMapping->getPackage()); $targetFilePath = Files::concatenatePaths( [$package->getPackagePath(), $resourceMapping->getTargetFile()] ); $targetDirectory = dirname($targetFilePath); Files::createDirectoryRecursively($targetDirectory); copy($resourceMapping->getSourceFile(), $targetFilePath); $this->advanceProgress(); } $this->finishProgress(); } }
Test server existence via a socket connection
import bottle import threading import socket import time as _time def start_bottle_server(app, port, **kwargs): server_thread = ServerThread(app, port, kwargs) server_thread.daemon = True server_thread.start() ok = False for i in range(10): try: conn = socket.create_connection(('127.0.0.1', port), 0.1) ok = True break except socket.error as e: _time.sleep(0.1) if not ok: import warnings warnings.warn('Server did not start after 1 second') class ServerThread(threading.Thread): def __init__(self, app, port, server_kwargs): threading.Thread.__init__(self) self.app = app self.port = port self.server_kwargs = server_kwargs def run(self): bottle.run(self.app, host='localhost', port=self.port, **self.server_kwargs) # http://code.activestate.com/recipes/106033-deep-list-to-convert-a-nested-tuple-of-tuples/ def listit(t): return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
import bottle import threading import time as _time def start_bottle_server(app, port, **kwargs): server_thread = ServerThread(app, port, kwargs) server_thread.daemon = True server_thread.start() _time.sleep(0.1) class ServerThread(threading.Thread): def __init__(self, app, port, server_kwargs): threading.Thread.__init__(self) self.app = app self.port = port self.server_kwargs = server_kwargs def run(self): bottle.run(self.app, host='localhost', port=self.port, **self.server_kwargs) # http://code.activestate.com/recipes/106033-deep-list-to-convert-a-nested-tuple-of-tuples/ def listit(t): return list(map(listit, t)) if isinstance(t, (list, tuple)) else t
Remove api key field from GetACcountDetailsMethod. It's already defined in the parent class.
/* * Copyright 2012 Ecwid, 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.ecwid.mailchimp.method.helper; import java.util.List; import com.ecwid.mailchimp.MailChimpMethod; /** * See http://apidocs.mailchimp.com/api/1.3/getaccountdetails.func.php * * @author Matt Farmer <matt@frmr.me> */ @MailChimpMethod.Name("getAccountDetails") public class GetAccountDetailsMethod extends MailChimpMethod<AccountDetails> { @Field public List<String> exclude; @Override public Class<AccountDetails> getResultType() { return AccountDetails.class; } }
/* * Copyright 2012 Ecwid, 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.ecwid.mailchimp.method.helper; import java.util.List; import com.ecwid.mailchimp.MailChimpMethod; /** * See http://apidocs.mailchimp.com/api/1.3/getaccountdetails.func.php * * @author Matt Farmer <matt@frmr.me> */ @MailChimpMethod.Name("getAccountDetails") public class GetAccountDetailsMethod extends MailChimpMethod<AccountDetails> { @Field public String apikey; @Field public List<String> exclude; @Override public Class<AccountDetails> getResultType() { return AccountDetails.class; } }
Fix standalone timeline (show community timeline again)
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { hydrateStore } from '../actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; import PublicTimeline from '../features/standalone/community_timeline'; import HashtagTimeline from '../features/standalone/hashtag_timeline'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); const initialStateContainer = document.getElementById('initial-state'); if (initialStateContainer !== null) { const initialState = JSON.parse(initialStateContainer.textContent); store.dispatch(hydrateStore(initialState)); } export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, hashtag: PropTypes.string, }; render () { const { locale, hashtag } = this.props; let timeline; if (hashtag) { timeline = <HashtagTimeline hashtag={hashtag} />; } else { timeline = <PublicTimeline />; } return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> {timeline} </Provider> </IntlProvider> ); } }
import React from 'react'; import { Provider } from 'react-redux'; import PropTypes from 'prop-types'; import configureStore from '../store/configureStore'; import { hydrateStore } from '../actions/store'; import { IntlProvider, addLocaleData } from 'react-intl'; import { getLocale } from '../locales'; import PublicTimeline from '../features/standalone/public_timeline'; import HashtagTimeline from '../features/standalone/hashtag_timeline'; const { localeData, messages } = getLocale(); addLocaleData(localeData); const store = configureStore(); const initialStateContainer = document.getElementById('initial-state'); if (initialStateContainer !== null) { const initialState = JSON.parse(initialStateContainer.textContent); store.dispatch(hydrateStore(initialState)); } export default class TimelineContainer extends React.PureComponent { static propTypes = { locale: PropTypes.string.isRequired, hashtag: PropTypes.string, }; render () { const { locale, hashtag } = this.props; let timeline; if (hashtag) { timeline = <HashtagTimeline hashtag={hashtag} />; } else { timeline = <PublicTimeline />; } return ( <IntlProvider locale={locale} messages={messages}> <Provider store={store}> {timeline} </Provider> </IntlProvider> ); } }
Set static file Content-Length header
Router.route('/media', {name: 'mediaMenu'}); Router.route('/media/static/:filepath*', function () { if (settings.findOne({key: 'mediainternalserver'}).value) { var fs = Npm.require('fs'); var filepath = settings.findOne({key: 'mediadir'}).value + '/' + this.params.filepath; try { var stats = fs.statSync(filepath); } catch (e) { this.next(); return; } if (!stats.isFile()) { this.next(); return; } var headers = { 'Cache-Control': 'max-age=2592000', // Cache for 30 days. 'Content-Length': stats.size }; this.response.writeHead(200, headers); var stream = fs.createReadStream(filepath); return stream.pipe(this.response); } }, {where: 'server'});
Router.route('/media', {name: 'mediaMenu'}); Router.route('/media/static/:filepath*', function () { if (settings.findOne({key: 'mediainternalserver'}).value) { // var mime = Npm.require('mime'); var fs = Npm.require('fs'); var filepath = settings.findOne({key: 'mediadir'}).value + '/' + this.params.filepath; try { var stats = fs.statSync(filepath); } catch (e) { this.next(); return; } if (!stats.isFile()) { this.next(); return; } var headers = { 'Cache-Control': 'max-age=2592000' // Cache for 30 days. }; this.response.writeHead(200, headers); var stream = fs.createReadStream(filepath); return stream.pipe(this.response); } }, {where: 'server'});
Add braces to every 'if' block
/*global angular */ (function (angular) { // -- MODULE DECLARATION angular.module("ngFilesizeFilter", []) // FILTER .filter("filesize", function () { /** * An array of units, starting at bytes and ending with yottabytes. */ var units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; return function(bytes, precision) { // validate 'bytes' if (isNaN(parseFloat(bytes))) { return "-"; } if (bytes < 1) { return "0 B"; } // validate 'precision' if (isNaN(precision)) { precision = 1; } var unitIndex = Math.floor(Math.log(bytes) / Math.log(1000)), value = bytes / Math.pow(1000, unitIndex); return value.toFixed(precision) + " " + units[unitIndex]; }; }); })(angular);
/*global angular */ (function (angular) { // -- MODULE DECLARATION angular.module("ngFilesizeFilter", []) // FILTER .filter("filesize", function () { /** * An array of units, starting at bytes and ending with yottabytes. */ var units = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; return function(bytes, precision) { if (isNaN(parseFloat(bytes))) return "-"; if (isNaN(precision)) precision = 1; if (bytes < 1) return "0 B"; var unitIndex = Math.floor(Math.log(bytes) / Math.log(1000)), value = bytes / Math.pow(1000, unitIndex); return value.toFixed(precision) + " " + units[unitIndex]; }; }); })(angular);
Update to use response object for setting headers Signed off by : Adam Pilkington apilkington@uk.ibm.com
/******************************************************************************* * Copyright (c) 2017 IBM Corp. * * 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.ibm.liberty.starter.api; import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException { MultivaluedMap<String, Object> headers = res.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Methods", "GET, POST"); headers.add("Access-Control-Max-Age", "86400"); headers.add("Access-Control-Allow-Credentials", "true"); headers.add("Access-Control-Allow-Headers", "Content-Type"); } }
/******************************************************************************* * Copyright (c) 2017 IBM Corp. * * 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.ibm.liberty.starter.api; import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException { MultivaluedMap<String, String> headers = req.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Methods", "GET, POST"); headers.add("Access-Control-Max-Age", "86400"); headers.add("Access-Control-Allow-Credentials", "true"); headers.add("Access-Control-Allow-Headers", "Content-Type"); } }
Mark test as xfail so that releases can be cut
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
Use backend_id instead of Waldur UUID for OpenStack
import template from './appstore-field-select-openstack-tenant.html'; class AppstoreFieldSelectOpenstackTenantController { // @ngInject constructor(ncUtilsFlash, openstackTenantsService, currentStateService) { this.ncUtilsFlash = ncUtilsFlash; this.openstackTenantsService = openstackTenantsService; this.currentStateService = currentStateService; } $onInit() { this.loading = true; this.currentStateService.getProject().then(project => { this.openstackTenantsService.getAll({ field: ['name', 'uuid'], project_uuid: project.uuid, }).then(tenants => { this.choices = tenants.map(tenant => ({ display_name: tenant.name, value: `Tenant UUID: ${tenant.backend_id}. Name: ${tenant.name}` })); this.loading = false; this.loaded = true; }) .catch(response => { this.ncUtilsFlash.errorFromResponse(response, gettext('Unable to get list of OpenStack tenants.')); this.loading = false; this.loaded = false; }); }); } } const appstoreFieldSelectOpenstackTenant = { template, bindings: { field: '<', model: '<' }, controller: AppstoreFieldSelectOpenstackTenantController, }; export default appstoreFieldSelectOpenstackTenant;
import template from './appstore-field-select-openstack-tenant.html'; class AppstoreFieldSelectOpenstackTenantController { // @ngInject constructor(ncUtilsFlash, openstackTenantsService, currentStateService) { this.ncUtilsFlash = ncUtilsFlash; this.openstackTenantsService = openstackTenantsService; this.currentStateService = currentStateService; } $onInit() { this.loading = true; this.currentStateService.getProject().then(project => { this.openstackTenantsService.getAll({ field: ['name', 'uuid'], project_uuid: project.uuid, }).then(tenants => { this.choices = tenants.map(tenant => ({ display_name: tenant.name, value: `UUID: ${tenant.uuid}. Name: ${tenant.name}` })); this.loading = false; this.loaded = true; }) .catch(response => { this.ncUtilsFlash.errorFromResponse(response, gettext('Unable to get list of OpenStack tenants.')); this.loading = false; this.loaded = false; }); }); } } const appstoreFieldSelectOpenstackTenant = { template, bindings: { field: '<', model: '<' }, controller: AppstoreFieldSelectOpenstackTenantController, }; export default appstoreFieldSelectOpenstackTenant;
Check price exists before using it
from django.db import models from django.db.models.deletion import PROTECT from django_extensions.db.fields import AutoSlugField class Workshop(models.Model): event = models.ForeignKey('events.Event', PROTECT, related_name='workshops') applicant = models.ForeignKey('cfp.Applicant', related_name='workshops') title = models.CharField(max_length=80) slug = AutoSlugField(populate_from="title", unique=True) about = models.TextField() abstract = models.TextField() extra_info = models.TextField(blank=True) skill_level = models.ForeignKey('cfp.AudienceSkillLevel', PROTECT) starts_at = models.DateTimeField() duration_hours = models.DecimalField(max_digits=3, decimal_places=1) tickets_link = models.URLField(blank=True) price = models.PositiveIntegerField(blank=True, null=True) @property def approximate_euro_price(self): return int(self.price / 7.5) if self.price else None
from django.db import models from django.db.models.deletion import PROTECT from django_extensions.db.fields import AutoSlugField class Workshop(models.Model): event = models.ForeignKey('events.Event', PROTECT, related_name='workshops') applicant = models.ForeignKey('cfp.Applicant', related_name='workshops') title = models.CharField(max_length=80) slug = AutoSlugField(populate_from="title", unique=True) about = models.TextField() abstract = models.TextField() extra_info = models.TextField(blank=True) skill_level = models.ForeignKey('cfp.AudienceSkillLevel', PROTECT) starts_at = models.DateTimeField() duration_hours = models.DecimalField(max_digits=3, decimal_places=1) tickets_link = models.URLField(blank=True) price = models.PositiveIntegerField(blank=True, null=True) @property def approximate_euro_price(self): return int(self.price / 7.5)
Refactor user input story with padding parameter.
/** * User Input Component Stories. * * Site Kit by Google, Copyright 2021 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import { storiesOf } from '@storybook/react'; /** * Internal dependencies */ import UserInputApp from '../assets/js/components/user-input/UserInputApp'; import { CORE_USER } from '../assets/js/googlesitekit/datastore/user/constants'; import { WithTestRegistry } from '../tests/js/utils'; storiesOf( 'User Input', module ) .add( 'UserInputApp', () => { return ( <WithTestRegistry callback={ ( registry ) => { // Don't mark the user input as completed in this story. registry.dispatch( CORE_USER ).receiveUserInputState( 'missing' ); } } features={ [ 'userInput' ] }> <UserInputApp /> </WithTestRegistry> ); }, { padding: 0, } );
/** * User Input Component Stories. * * Site Kit by Google, Copyright 2021 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import { storiesOf } from '@storybook/react'; /** * Internal dependencies */ import UserInputApp from '../assets/js/components/user-input/UserInputApp'; import { CORE_USER } from '../assets/js/googlesitekit/datastore/user/constants'; import { WithTestRegistry } from '../tests/js/utils'; storiesOf( 'User Input', module ) .add( 'UserInputApp', () => { return ( <WithTestRegistry callback={ ( registry ) => { // Don't mark the user input as completed in this story. registry.dispatch( CORE_USER ).receiveUserInputState( 'missing' ); } } features={ [ 'userInput' ] }> <div className="-googlesitekit-plugin-preview"> <UserInputApp /> </div> </WithTestRegistry> ); } );
Remove param from datapoint store
import _ from 'lodash' import Reflux from 'reflux' import StateMixin from'reflux-state-mixin' import DatapointActions from 'actions/DatapointActions' var DatapointStore = Reflux.createStore({ mixins: [StateMixin.store], listenables: DatapointActions, datapoints: { meta: null, raw: null }, getInitialState () { return this.datapoints }, // =========================================================================== // // API CALL HANDLERS // // =========================================================================== // // ============================ Fetch Datapoints ========================== // onFetchDatapoints () { this.setState({ raw: [] }) }, onFetchDatapointsCompleted (response) { this.datapoints.meta = response.meta this.datapoints.raw = response.objects this.setState(this.datapoints) }, onFetchDatapointsFailed (error) { this.setState({ error: error }) } }) export default DatapointStore
import _ from 'lodash' import Reflux from 'reflux' import StateMixin from'reflux-state-mixin' import DatapointActions from 'actions/DatapointActions' var DatapointStore = Reflux.createStore({ mixins: [StateMixin.store], listenables: DatapointActions, datapoints: { meta: null, raw: null, index: null }, getInitialState () { return this.datapoints }, // =========================================================================== // // API CALL HANDLERS // // =========================================================================== // // ============================ Fetch Datapoints ========================== // onFetchDatapoints () { this.setState({ raw: [] }) }, onFetchDatapointsCompleted (response) { this.datapoints.meta = response.meta this.datapoints.raw = response.objects this.datapoints.index = _.indexBy(this.datapoints.raw, 'id') this.setState(this.datapoints) }, onFetchDatapointsFailed (error) { this.setState({ error: error }) } }) export default DatapointStore
Speed up lookup of formatter by source type
from .formatter import * class FormatterRegistry(): def __init__(self): self.__formatters = [] self.__formatter_source_map = {} def populate(self): self.__formatters = [ ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(), JsonFormat(), PythonFormat(), RustFormat(), TerraformFormat() ] self.__formatter_source_map = dict((source, formatter) for formatter in self.__formatters for source in formatter.sources) @property def all(self): return self.__formatters @property def enabled(self): return [x for x in self.all if x.format_on_save] def by_view(self, view): source = view.scope_name(0).split(' ')[0].split('.')[1] return self.__formatter_source_map.get(source) def by_name(self, name): return next((x for x in self.all if x.name == name))
from .formatter import * class FormatterRegistry(): def __init__(self): self.__formatters = [] def populate(self): self.__formatters = [ ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(), JsonFormat(), PythonFormat(), RustFormat(), TerraformFormat() ] @property def all(self): return self.__formatters @property def enabled(self): return [x for x in self.all if x.format_on_save] def find(self, predicate, default=None): return next((x for x in self.all if predicate(x)), default) def by_view(self, view): source = view.scope_name(0).split(' ')[0].split('.')[1] return self.find(lambda x: source in x.sources) def by_name(self, name): return self.find(lambda x: x.name == name)
Make stable job IDs in ingest runs
import os import logging from servicelayer.jobs import Job from aleph.core import db, archive from aleph.model import Document from aleph.queues import ingest_entity log = logging.getLogger(__name__) def crawl_directory(collection, path, parent=None, job_id=None): """Crawl the contents of the given path.""" content_hash = None if not path.is_dir(): content_hash = archive.archive_file(path) foreign_id = path.name if parent is not None: foreign_id = os.path.join(parent.foreign_id, foreign_id) meta = {'file_name': path.name} document = Document.save(collection, parent=parent, foreign_id=foreign_id, content_hash=content_hash, meta=meta) db.session.commit() job_id = job_id or Job.random_id() ingest_entity(collection, document.to_proxy(), job_id=job_id) log.info("Crawl [%s]: %s -> %s", collection.id, path, document.id) if path.is_dir(): for child in path.iterdir(): crawl_directory(collection, child, document, job_id)
import os import logging from aleph.core import db, archive from aleph.model import Document from aleph.queues import ingest_entity log = logging.getLogger(__name__) def crawl_directory(collection, path, parent=None): """Crawl the contents of the given path.""" content_hash = None if not path.is_dir(): content_hash = archive.archive_file(path) foreign_id = path.name if parent is not None: foreign_id = os.path.join(parent.foreign_id, foreign_id) meta = {'file_name': path.name} document = Document.save(collection, parent=parent, foreign_id=foreign_id, content_hash=content_hash, meta=meta) db.session.commit() ingest_entity(collection, document.to_proxy()) log.info("Crawl [%s]: %s -> %s", collection.id, path, document.id) if path.is_dir(): for child in path.iterdir(): crawl_directory(collection, child, document)
Docs: Fix a typo in maximumNumberOfLines Closes gh-1660
/** * Requires the file to be at most the number of lines specified * * Type: `Integer` * * Values: * - `Integer`: file should be at most the number of lines specified * * #### Example * * ```js * "maximumNumberOfLines": 100 * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( typeof options === 'number', this.getOptionName() + ' option requires number value or should be removed' ); this._maximumNumberOfLines = options; }, getOptionName: function() { return 'maximumNumberOfLines'; }, check: function(file, errors) { var firstToken = file.getFirstToken(); var lastToken = file.getLastToken(); errors.assert.linesBetween({ token: firstToken, nextToken: lastToken, atMost: this._maximumNumberOfLines - 1, message: 'File must be at most ' + this._maximumNumberOfLines + ' lines long' }); } };
/** * Requires the file to be at most the number of lines specified * * Type: `Integer` * * Values: * - `Integer`: file should be at most the number of lines specified * * #### Example * * ```js * "maximumNumberOfLines": 100 * ``` */ var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(options) { assert( typeof options === 'number', this.getOptionName() + ' option requires number value or should be removed' ); this._maximumNumberOfLines = options; }, getOptionName: function() { return 'maximumNumberOfLines'; }, check: function(file, errors) { var firstToken = file.getFirstToken(); var lastToken = file.getLastToken(); errors.assert.linesBetween({ token: firstToken, nextToken: lastToken, atMost: this._maximumNumberOfLines - 1, message: 'File must be at most ' + this._maximumNumberOfLines + ' lines long' }); } };
FIX Does not update list on nested change
import { COMPONENT } from '../symbols'; import { defer } from '../utils'; function walk(node, Component, options, items = []) { Array.from(node.children).forEach((child) => { const component = child[COMPONENT]; if (component && component instanceof Component) { items.push(component); if (options.deep && options.nested) walk(child, Component, options, items); } else if (options.deep) walk(child, Component, options, items); }); return items; } export default (Component, options = {}) => () => (host, get, set) => { let items = []; set(items); const resolveItems = defer(() => { items = walk(host, Component, options); set(items); }); const refreshItems = defer(() => { set(items); }); new MutationObserver(resolveItems).observe(host, { childList: true, subtree: !!options.deep, }); if (options.observe !== false) { host.addEventListener('@change', ({ target }) => { if (target !== host && items && items.includes(target[COMPONENT])) { refreshItems(); } }); } resolveItems(); };
import { COMPONENT } from '../symbols'; import { defer } from '../utils'; function walk(node, Component, options, items = []) { Array.from(node.children).forEach((child) => { const component = child[COMPONENT]; if (component && component instanceof Component) { items.push(component); if (options.deep && options.nested) walk(child, Component, options, items); } else if (options.deep) walk(child, Component, options, items); }); return items; } export default (Component, options = {}) => () => (host, get, set) => { let items = []; set(items); const resolveItems = defer(() => { items = walk(host, Component, options); set(items); }); const refreshItems = defer(() => { items = items.slice(0); set(items); }); new MutationObserver(resolveItems).observe(host, { childList: true, subtree: !!options.deep, }); if (options.observe !== false) { host.addEventListener('@change', ({ target }) => { if (target !== host && items && items.includes(target[COMPONENT])) { refreshItems(); } }); } resolveItems(); };
Hide submenu on click sub menu item
import { HEADER_NAV_MOUSE_ENTER, HEADER_NAV_MOUSE_LEAVE, SET_HEADER_NAV } from '../constants/headerNav'; import { setCurrentAsset } from '../actions/assets'; import keyBy from 'lodash/keyBy'; export const setCurrentHeaderNav = headerNavID => dispatch => { dispatch({ type: SET_HEADER_NAV, payload: headerNavID }); }; export const headevNavMouseEnter = headerNavID => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_ENTER, payload: headerNavID }); }; export const headevNavMouseLeave = () => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_LEAVE }); }; export const headerNavClick = headerNavID => (dispatch, getState) => { const mapping = keyBy(getState().assetsToHeaderNavMapping, 'headerNavID')[headerNavID]; mapping && dispatch(setCurrentAsset(mapping.assetID)); dispatch(setCurrentHeaderNav(headerNavID)); dispatch(headevNavMouseLeave()); };
import { HEADER_NAV_MOUSE_ENTER, HEADER_NAV_MOUSE_LEAVE, SET_HEADER_NAV } from '../constants/headerNav'; import { setCurrentAsset } from '../actions/assets'; import keyBy from 'lodash/keyBy'; export const setCurrentHeaderNav = headerNavID => dispatch => { dispatch({ type: SET_HEADER_NAV, payload: headerNavID }); }; export const headevNavMouseEnter = headerNavID => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_ENTER, payload: headerNavID }); }; export const headevNavMouseLeave = () => dispatch => { dispatch({ type: HEADER_NAV_MOUSE_LEAVE }); }; export const headerNavClick = headerNavID => (dispatch, getState) => { const mapping = keyBy(getState().assetsToHeaderNavMapping, 'headerNavID')[headerNavID]; mapping && dispatch(setCurrentAsset(mapping.assetID)); dispatch(setCurrentHeaderNav(headerNavID)); };
Add reception of GPS_RAW_INT messages as demo
#!/usr/bin/env python ''' test mavlink messages Do not forget to precise the baudrate (default 115200) ''' import sys, struct, time, os from curses import ascii from pymavlink import mavutil from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--baudrate", type=int, help="master port baud rate", default=115200) parser.add_argument("--device", required=True, help="serial device") parser.add_argument("--source-system", dest='SOURCE_SYSTEM', type=int, default=255, help='MAVLink source system for this GCS') args = parser.parse_args() def wait_heartbeat(m): '''wait for a heartbeat so we know the target system IDs''' print("Waiting for APM heartbeat") msg = m.recv_match(type='HEARTBEAT', blocking=True) print("Heartbeat from APM (system %u component %u)" % (m.target_system, m.target_component)) # create a mavlink serial instance master = mavutil.mavlink_connection(args.device, baud=args.baudrate, source_system=args.SOURCE_SYSTEM) # wait for the heartbeat msg to find the system ID while True: wait_heartbeat(master) msg = master.recv_match(type='GPS_RAW_INT', blocking=False) print msg
#!/usr/bin/env python ''' test mavlink messages Do not forget to precise the baudrate (default 115200) ''' import sys, struct, time, os from curses import ascii from pymavlink import mavutil from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("--baudrate", type=int, help="master port baud rate", default=115200) parser.add_argument("--device", required=True, help="serial device") parser.add_argument("--source-system", dest='SOURCE_SYSTEM', type=int, default=255, help='MAVLink source system for this GCS') args = parser.parse_args() def wait_heartbeat(m): '''wait for a heartbeat so we know the target system IDs''' print("Waiting for APM heartbeat") msg = m.recv_match(type='HEARTBEAT', blocking=True) print("Heartbeat from APM (system %u component %u)" % (m.target_system, m.target_component)) # create a mavlink serial instance master = mavutil.mavlink_connection(args.device, baud=args.baudrate, source_system=args.SOURCE_SYSTEM) # wait for the heartbeat msg to find the system ID while True: wait_heartbeat(master)
Update the pipeline to take into account the outlier rejection method to compute the RPP
import sys import os import numpy as np from skcycling.utils import load_power_from_fit from skcycling.restoration import denoise from skcycling.power_profile import Rpp # The first input argument corresponding to the data path data_path = sys.argv[1] # The second input argument is the storage directory storage_path = sys.argv[2] # We can create a list of all the *.fit files present inside that directory # Create a list with the files to considered filenames = [] for root, dirs, files in os.walk(data_path): for file in files: if file.endswith('.fit'): filenames.append(os.path.join(root, file)) max_duration_rpp = 30 rpp_rider = Rpp(max_duration_rpp=max_duration_rpp) # Open each file and fit for idx_file, filename in enumerate(filenames): print 'Process file #{} over {}'.format(idx_file+1, len(filenames)) # Open the file power_ride = load_power_from_fit(filename) # Reject the outliers using thresholding method power_ride = denoise.outliers_rejection(power_ride) # Fit the ride rpp_rider.fit(power_ride) # Create a directory to store the data if it is not existing if not os.path.exists(storage_path): os.makedirs(storage_path) # Store the data somewhere np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
import sys import os import numpy as np from skcycling.utils import load_power_from_fit from skcycling.power_profile import Rpp # The first input argument corresponding to the data path data_path = sys.argv[1] # The second input argument is the storage directory storage_path = sys.argv[2] # We can create a list of all the *.fit files present inside that directory # Create a list with the files to considered filenames = [] for root, dirs, files in os.walk(data_path): for file in files: if file.endswith('.fit'): filenames.append(os.path.join(root, file)) max_duration_rpp = 30 rpp_rider = Rpp(max_duration_rpp=max_duration_rpp) # Open each file and fit for idx_file, filename in enumerate(filenames): print 'Process file #{} over {}'.format(idx_file+1, len(filenames)) # Open the file power_ride = load_power_from_fit(filename) # Fit the ride rpp_rider.fit(power_ride) # Create a directory to store the data if it is not existing if not os.path.exists(storage_path): os.makedirs(storage_path) # Store the data somewhere np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)
Add delete_min() and its helper func’s
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def _percolate_down(self, i): pass def _get_min_child(self, i): pass def delete_min(self): pass def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import division from __future__ import print_function class BinaryHeap(object): def __init__(self): # Put single zero as the 1st element, so that # integer division can be used in later methods. self.heap_ls = [0] self.current_size = 0 def _percolate_up(self, i): while i // 2 > 0: if self.heap_ls[i] < self.heap_ls[i // 2]: tmp = self.heap_ls[i // 2] self.heap_ls[i // 2] = self.heap_ls[i] self.heap_ls[i] = tmp i = i // 2 def insert(self, new_node): self.heap_ls.append(new_node) self.current_size += 1 self._percolate_up(self.current_size) def main(): pass if __name__ == '__main__': main()
Initialize working directory with root directory
<?php namespace Lauft\Behat\BashExtension\Context; /** * BashContext context for Behat BDD tool. * Provides bash base step definitions. */ class BashContext extends RawBashContext { /** @var string */ protected $rootDirectory; /** @var string */ protected $workingDir; /** @var Process */ protected $process; /** * @param string $rootDirectory */ public function __construct($rootDirectory = DIRECTORY_SEPARATOR) { $this->rootDirectory = $rootDirectory; $this->workingDir = $rootDirectory; $this->process = new Process(null); } /** * @When /^I run "([^"]*)"(?: with "([^"]*)")?$/ * * @param string $command * @param string $arguments */ public function iRunCommand($command, $arguments = '') { $arguments = strtr($arguments, array('\'' => '"')); $this->process->setWorkingDirectory($this->workingDir); $this->process->setCommandLine($command.' '.$arguments); $this->process->start(); $this->process->wait(); } }
<?php namespace Lauft\Behat\BashExtension\Context; /** * BashContext context for Behat BDD tool. * Provides bash base step definitions. */ class BashContext extends RawBashContext { /** @var string */ protected $rootDirectory; /** @var string */ protected $workingDir; /** @var Process */ protected $process; public function __construct($rootDirectory = DIRECTORY_SEPARATOR) { $this->rootDirectory = $rootDirectory; $this->process = new Process(null); } /** /** * @When /^I run "([^"]*)"(?: with "([^"]*)")?$/ * * @param string $command * @param string $arguments */ public function iRunCommand($command, $arguments = '') { $arguments = strtr($arguments, array('\'' => '"')); $this->process->setWorkingDirectory($this->workingDir); $this->process->setCommandLine($command.' '.$arguments); $this->process->start(); $this->process->wait(); } }
Fix breakage: conversion of tf.data was allowed too soon and broke the autograph notebook. PiperOrigin-RevId: 250764059
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Global configuration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import config_lib Action = config_lib.Action Convert = config_lib.Convert DoNotConvert = config_lib.DoNotConvert # This list is evaluated in order and stops at the first rule that tests True # for a definitely_convert of definitely_bypass call. CONVERSION_RULES = ( DoNotConvert('tensorflow'), # TODO(b/133417201): Remove. DoNotConvert('tensorflow_probability'), # TODO(b/130313089): Remove. DoNotConvert('numpy'), DoNotConvert('threading'), )
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Global configuration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import config_lib Action = config_lib.Action Convert = config_lib.Convert DoNotConvert = config_lib.DoNotConvert # This list is evaluated in order and stops at the first rule that tests True # for a definitely_convert of definitely_bypass call. CONVERSION_RULES = ( Convert('tensorflow.python.data.ops'), DoNotConvert('tensorflow'), # TODO(b/133417201): Remove. DoNotConvert('tensorflow_probability'), # TODO(b/130313089): Remove. DoNotConvert('numpy'), DoNotConvert('threading'), )
Remove non-working network topology panel
# Disable Floating IPs from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Completely remove panel Network->Network Topology topology_panel = project_dashboard.get_panel("network_topology") project_dashboard.unregister(topology_panel.__class__) # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
# Disable Floating IPs from openstack_dashboard.dashboards.project.access_and_security import tabs from openstack_dashboard.dashboards.project.instances import tables import horizon NO = lambda *x: False tabs.FloatingIPsTab.allowed = NO tabs.APIAccessTab.allowed = NO tables.AssociateIP.allowed = NO tables.SimpleAssociateIP.allowed = NO tables.SimpleDisassociateIP.allowed = NO project_dashboard = horizon.get_dashboard("project") # Completely remove panel Network->Routers routers_panel = project_dashboard.get_panel("routers") project_dashboard.unregister(routers_panel.__class__) # Completely remove panel Network->Networks networks_panel = project_dashboard.get_panel("networks") project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs # Remove "Volume Consistency Groups" tab from openstack_dashboard.dashboards.project.volumes import tabs tabs.CGroupsTab.allowed = NO
Allow port definition for spot2 config
<?php namespace OpenCFP\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Spot\Config as SpotConfig; use Spot\Locator as SpotLocator; class SpotServiceProvider implements ServiceProviderInterface { /** * {@inheritdoc} */ public function register(Application $app) { $app['spot'] = $app->share(function ($app) { $config = new SpotConfig(); $dbConfig = [ 'dbname' => $app->config('database.database'), 'user' => $app->config('database.user'), 'password' => $app->config('database.password'), 'host' => $app->config('database.host'), 'driver' => 'pdo_mysql' ]; if ($app->config('database.port') !== null) { $dbConfig['port'] = $app->config('database.port'); } $config->addConnection('mysql', $dbConfig); return new SpotLocator($config); }); } /** * {@inheritdoc} */ public function boot(Application $app) { } }
<?php namespace OpenCFP\Provider; use Silex\Application; use Silex\ServiceProviderInterface; use Spot\Config as SpotConfig; use Spot\Locator as SpotLocator; class SpotServiceProvider implements ServiceProviderInterface { /** * {@inheritdoc} */ public function register(Application $app) { $app['spot'] = $app->share(function ($app) { $config = new SpotConfig(); $config->addConnection('mysql', [ 'dbname' => $app->config('database.database'), 'user' => $app->config('database.user'), 'password' => $app->config('database.password'), 'host' => $app->config('database.host'), 'driver' => 'pdo_mysql' ]); return new SpotLocator($config); }); } /** * {@inheritdoc} */ public function boot(Application $app) { } }
Use stronger password in reset password test
import pytest from radar.validation.reset_password import ResetPasswordValidation from radar.validation.core import ValidationError from radar.tests.validation.helpers import validation_runner def test_valid(): obj = valid({ 'token': '12345', 'username': 'hello', 'password': '2irPtfNUURf8G', }) assert obj['token'] == '12345' assert obj['username'] == 'hello' assert obj['password'] == '2irPtfNUURf8G' def test_token_missing(): invalid({ 'username': 'hello', 'password': 'password', }) def test_username_missing(): invalid({ 'token': '12345', 'password': 'password', }) def test_password_missing(): invalid({ 'token': '12345', 'username': 'hello', }) def test_weak_password(): invalid({ 'token': '12345', 'username': 'hello', 'password': 'password', }) def invalid(obj, **kwargs): with pytest.raises(ValidationError) as e: valid(obj, **kwargs) return e def valid(obj, **kwargs): return validation_runner(dict, ResetPasswordValidation, obj, **kwargs)
import pytest from radar.validation.reset_password import ResetPasswordValidation from radar.validation.core import ValidationError from radar.tests.validation.helpers import validation_runner def test_valid(): obj = valid({ 'token': '12345', 'username': 'hello', 'password': 'password', }) assert obj['token'] == '12345' assert obj['username'] == 'hello' assert obj['password'] == 'password' def test_token_missing(): invalid({ 'username': 'hello', 'password': 'password', }) def test_username_missing(): invalid({ 'token': '12345', 'password': 'password', }) def test_password_missing(): invalid({ 'token': '12345', 'username': 'hello', }) def invalid(obj, **kwargs): with pytest.raises(ValidationError) as e: valid(obj, **kwargs) return e def valid(obj, **kwargs): return validation_runner(dict, ResetPasswordValidation, obj, **kwargs)
Remove accidental leftover deserialize() on abstract base class
<?php namespace CultuurNet\UDB3\Role\Events; use Broadway\Serializer\SerializableInterface; use ValueObjects\Identity\UUID; abstract class AbstractEvent implements SerializableInterface { const UUID = 'uuid'; /** * @var UUID */ private $uuid; /** * AbstractEvent constructor. * @param UUID $uuid */ public function __construct(UUID $uuid) { $this->uuid = $uuid; } /** * @return UUID */ public function getUuid() { return $this->uuid; } /** * @inheritdoc */ public function serialize() { return ['uuid' => $this->getUuid()->toNative()]; } }
<?php namespace CultuurNet\UDB3\Role\Events; use Broadway\Serializer\SerializableInterface; use ValueObjects\Identity\UUID; abstract class AbstractEvent implements SerializableInterface { const UUID = 'uuid'; /** * @var UUID */ private $uuid; /** * AbstractEvent constructor. * @param UUID $uuid */ public function __construct(UUID $uuid) { $this->uuid = $uuid; } /** * @return UUID */ public function getUuid() { return $this->uuid; } /** * @inheritdoc */ public static function deserialize(array $data) { return new static(new UUID($data['uuid'])); } /** * @inheritdoc */ public function serialize() { return ['uuid' => $this->getUuid()->toNative()]; } }
Fix an error accessing the twitter returned auth object
""" Command for getting the Twitter oauth access. http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/ """ from django.core.management.base import NoArgsCommand import tweepy class Command(NoArgsCommand): """ This is an implementation of script showed in the step 3 of the tutorial. """ help = 'Get access to your Twitter account' def handle_noargs(self, **options): CONSUMER_KEY = raw_input('Paste your Consumer Key here: ') CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ') auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.secure = True auth_url = auth.get_authorization_url() print 'Please authorize: ' + auth_url verifier = raw_input('PIN: ').strip() auth.get_access_token(verifier) print("ACCESS_KEY = '%s'" % auth.access_token) print("ACCESS_SECRET = '%s'" % auth.access_token_secret)
""" Command for getting the Twitter oauth access. http://talkfast.org/2010/05/31/twitter-from-the-command-line-in-python-using-oauth/ """ from django.core.management.base import NoArgsCommand import tweepy class Command(NoArgsCommand): """ This is an implementation of script showed in the step 3 of the tutorial. """ help = 'Get access to your Twitter account' def handle_noargs(self, **options): CONSUMER_KEY = raw_input('Paste your Consumer Key here: ') CONSUMER_SECRET = raw_input('Paste your Consumer Secret here: ') auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.secure = True auth_url = auth.get_authorization_url() print 'Please authorize: ' + auth_url verifier = raw_input('PIN: ').strip() auth.get_access_token(verifier) print("ACCESS_KEY = '%s'" % auth.access_token.key) print("ACCESS_SECRET = '%s'" % auth.access_token.secret)
Remove unused (moved) FFI function
"use strict"; // module Data.Ord exports.ordArrayImpl = function (f) { return function (xs) { return function (ys) { var i = 0; var xlen = xs.length; var ylen = ys.length; while (i < xlen && i < ylen) { var x = xs[i]; var y = ys[i]; var o = f(x)(y); if (o !== 0) { return o; } i++; } if (xlen === ylen) { return 0; } else if (xlen > ylen) { return -1; } else { return 1; } }; }; };
"use strict"; // module Data.Ord exports.ordArrayImpl = function (f) { return function (xs) { return function (ys) { var i = 0; var xlen = xs.length; var ylen = ys.length; while (i < xlen && i < ylen) { var x = xs[i]; var y = ys[i]; var o = f(x)(y); if (o !== 0) { return o; } i++; } if (xlen === ylen) { return 0; } else if (xlen > ylen) { return -1; } else { return 1; } }; }; }; exports.unsafeCompareImpl = function (lt) { return function (eq) { return function (gt) { return function (x) { return function (y) { return x < y ? lt : x > y ? gt : eq; }; }; }; }; };
Set base url to https
BLOG_TITLE = 'Svenv.nl' BLOG_DESCRIPTION = 'Blogposts about tech related subject like Unix, Linux, Docker and programming.' BASE_URL = 'https://svenv.nl' CONTACT_PAGE_PATH = 'contact' CONTACT_THANK_YOU_PAGE = '/thankyou' EMAIL = 'svenvandescheur@gmail.com' EMAIL_FROM = 'noreply@svenv.nl' SMTP_HOST = 'localhost' REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.OrderingFilter',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 12, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], }
BLOG_TITLE = 'Svenv.nl' BLOG_DESCRIPTION = 'Blogposts about tech related subject like Unix, Linux, Docker and programming.' BASE_URL = 'http://svenv.nl' CONTACT_PAGE_PATH = 'contact' CONTACT_THANK_YOU_PAGE = '/thankyou' EMAIL = 'svenvandescheur@gmail.com' EMAIL_FROM = 'noreply@svenv.nl' SMTP_HOST = 'localhost' REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.OrderingFilter',), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 12, 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], }
Remove events_type from alert test case
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], events_type='event', expected_alert=None): self.description = description # As a result of defining our test cases as class level variables # we need to copy each event so that other tests dont # mess with the same instance in memory self.events = AlertTestSuite.copy(events) assert any(isinstance(i, list) for i in self.events) is False, 'Test case events contains a sublist when it should not.' self.events_type = events_type self.expected_alert = expected_alert self.full_events = [] def run(self, alert_filename, alert_classname): alert_file_module = __import__(alert_filename) alert_class_attr = getattr(alert_file_module, alert_classname) alert_task = alert_class_attr() alert_task.run() return alert_task
Fix the name for Bangkok Kitchen
package net.rebworks.lunchy.domain.places; import net.rebworks.lunchy.domain.Place; import net.rebworks.lunchy.resources.LunchResource; import javax.inject.Inject; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; public class BangkokKitchen implements Place { private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("bangkokkitchen", "bkk", "bkgbg")); public static final String NAME = ALIASES.first(); private final UriInfo uriInfo; @Inject public BangkokKitchen(@Context final UriInfo uriInfo) { this.uriInfo = uriInfo; } @Override public String getName() { return "Bangkok Kitchen"; } @Override public SortedSet<String> getAliases() { return ALIASES; } @Override public URI getWebsite() { return URI.create("http://www.bkgbg.se/lunch"); } @Override public URI getUri() { return LunchResource.getPlaceURI(uriInfo, NAME); } }
package net.rebworks.lunchy.domain.places; import net.rebworks.lunchy.domain.Place; import net.rebworks.lunchy.resources.LunchResource; import javax.inject.Inject; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; public class BangkokKitchen implements Place { private static final TreeSet<String> ALIASES = new TreeSet<>(Arrays.asList("bangkokkitchen", "bkk", "bkgbg")); public static final String NAME = ALIASES.first(); private final UriInfo uriInfo; @Inject public BangkokKitchen(@Context final UriInfo uriInfo) { this.uriInfo = uriInfo; } @Override public String getName() { return NAME; } @Override public SortedSet<String> getAliases() { return ALIASES; } @Override public URI getWebsite() { return URI.create("http://www.bkgbg.se/lunch"); } @Override public URI getUri() { return LunchResource.getPlaceURI(uriInfo, NAME); } }
Add try-catch if no organism allowed
#!/usr/bin/env python from __future__ import print_function import argparse import json from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator if __name__ == '__main__': parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance') WAAuth(parser) parser.add_argument('email', help='User Email') args = parser.parse_args() wa = WebApolloInstance(args.apollo, args.username, args.password) try: gx_user = AssertUser(wa.users.loadUsers(email=args.email)) except Exception: returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True) gx_user = AssertUser(wa.users.loadUsers(email=args.email)) all_orgs = wa.organisms.findAllOrganisms() try: orgs = accessible_organisms(gx_user, all_orgs) except Exception: orgs = [] print(json.dumps(orgs, indent=2))
#!/usr/bin/env python from __future__ import print_function import argparse import json from webapollo import AssertUser, WAAuth, WebApolloInstance, accessible_organisms, PasswordGenerator if __name__ == '__main__': parser = argparse.ArgumentParser(description='List all organisms available in an Apollo instance') WAAuth(parser) parser.add_argument('email', help='User Email') args = parser.parse_args() wa = WebApolloInstance(args.apollo, args.username, args.password) try: gx_user = AssertUser(wa.users.loadUsers(email=args.email)) except Exception: returnData = wa.users.createUser(args.email, args.email, args.email, PasswordGenerator(12), role='user', addToHistory=True) gx_user = AssertUser(wa.users.loadUsers(email=args.email)) all_orgs = wa.organisms.findAllOrganisms() orgs = accessible_organisms(gx_user, all_orgs) print(json.dumps(orgs, indent=2))
fix(UserSwitcher): Stop most of the logic from using entwine
(function($){ function loadSwitcher() { var base = $('base').prop('href'); var isCMS = $('body').hasClass('cms') ? 1 : 0; $.get(base + 'userswitcher/UserSwitcherFormHTML/', {userswitchercms: isCMS}).done(function(data){ var $data = $(data); if (!$data.length) { return; } // Submit form on change $data.find('select').on('change', function() { $(this.form).submit(); }); // Hide submit button $data.find('.Actions').hide(); if($('body').hasClass('cms')){ $('.cms-login-status').append($data); }else{ $('body').append($data); } }); } function main() { var isCMS = $('body').hasClass('cms') ? 1 : 0; if (!$.entwine || !isCMS) { loadSwitcher(); } else { $.entwine('userswitcher', function($){ $('body').entwine({ onmatch : function(){ loadSwitcher(); this._super(); }, onunmatch: function() { this._super(); } }); }); } } main(); })(jQuery);
(function($){ $.entwine('userswitcher', function($){ $('form.userswitcher select').entwine({ onchange : function(){ this.parents('form:first').submit(); this._super(); } }); $('form.userswitcher .Actions').entwine({ onmatch : function(){ this.hide(); this._super(); } }); $('body').entwine({ onmatch : function(){ var base = $('base').prop('href'), isCMS = this.hasClass('cms') ? 1 : ''; $.get(base + 'userswitcher/UserSwitcherFormHTML/', {userswitchercms: isCMS}).done(function(data){ var body = $('body'); if(body.hasClass('cms')){ $('.cms-login-status').append(data); }else{ $('body').append(data); } }); this._super(); } }); }); })(jQuery);
Fix Call to undefined method Orchestra\Tenanti\Migrator\Factory::getModel() - Call model method instead of getModel
<?php namespace Orchestra\Tenanti\Console; use Symfony\Component\Console\Input\InputArgument; class TinkerCommand extends BaseCommand { /** * The console command name. * * @var string */ protected $name = 'tenanti:tinker'; /** * The console command description. * * @var string */ protected $description = 'Run tinker using tenant connection'; /** * Execute the console command. * * @return int */ public function handle() { $arguments = $this->getArgumentsWithDriver('id'); \tap($this->tenantDriver($arguments['driver']), static function ($tenanti) use ($arguments) { $tenanti->asDefaultConnection( $tenanti->model()->findOrFail($arguments['id']), 'tinker' ); }); $this->call('tinker'); return 0; } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ['driver', InputArgument::OPTIONAL, 'Tenant driver name.'], ['id', InputArgument::OPTIONAL, 'The entity ID.'], ]; } }
<?php namespace Orchestra\Tenanti\Console; use Symfony\Component\Console\Input\InputArgument; class TinkerCommand extends BaseCommand { /** * The console command name. * * @var string */ protected $name = 'tenanti:tinker'; /** * The console command description. * * @var string */ protected $description = 'Run tinker using tenant connection'; /** * Execute the console command. * * @return int */ public function handle() { $arguments = $this->getArgumentsWithDriver('id'); \tap($this->tenantDriver($arguments['driver']), static function ($tenanti) use ($arguments) { $tenanti->asDefaultConnection( $tenanti->getModel()->findOrFail($arguments['id']), 'tinker' ); }); $this->call('tinker'); return 0; } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return [ ['driver', InputArgument::OPTIONAL, 'Tenant driver name.'], ['id', InputArgument::OPTIONAL, 'The entity ID.'], ]; } }
Improve error reporting in API response.
package api import ( "net/http" "github.com/ibrt/go-oauto/oauto/config" "encoding/json" "fmt" "github.com/go-errors/errors" ) type ApiHandler func(config *config.Config, r *http.Request, baseURL string) (interface{}, error) func RegisterApiRoutes(config *config.Config) { http.HandleFunc("/api/authenticate", MakeHandlerFunc(config, HandleAuthenticate)) } func MakeHandlerFunc(config *config.Config, apiHandler ApiHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, fmt.Sprintf("Method '%v' is not acceptable.", r.Method), http.StatusMethodNotAllowed) return } if resp, err := apiHandler(config, r, fmt.Sprintf("http://%v:%v", config.RedirectHost, config.ServerPort)); err == nil { w.Header().Add("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) } else { http.Error(w, err.(*errors.Error).ErrorStack(), http.StatusInternalServerError) } } }
package api import ( "net/http" "github.com/ibrt/go-oauto/oauto/config" "encoding/json" "fmt" ) type ApiHandler func(config *config.Config, r *http.Request, baseURL string) (interface{}, error) func RegisterApiRoutes(config *config.Config) { http.HandleFunc("/api/authenticate", MakeHandlerFunc(config, HandleAuthenticate)) } func MakeHandlerFunc(config *config.Config, apiHandler ApiHandler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, fmt.Sprintf("Method '%v' is not acceptable.", r.Method), http.StatusMethodNotAllowed) return } if resp, err := apiHandler(config, r, fmt.Sprintf("http://%v:%v", config.RedirectHost, config.ServerPort)); err == nil { w.Header().Add("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(resp) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } } }
Fix global search placeholder text
from __future__ import unicode_literals from django import forms from utilities.forms import BootstrapMixin OBJ_TYPE_CHOICES = ( ('', 'All Objects'), ('Circuits', ( ('provider', 'Providers'), ('circuit', 'Circuits'), )), ('DCIM', ( ('site', 'Sites'), ('rack', 'Racks'), ('devicetype', 'Device types'), ('device', 'Devices'), )), ('IPAM', ( ('vrf', 'VRFs'), ('aggregate', 'Aggregates'), ('prefix', 'Prefixes'), ('ipaddress', 'IP addresses'), ('vlan', 'VLANs'), )), ('Secrets', ( ('secret', 'Secrets'), )), ('Tenancy', ( ('tenant', 'Tenants'), )), ) class SearchForm(BootstrapMixin, forms.Form): q = forms.CharField( label='Search', widget=forms.TextInput(attrs={'style': 'width: 350px'}) ) obj_type = forms.ChoiceField( choices=OBJ_TYPE_CHOICES, required=False, label='Type' )
from __future__ import unicode_literals from django import forms from utilities.forms import BootstrapMixin OBJ_TYPE_CHOICES = ( ('', 'All Objects'), ('Circuits', ( ('provider', 'Providers'), ('circuit', 'Circuits'), )), ('DCIM', ( ('site', 'Sites'), ('rack', 'Racks'), ('devicetype', 'Device types'), ('device', 'Devices'), )), ('IPAM', ( ('vrf', 'VRFs'), ('aggregate', 'Aggregates'), ('prefix', 'Prefixes'), ('ipaddress', 'IP addresses'), ('vlan', 'VLANs'), )), ('Secrets', ( ('secret', 'Secrets'), )), ('Tenancy', ( ('tenant', 'Tenants'), )), ) class SearchForm(BootstrapMixin, forms.Form): q = forms.CharField( label='Query', widget=forms.TextInput(attrs={'style': 'width: 350px'}) ) obj_type = forms.ChoiceField( choices=OBJ_TYPE_CHOICES, required=False, label='Type' )
Fix case on committee URL
<?php /******************************************************************************* * Copyright (c) 2015 Eclipse Foundation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christopher Guindon (Eclipse Foundation) - Initial implementation *******************************************************************************/ if (!defined('ABSPATH')) exit; ?> <ul class="nav navbar-nav navbar-right"> <!--<li><a href="./cfp.php">Call For Proposals</a></li>--> <li><a href="./index.php#registration">Register</a></li> <li><a href="./committee.php">Our Committee</a></li> <li><a href="./terms.php">Terms</a></li> <li><a href="./conduct.php">Code of Conduct</a></li> <li><a href="./index.php#schedule">Schedule</a></li> <li><a href="./index.php#sponsorship">Sponsorship</a></li> </ul>
<?php /******************************************************************************* * Copyright (c) 2015 Eclipse Foundation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Christopher Guindon (Eclipse Foundation) - Initial implementation *******************************************************************************/ if (!defined('ABSPATH')) exit; ?> <ul class="nav navbar-nav navbar-right"> <!--<li><a href="./cfp.php">Call For Proposals</a></li>--> <li><a href="./index.php#registration">Register</a></li> <li><a href="./Committee.php">Our Committee</a></li> <li><a href="./terms.php">Terms</a></li> <li><a href="./conduct.php">Code of Conduct</a></li> <li><a href="./index.php#schedule">Schedule</a></li> <li><a href="./index.php#sponsorship">Sponsorship</a></li> </ul>
Fix syntax for PHP 5.3
<?php /** * This file is part of cocur/slugify. * * (c) Florian Eckerstorfer <florian@eckerstorfer.co> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cocur\Slugify\Bridge\Bundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * CourSlugifyBundle * * @package cocur/slugify * @subpackage bridge * @author Florian Eckerstorfer <florian@eckerstorfer.co> * @copyright 2012-2014 Florian Eckerstorfer * @license http://www.opensource.org/licenses/MIT The MIT License */ class CocurSlugifyBundle extends Bundle { /** * {@inheritDoc} */ public function build(ContainerBuilder $container) { parent::build($container); $extension = new CocurSlugifyExtension(); $extension->load(array(), $container); $container->registerExtension($extension); } }
<?php /** * This file is part of cocur/slugify. * * (c) Florian Eckerstorfer <florian@eckerstorfer.co> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Cocur\Slugify\Bridge\Bundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * CourSlugifyBundle * * @package cocur/slugify * @subpackage bridge * @author Florian Eckerstorfer <florian@eckerstorfer.co> * @copyright 2012-2014 Florian Eckerstorfer * @license http://www.opensource.org/licenses/MIT The MIT License */ class CocurSlugifyBundle extends Bundle { /** * {@inheritDoc} */ public function build(ContainerBuilder $container) { parent::build($container); $extension = new CocurSlugifyExtension(); $extension->load([], $container); $container->registerExtension($extension); } }
Use new print function (part of patch 1031)
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted"
Remove out of scope method contract from EventApi
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent, CalendArt\AbstractCalendar; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier); /** * Make an event persistent within the provider * * @return void */ public function persist(AbstractEvent $event); }
<?php /** * This file is part of the CalendArt package * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. * * @copyright Wisembly * @license http://www.opensource.org/licenses/MIT-License MIT License */ namespace CalendArt\Adapter; use Doctrine\Common\Collections\Collection; use CalendArt\AbstractEvent, CalendArt\AbstractCalendar; /** * Handle the dialog with the adapter's api for its events * * @author Baptiste Clavié <baptiste@wisembly.com> */ interface EventApiInterface { /** * Get all the events available on the selected calendar * * @return Collection<AbstractEvent> */ public function getList(); /** * Returns the specific information for a given event * * @param mixed $identifier Identifier of the event to fetch * * @return AbstractEvent */ public function get($identifier); /** * Get the associated calendar for this api * * @return AbstractCalendar */ public function getCalendar(); /** * Make an event persistent within the provider * * @return void */ public function persist(AbstractEvent $event); }
Remove TODO from settings example. This work has been started with the Yaml settings file.
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
Index posts instead of employee titles to fix search results
from haystack import indexes from tx_salaries.models import Employee class EmployeeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) content_auto = indexes.EdgeNgramField(model_attr='position__person__name') compensation = indexes.FloatField(model_attr='compensation', null=True) title = indexes.CharField(model_attr='position__post__label', faceted=True) title_slug = indexes.CharField(model_attr='position__post__stats__slug', faceted=True) department = indexes.CharField(model_attr='position__organization__name', faceted=True) department_slug = indexes.CharField(model_attr='position__organization__stats__slug') entity = indexes.CharField(model_attr='position__organization__parent__name', faceted=True) entity_slug = indexes.CharField(model_attr='position__organization__parent__stats__slug') def get_model(self): return Employee
from haystack import indexes from tx_salaries.models import Employee class EmployeeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) content_auto = indexes.EdgeNgramField(model_attr='position__person__name') compensation = indexes.FloatField(model_attr='compensation', null=True) title = indexes.CharField(model_attr='title__name', faceted=True) title_slug = indexes.CharField(model_attr='title__stats__slug', faceted=True) department = indexes.CharField(model_attr='position__organization__name', faceted=True) department_slug = indexes.CharField(model_attr='position__organization__stats__slug') entity = indexes.CharField(model_attr='position__organization__parent__name', faceted=True) entity_slug = indexes.CharField(model_attr='position__organization__parent__stats__slug') def get_model(self): return Employee
Add a functional test for find_extension Change-Id: I351a1c1529beb3cae799650e1e57364b3521d00c
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types) def test_find(self): extension = self.conn.network.find_extension('external-net') self.assertEqual('Neutron external network', extension.name)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import six from openstack.tests.functional import base class TestExtension(base.BaseFunctionalTest): def test_list_and_find(self): extensions = list(self.conn.network.extensions()) self.assertGreater(len(extensions), 0) for ext in extensions: self.assertIsInstance(ext.name, six.string_types) self.assertIsInstance(ext.alias, six.string_types)
Convert everything other than assets to app config We're using Laravel's config resolving classes: ```PHP $config = $app->make('config'); $config->get('app.version'); // '5.7.0b2' ``` Former-commit-id: 950db1326fe3a417acb509d4d2b572fda0cdd100
<?php namespace Concrete\Core\Config; use Illuminate\Config\FileLoader; use Illuminate\Filesystem\Filesystem; class ConfigLoader extends FileLoader { protected $config; public function __construct(Filesystem $files, Config $config) { $this->config = $config; parent::__construct($files, DIR_APPLICATION . '/config'); $this->addNamespace('core', DIR_BASE . '/concrete/config'); } public function load($environment, $group, $namespace = null) { if (is_null($namespace)) { return array_replace_recursive( (array) parent::load($environment, $group, 'core'), (array) parent::load($environment, $group, $namespace) ); } return parent::load($environment, $group, $namespace); } }
<?php namespace Concrete\Core\Config; use Illuminate\Config\FileLoader; use Illuminate\Filesystem\Filesystem; class ConfigLoader extends FileLoader { protected $config; public function __construct(Filesystem $files, Config $config) { $this->config = $config; parent::__construct($files, DIR_APPLICATION . '/config'); $this->addNamespace('core', DIR_BASE . '/concrete/config'); } public function load($environment, $group, $namespace = null) { if (is_null($namespace)) { return array_replace_recursive( parent::load($environment, $group, 'core'), parent::load($environment, $group, $namespace) (array) parent::load($environment, $group, 'core'), (array) parent::load($environment, $group, $namespace) ); } return parent::load($environment, $group, $namespace); } }
Add template and remove company from insurance_us imports
# -*- coding: utf-8 -*- ############################################################################## # # Author: Dave Lasley <dave@laslabs.com> # Copyright: 2015 LasLabs, Inc [https://laslabs.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import medical_insurance_plan from . import medical_insurance_template
# -*- coding: utf-8 -*- ############################################################################## # # Author: Dave Lasley <dave@laslabs.com> # Copyright: 2015 LasLabs, Inc [https://laslabs.com] # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import medical_insurance_plan from . import medical_insurance_company
Use LinkedHashMap for deterministic order
package com.alibaba.json.bvt.issue_1100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import java.util.LinkedHashMap; import java.util.Map; /** * Created by wenshao on 05/05/2017. */ public class Issue1177_2 extends TestCase { public void test_for_issue() throws Exception { String text = "{\"a\":{\"x\":\"y\"},\"b\":{\"x\":\"y\"}}"; Map<String, Model> jsonObject = JSONObject.parseObject(text, new TypeReference<LinkedHashMap<String, Model>>(){}); System.out.println(JSON.toJSONString(jsonObject)); String jsonpath = "$..x"; String value="y2"; JSONPath.set(jsonObject, jsonpath, value); assertEquals("{\"a\":{\"x\":\"y2\"},\"b\":{\"x\":\"y2\"}}", JSON.toJSONString(jsonObject)); } public static class Model { public String x; } }
package com.alibaba.json.bvt.issue_1100; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONPath; import com.alibaba.fastjson.TypeReference; import junit.framework.TestCase; import java.util.Map; /** * Created by wenshao on 05/05/2017. */ public class Issue1177_2 extends TestCase { public void test_for_issue() throws Exception { String text = "{\"a\":{\"x\":\"y\"},\"b\":{\"x\":\"y\"}}"; Map<String, Model> jsonObject = JSONObject.parseObject(text, new TypeReference<Map<String, Model>>(){}); System.out.println(JSON.toJSONString(jsonObject)); String jsonpath = "$..x"; String value="y2"; JSONPath.set(jsonObject, jsonpath, value); assertEquals("{\"a\":{\"x\":\"y2\"},\"b\":{\"x\":\"y2\"}}", JSON.toJSONString(jsonObject)); } public static class Model { public String x; } }
Add ability to pass options to modules
<?php /* Plugin Name: Soil Plugin URI: https://roots.io/plugins/soil/ Description: Clean up WordPress markup, use relative URLs, nicer search URLs, and disable trackbacks Version: 3.1.0 Author: Roots Author URI: https://roots.io/ License: MIT License License URI: http://opensource.org/licenses/MIT */ namespace Roots\Soil; function load_modules() { global $_wp_theme_features; foreach (glob(__DIR__ . '/modules/*.php') as $file) { $feature = 'soil-' . basename($file, '.php'); if (isset($_wp_theme_features[$feature])) { $options = (array) $_wp_theme_features[$feature]; require_once $file; } } } add_action('after_setup_theme', __NAMESPACE__ . '\\load_modules');
<?php /* Plugin Name: Soil Plugin URI: https://roots.io/plugins/soil/ Description: Clean up WordPress markup, use relative URLs, nicer search URLs, and disable trackbacks Version: 3.1.0 Author: Roots Author URI: https://roots.io/ License: MIT License License URI: http://opensource.org/licenses/MIT */ namespace Roots\Soil; function load_modules() { foreach (glob(__DIR__ . '/modules/*.php') as $file) { if (current_theme_supports('soil-' . basename($file, '.php'))) { require_once $file; } } } add_action('after_setup_theme', __NAMESPACE__ . '\\load_modules');
Make `let` declarations put their value in the local frame
package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.FrameSlot; import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.TypeException; import org.hummingbirdlang.types.realize.InferenceVisitor; public class HBLetDeclarationNode extends HBStatementNode { private final String left; @Child private HBExpressionNode rightNode; public HBLetDeclarationNode(String left, HBExpressionNode rightNode) { this.left = left; this.rightNode = rightNode; } public void accept(InferenceVisitor visitor) throws TypeException { this.rightNode.accept(visitor); visitor.visit(this); } public String getLeft() { return this.left; } public HBExpressionNode getRightNode() { return this.rightNode; } @Override public Object executeGeneric(VirtualFrame frame) { Object value = this.rightNode.executeGeneric(frame); FrameSlot frameSlot = frame.getFrameDescriptor().findOrAddFrameSlot(this.left); frame.setObject(frameSlot, value); return null; } @Override public String toString() { return "let " + this.left + " = " + this.rightNode.toString(); } }
package org.hummingbirdlang.nodes; import com.oracle.truffle.api.frame.VirtualFrame; import org.hummingbirdlang.types.TypeException; import org.hummingbirdlang.types.realize.InferenceVisitor; public class HBLetDeclarationNode extends HBStatementNode { private final String left; @Child private HBExpressionNode rightNode; public HBLetDeclarationNode(String left, HBExpressionNode rightNode) { this.left = left; this.rightNode = rightNode; } public void accept(InferenceVisitor visitor) throws TypeException { this.rightNode.accept(visitor); visitor.visit(this); } public String getLeft() { return this.left; } public HBExpressionNode getRightNode() { return this.rightNode; } @Override public Object executeGeneric(VirtualFrame frame) { return null; } @Override public String toString() { return "let " + this.left + " = " + this.rightNode.toString(); } }
Enable Redux DevTools in dev
/* eslint global-require: 0 */ import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from '../modules/reducer'; import Immutable from 'immutable'; const middlewares = [thunk]; if ('production' !== process.env.NODE_ENV) { const createLogger = require('redux-logger'); const logger = createLogger({ stateTransformer: (state) => { const newState = {}; for (const i of Object.keys(state)) { if (Immutable.Iterable.isIterable(state[i])) { newState[i] = state[i].toJS(); } else { newState[i] = state[i]; } } return newState; }, }); middlewares.push(logger); } const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore); export default function configureStore(initialState) { return createStoreWithMiddleware( rootReducer, initialState, window.devToolsExtension && window.devToolsExtension() ); }
/* eslint global-require: 0 */ import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from '../modules/reducer'; import Immutable from 'immutable'; const middlewares = [thunk]; if ('production' !== process.env.NODE_ENV) { const createLogger = require('redux-logger'); const logger = createLogger({ stateTransformer: (state) => { const newState = {}; for (const i of Object.keys(state)) { if (Immutable.Iterable.isIterable(state[i])) { newState[i] = state[i].toJS(); } else { newState[i] = state[i]; } } return newState; }, }); middlewares.push(logger); } const createStoreWithMiddleware = applyMiddleware(...middlewares)(createStore); export default function configureStore(initialState) { return createStoreWithMiddleware(rootReducer, initialState); }
Rewrite previous migration in raw SQL We shouldn’t import models into migrations because if the model changes later down the line then the migration can’t be re-run at a later date (for example to rebuild a database from scratch). We don’t need to encode the content before storing it (we’ll always do that before rendering/sending) so we don’t need to use `BroadcastMessageTemplate`. And given that no past broadcasts will have personalisation, we don’t need to replace the personalisation in the template before rendering it. So we can just copy the raw content from the templates table.
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from notifications_utils.template import BroadcastMessageTemplate from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): conn = op.get_bind() results = conn.execute(sa.text(""" UPDATE broadcast_message SET content = templates_history.content FROM templates_history WHERE broadcast_message.content is NULL and broadcast_message.template_id = templates_history.id and broadcast_message.template_version = templates_history.version ; """)) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
""" Revision ID: 0336_broadcast_msg_content_2 Revises: 0335_broadcast_msg_content Create Date: 2020-12-04 15:06:22.544803 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.orm.session import Session from app.models import BroadcastMessage revision = '0336_broadcast_msg_content_2' down_revision = '0335_broadcast_msg_content' def upgrade(): session = Session(bind=op.get_bind()) broadcast_messages = session.query(BroadcastMessage).filter(BroadcastMessage.content == None) for broadcast_message in broadcast_messages: broadcast_message.content = broadcast_message.template._as_utils_template_with_personalisation( broadcast_message.personalisation ).content_with_placeholders_filled_in session.commit() op.alter_column('broadcast_message', 'content', nullable=False) def downgrade(): op.alter_column('broadcast_message', 'content', nullable=True)
:new: Add attached attribute to BottomTab
'use strict'; class BottomTab extends HTMLElement{ prepare(Name){ this.Name = Name this.attached = false return this } attachedCallback() { this.active = false this.attached = true this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.innerHTML = this.Name + ' ' this.appendChild(this.countSpan) } detachedCallback(){ this.attached = false } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } set count(value) { this.countSpan.textContent = value } } module.exports = BottomTab = document.registerElement('linter-bottom-tab', { prototype: BottomTab.prototype })
'use strict'; class BottomTab extends HTMLElement{ prepare(Name){ this.Name = Name return this } attachedCallback() { this.active = false this.classList.add('linter-tab') this.countSpan = document.createElement('span') this.countSpan.classList.add('count') this.countSpan.textContent = '0' this.innerHTML = this.Name + ' ' this.appendChild(this.countSpan) } get active() { return this._active } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } set count(value) { this.countSpan.textContent = value } } module.exports = BottomTab = document.registerElement('linter-bottom-tab', { prototype: BottomTab.prototype })
Fix typo in loging page causing fatal error Fix typo in loging page causing fatal error - Close `?>`
<?php defined('C5_EXECUTE') or die('Access denied.'); $form = Loader::helper('form'); ?> <div class='row'> <div class='span5'> <div class='control-group'> <label class='control-label' for="uName"> <?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?> </label> <div class='controls'> <?=$form->text('uName')?> </div> </div> <div class='control-group'> <label class='control-label' for="uPassword"> <?=t('Password')?> </label> <div class='controls'> <?=$form->password('uPassword')?> </div> </div> </div> <?=$form->hidden('rcID', $rcID); ?> <div class='span3 offset1'> <label class='checkbox'><?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?></label> <div class="help-block"><a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?></a></div> </div> </div> <div class='actions'> <button class='btn primary'><?=t('Sign In')?></button> </div>
<?php defined('C5_EXECUTE') or die('Access denied.'); $form = Loader::helper('form'); ?> <div class='row'> <div class='span5'> <div class='control-group'> <label class='control-label' for="uName"> <?=USER_REGISTRATION_WITH_EMAIL_ADDRESS?t('Email Address'):t('Username')?> </label> <div class='controls'> <?=$form->text('uName')?> </div> </div> <div class='control-group'> <label class='control-label' for="uPassword"> <?=t('Password')?> </label> <div class='controls'> <?=$form->password('uPassword')?> </div> </div> </div> <?=$form->hidden('rcID', $rcID); ?> <div class='span3 offset1'> <label class='checkbox'><?=$form->checkbox('uMaintainLogin',1)?> <?=t('Remain logged in to website.')?></label> <div class="help-block"><a href="<?=View::url('/login', 'concrete', 'forgot_password')?>"><?=t('Forgot Password?')?></a></div> </div> </div> <div class='actions'> <button class='btn primary'><?=t('Sign In')</button> </div>
Fix bad reference on webhook response.
/* LIB */ const radial = require('../../radial'); const authenticate = require('./authenticate'); /* MODULES */ const xmlConvert = require('xml-js'); /* CONSTRUCTOR */ (function () { var RiskOrderStatus = {}; /* PRIVATE VARIABLES */ /* PUBLIC VARIABLES */ /* PUBLIC FUNCTIONS */ RiskOrderStatus.parse = function (req, fn) { authenticate('riskOrderStatus', req, function (err) { if (err) { return fn({ status: 401, type: 'Authentication Failed', message: err.message }); } var body = req.body; var reply = body.RiskAssessmentReplyList; var assessment = reply.RiskAssessmentReply; return fn(null, { orderId: assessment.OrderId, responseCode: assessment.ResponseCode, storeId: assessment.StoreId, reasonCode: assessment.ReasonCode, reasonCodeDescription: assessment.ReasonCodeDescription }); }); }; /* NPM EXPORT */ if (typeof module === 'object' && module.exports) { module.exports = RiskOrderStatus.parse; } else { throw new Error('This module only works with NPM in NodeJS environments.'); } }());
/* LIB */ const radial = require('../../radial'); const authenticate = require('./authenticate'); /* MODULES */ const xmlConvert = require('xml-js'); /* CONSTRUCTOR */ (function () { var RiskOrderStatus = {}; /* PRIVATE VARIABLES */ /* PUBLIC VARIABLES */ /* PUBLIC FUNCTIONS */ RiskOrderStatus.parse = function (req, fn) { authenticate('riskOrderStatus', req, function (err) { if (err) { return fn({ status: 401, type: 'Authentication Failed', message: err.message }); } var body = req.body; var reply = response.RiskAssessmentReplyList; var assessment = reply.RiskAssessmentReply; return fn(null, { orderId: assessment.OrderId, responseCode: assessment.ResponseCode, storeId: assessment.StoreId, reasonCode: assessment.ReasonCode, reasonCodeDescription: assessment.ReasonCodeDescription }); }); }; /* NPM EXPORT */ if (typeof module === 'object' && module.exports) { module.exports = RiskOrderStatus.parse; } else { throw new Error('This module only works with NPM in NodeJS environments.'); } }());
Add some additional commenting to detail store
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), // TODO: Not sure I need to store the requests _requests = {}; function requestsChanged(targetRequests) { glimpse.emit('shell.request.summary.changed', targetRequests); } // Found Data (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; glimpse.emit('shell.request.detail.changed', payload.newRequest); } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); // Trigger Requests (function() { function triggerRequest(payload) { if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.id); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
var glimpse = require('glimpse'), requestRepository = require('../repository/request-repository.js'), _requests = {}; function requestsChanged(targetRequests) { glimpse.emit('shell.request.summary.changed', targetRequests); } (function() { function dataFound(payload) { // TODO: Really bad hack to get things going atm _requests[payload.newRequest.id] = payload.newRequest; glimpse.emit('shell.request.detail.changed', payload.newRequest); } // External data coming in glimpse.on('data.request.detail.found', dataFound); })(); (function() { function triggerRequest(payload) { if (!FAKE_SERVER) { requestRepository.triggerGetDetailsFor(payload.id); } } glimpse.on('data.request.detail.requested', triggerRequest); })();
Enable contrib.gis for test runs so templates are found
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'django.contrib.gis', 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests()
#!/usr/bin/env python import os import sys from django.conf import settings import django DEFAULT_SETTINGS = { 'INSTALLED_APPS': ( 'spillway', 'tests', ), 'DATABASES': { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': ':memory:' } }, } def runtests(): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, 'setup'): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner failures = runner_class( verbosity=1, interactive=True, failfast=False).run_tests(['tests']) sys.exit(failures) if __name__ == '__main__': runtests()
Fix exclusion of migrations from installed app.
#! /usr/bin/env python from setuptools import setup, find_packages setup( name='django-nomination', version='1.0.0', packages=find_packages(exclude=['tests*']), description='', long_description='See the home page for more information.', include_package_data=True, install_requires=[ 'simplejson>=3.8.1', 'django-markup-deprecated>=0.0.3', 'markdown>=2.6.5', 'django-widget-tweaks>=1.4.1', ], zip_safe=False, url='https://github.com/unt-libraries/django-nomination', author='University of North Texas Libraries', author_email='mark.phillips@unt.edu', license='BSD', keywords=[ 'django', 'app', 'UNT', 'url', 'surt', 'nomination', 'web archiving' ], classifiers=[ 'Natural Language :: English', 'Environment :: Web Environment', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
#! /usr/bin/env python from setuptools import setup setup( name='django-nomination', version='1.0.0', packages=['nomination'], description='', long_description='See the home page for more information.', include_package_data=True, install_requires=[ 'simplejson>=3.8.1', 'django-markup-deprecated>=0.0.3', 'markdown>=2.6.5', 'django-widget-tweaks>=1.4.1', ], zip_safe=False, url='https://github.com/unt-libraries/django-nomination', author='University of North Texas Libraries', author_email='mark.phillips@unt.edu', license='BSD', keywords=[ 'django', 'app', 'UNT', 'url', 'surt', 'nomination', 'web archiving' ], classifiers=[ 'Natural Language :: English', 'Environment :: Web Environment', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', ] )
Fix - the project_path is the first member of tuple
# Copyright 2014 0xc0170 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging class Builder: """ Template to be subclassed """ def build_project(self, project, project_path): raise NotImplementedError def build(self, projects_path, project_list, env_settings, root): # Loop through each of the projects and build them. logging.debug("Building projects.") for i, project_name in enumerate(project_list): logging.debug("Building project %i of %i: %s" % (i + 1, len(project_list), project_name)) self.build_project(project_name[0], projects_path[i], env_settings, root)
# Copyright 2014 0xc0170 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging class Builder: """ Template to be subclassed """ def build_project(self, project, project_path): raise NotImplementedError def build(self, projects_path, project_list, env_settings, root): # Loop through each of the projects and build them. logging.debug("Building projects.") for i, project_name in enumerate(project_list): logging.debug("Building project %i of %i: %s" % (i + 1, len(project_list), project_name)) self.build_project(project_name, projects_path[i], env_settings, root)
Fix bug OSC-1094 - Incorrect spelling of database
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2002 osCommerce Released under the GNU General Public License */ define('HEADING_TITLE', 'Server Information'); define('TITLE_SERVER_HOST', 'Server Host:'); define('TITLE_SERVER_OS', 'Server OS:'); define('TITLE_SERVER_DATE', 'Server Date:'); define('TITLE_SERVER_UP_TIME', 'Server Up Time:'); define('TITLE_HTTP_SERVER', 'HTTP Server:'); define('TITLE_PHP_VERSION', 'PHP Version:'); define('TITLE_ZEND_VERSION', 'Zend:'); define('TITLE_DATABASE_HOST', 'Database Host:'); define('TITLE_DATABASE', 'Database:'); define('TITLE_DATABASE_DATE', 'Database Date:'); define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.'); define('TEXT_EXPORT_INFO', 'Export Server Information'); define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.'); define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later'); ?>
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2002 osCommerce Released under the GNU General Public License */ define('HEADING_TITLE', 'Server Information'); define('TITLE_SERVER_HOST', 'Server Host:'); define('TITLE_SERVER_OS', 'Server OS:'); define('TITLE_SERVER_DATE', 'Server Date:'); define('TITLE_SERVER_UP_TIME', 'Server Up Time:'); define('TITLE_HTTP_SERVER', 'HTTP Server:'); define('TITLE_PHP_VERSION', 'PHP Version:'); define('TITLE_ZEND_VERSION', 'Zend:'); define('TITLE_DATABASE_HOST', 'Database Host:'); define('TITLE_DATABASE', 'Database:'); define('TITLE_DATABASE_DATE', 'Datebase Date:'); define('TEXT_EXPORT_INTRO', 'The following information can be submitted to osCommerce by clicking on the Send button. You can also save the information to a file by clicking Save. This information is totally anonymous and cannot be used to identify an individual system. It will be used for support and development purposes only.'); define('TEXT_EXPORT_INFO', 'Export Server Information'); define('SUCCESS_INFO_SUBMIT', 'Your information has been submitted sucessfully.'); define('ERROR_INFO_SUBMIT', 'Could not connect to the osCommerce website to submit your configuration. Please try again later'); ?>
Update Geronimo JPA 2.0 specs EA7 git-svn-id: 60e751271f50ec028ae56d425821c1c711e0b018@807373 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.persistence; public interface TupleElement<X> { Class<? extends X> getJavaType(); String getAlias(); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // // This source code implements specifications defined by the Java // Community Process. In order to remain compliant with the specification // DO NOT add / change / or delete method signatures! // package javax.persistence; public interface TupleElement<X> { Class<X> getJavaType(); String getAlias(); }
Work around occasionally thrown IllegalAccessException
package com.codeaffine.extras.workingset.internal; import static java.lang.reflect.Modifier.isPublic; import static java.lang.reflect.Modifier.isStatic; import static org.junit.Assert.assertNotNull; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.junit.Test; public class ImagesPDETest { @Test public void testRegisteredImages() throws IllegalAccessException { for( String constantValue : getConstantValues() ) { checkImageDescriptor( constantValue ); } } private static void checkImageDescriptor( String constantValue ) { ImageDescriptor descriptor = Images.getImageDescriptor( constantValue ); assertNotNull( "No image descriptor registered for: " + constantValue, descriptor ); Image image = descriptor.createImage( false ); assertNotNull( "Image descriptor does not return image: " + constantValue, image ); image.dispose(); } private static String[] getConstantValues() throws IllegalAccessException { List<String> constantValues = new LinkedList<>(); Field[] declaredFields = Images.class.getDeclaredFields(); for( Field declaredField : declaredFields ) { if( isStatic( declaredField.getModifiers() ) && isPublic( declaredField.getModifiers() ) ) { constantValues.add( ( String )declaredField.get( null ) ); } } return constantValues.toArray( new String[ constantValues.size() ] ); } }
package com.codeaffine.extras.workingset.internal; import static org.junit.Assert.assertNotNull; import java.lang.reflect.Field; import java.util.LinkedList; import java.util.List; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.swt.graphics.Image; import org.junit.Test; import com.codeaffine.extras.workingset.internal.Images; public class ImagesPDETest { @Test public void testRegisteredImages() throws IllegalAccessException { for( String constantValue : getConstantValues() ) { checkImageDescriptor( constantValue ); } } private static void checkImageDescriptor( String constantValue ) { ImageDescriptor descriptor = Images.getImageDescriptor( constantValue ); assertNotNull( "No image descriptor registered for: " + constantValue, descriptor ); Image image = descriptor.createImage( false ); assertNotNull( "Image descriptor does not return image: " + constantValue, image ); image.dispose(); } private static String[] getConstantValues() throws IllegalAccessException { List<String> constantValues = new LinkedList<>(); Field[] declaredFields = Images.class.getDeclaredFields(); for( Field constant : declaredFields ) { constantValues.add( ( String )constant.get( null ) ); } return constantValues.toArray( new String[ constantValues.size() ] ); } }
Add `".dev0"` suffix to lower `"oedialect"` bound Readthedocs still picked up version 0.0.4, even with 0.0.5 being specified as the lower bound. Maybe it's because `oedialect` only has `.dev0` releases in which case adding the explicit suffix fixes that. Fingers crossed.
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="feedinlib", version="0.1.0rc1", description="Creating time series from pv or wind power plants.", url="http://github.com/oemof/feedinlib", author="oemof developer group", author_email="windpowerlib@rl-institut.de", license="MIT", packages=["feedinlib"], long_description=read("README.rst"), long_description_content_type="text/x-rst", zip_safe=False, install_requires=[ "cdsapi >= 0.1.4", "numpy >= 1.7.0", "oedialect >= 0.0.6.dev0", "open_FRED-cli", "pandas >= 0.13.1", "pvlib >= 0.6.0", "windpowerlib >= 0.2.0", "xarray >= 0.12.0", ], extras_require={ "dev": ["jupyter", "pytest", "shapely", "sphinx_rtd_theme"], "examples": ["jupyter", "shapely"], }, )
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="feedinlib", version="0.1.0rc1", description="Creating time series from pv or wind power plants.", url="http://github.com/oemof/feedinlib", author="oemof developer group", author_email="windpowerlib@rl-institut.de", license="MIT", packages=["feedinlib"], long_description=read("README.rst"), long_description_content_type="text/x-rst", zip_safe=False, install_requires=[ "cdsapi >= 0.1.4", "numpy >= 1.7.0", "oedialect >= 0.0.5", "open_FRED-cli", "pandas >= 0.13.1", "pvlib >= 0.6.0", "windpowerlib >= 0.2.0", "xarray >= 0.12.0", ], extras_require={ "dev": ["jupyter", "pytest", "shapely", "sphinx_rtd_theme"], "examples": ["jupyter", "shapely"], }, )
Clean up some commented out code
from weakref import WeakValueDictionary class DuplicateEntryError(Exception): def __init__(self, name, obj, registry): self.name = name self.obj = obj self.registry = registry def __str__(self): return "Duplicate entry in '%s' registry for '%s'." % ( self.registry._object_type.__name__, self.name) class Registry(WeakValueDictionary): def __init__(self, object_type, *args, **kwargs): self._object_type = object_type WeakValueDictionary.__init__(self, *args, **kwargs) def __setitem__(self, name, value): if not isinstance(value, self._object_type): raise TypeError("This registry only accepts objects of type %s." % (self._object_type.__name__)) if self.has_key(name): raise DuplicateEntryError(name, value, self) WeakValueDictionary.__setitem__(self, name, value)
from weakref import WeakValueDictionary class DuplicateEntryError(Exception): def __init__(self, name, obj, registry): self.name = name self.obj = obj self.registry = registry def __str__(self): return "Duplicate entry in '%s' registry for '%s'." % ( self.registry._registry_name, self.name) class Registry(WeakValueDictionary): def __init__(self, object_type, *args, **kwargs): self._object_type = object_type #super(Registry, self).__init__(*args, **kwargs) WeakValueDictionary.__init__(self, *args, **kwargs) def __setitem__(self, name, value): if not isinstance(value, self._object_type): raise TypeError("This registry only accepts objects of type %s." % (self._object_type.__name__)) if self.has_key(name): raise DuplicateEntryError(name, value, self) WeakValueDictionary.__setitem__(self, name, value)
Remove ability for extensions to register a service provider The concept of returning a bootstrapper function is simpler and the use of service providers had no advantage over it.
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Support; class ExtensionsServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('flarum.extensions', 'Flarum\Support\ExtensionManager'); $config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled'); $extensions = json_decode($config, true); foreach ($extensions as $extension) { if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php')) { $bootstrapper = require $file; $bootstrapper($this->app); } } } }
<?php /* * This file is part of Flarum. * * (c) Toby Zerner <toby.zerner@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Flarum\Support; class ExtensionsServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('flarum.extensions', 'Flarum\Support\ExtensionManager'); $config = $this->app->make('Flarum\Core\Settings\SettingsRepository')->get('extensions_enabled'); $extensions = json_decode($config, true); $events = $this->app->make('events'); foreach ($extensions as $extension) { if (file_exists($file = public_path().'/extensions/'.$extension.'/bootstrap.php')) { $provider = require $file; if (is_string($provider)) { $this->app->register($provider)->listen($events); } elseif (is_callable($provider)) { $provider($events); } } } } }
fix(theme): Add surface color to theming mixin.
const themeProps = [ 'primary', 'secondary', 'background', 'surface', 'on-primary', 'on-secondary', 'on-surface', 'primary-bg', 'secondary-bg', 'text-primary-on-light', 'text-secondary-on-light', 'text-hint-on-light', 'text-disabled-on-light', 'text-icon-on-light', 'text-primary-on-dark', 'text-secondary-on-dark', 'text-hint-on-dark', 'text-disabled-on-dark', 'text-icon-on-dark' ] const themeClassMixin = { props: { theming: { type: String, default: '' } }, mounted () { if (themeProps.indexOf(this.theming) > -1) { this.$el.classList.add('mdc-theme--' + this.theming) } } } export default themeClassMixin
const themeProps = [ 'primary', 'secondary', 'background', 'on-primary', 'on-secondary', 'primary-bg', 'secondary-bg', 'text-primary-on-light', 'text-secondary-on-light', 'text-hint-on-light', 'text-disabled-on-light', 'text-icon-on-light', 'text-primary-on-dark', 'text-secondary-on-dark', 'text-hint-on-dark', 'text-disabled-on-dark', 'text-icon-on-dark' ] const themeClassMixin = { props: { theming: { type: String, default: '' } }, mounted () { if (themeProps.indexOf(this.theming) > -1) { this.$el.classList.add('mdc-theme--' + this.theming) } } } export default themeClassMixin
Update docblock in variable expression evaluator
<?php namespace Pinq\Expressions; /** * Implementation of the expression evaluator using a variable * from the variable table or from the standard superglobals. * * @author Elliot Levin <elliotlevin@hotmail.com> */ class VariableEvaluator extends Evaluator { /** * @var string */ protected $name; public function __construct($name, IEvaluationContext $context = null) { parent::__construct($context); $this->name = $name; } public function doEvaluation(array $variableTable) { $variableTable += [ 'GLOBALS' => &$GLOBALS, '_SERVER' => &$_SERVER, '_ENV' => &$_ENV, '_REQUEST' => &$_REQUEST, '_GET' => &$_GET, '_POST' => &$_POST, '_COOKIE' => &$_COOKIE, '_SESSION' => &$_SESSION, '_FILES' => &$_FILES, ]; return $variableTable[$this->name]; } }
<?php namespace Pinq\Expressions; /** * Implementation of the expression evaluator using a variable * from the variable table. * * @author Elliot Levin <elliotlevin@hotmail.com> */ class VariableEvaluator extends Evaluator { /** * @var string */ protected $name; public function __construct($name, IEvaluationContext $context = null) { parent::__construct($context); $this->name = $name; } public function doEvaluation(array $variableTable) { $variableTable += [ 'GLOBALS' => &$GLOBALS, '_SERVER' => &$_SERVER, '_ENV' => &$_ENV, '_REQUEST' => &$_REQUEST, '_GET' => &$_GET, '_POST' => &$_POST, '_COOKIE' => &$_COOKIE, '_SESSION' => &$_SESSION, '_FILES' => &$_FILES, ]; return $variableTable[$this->name]; } }
Debug bad creation of folders.
""" Module used to group the functions and utils to built a report from a model application. """ from Mscthesis.Plotting.net_plotting import plot_net_distribution,\ plot_heat_net from os.path import exists, join from os import makedirs def create_model_report(net, sectors, dirname, reportname): "Creation of a report for the model applied." # Check and create the folders if not exists(dirname): makedirs(dirname) if not exists(join(dirname, reportname)): makedirs(join(dirname, reportname)) if not exists(join(join(dirname, reportname), 'Images')): makedirs(join(join(dirname, reportname), 'Images')) # Creation of the plots fig1 = plot_net_distribution(net, 50) fig2 = plot_heat_net(net, sectors) fig1.savefig(join(join(dirname, 'Images'), 'net_hist')) fig2.savefig(join(join(dirname, 'Images'), 'heat_net')) return fig1, fig2
""" Module used to group the functions and utils to built a report from a model application. """ from Mscthesis.Plotting.net_plotting import plot_net_distribution,\ plot_heat_net from os.path import exists, join from os import makedirs def create_model_report(net, sectors, dirname, reportname): "Creation of a report for the model applied." # Check and create the folders if not exists(dirname): makedirs(dirname) if not exists(join(dirname, reportname)): makedirs(join(dirname, 'Images')) if not exists(join(join(dirname, reportname), 'Images')): makedirs(join(join(dirname, reportname), 'Images')) # Creation of the plots fig1 = plot_net_distribution(net, 50) fig2 = plot_heat_net(net, sectors) fig1.savefig(join(dirname, 'Images'), 'net_hist') fig2.savefig(join(dirname, 'Images'), 'heat_net') return fig1, fig2
Fix column name in tests
import pytest import astropy.units as u from astropy.coordinates import SkyCoord from .. import Ogle @pytest.mark.remote_data def test_ogle_single(): co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic') response = Ogle.query_region(coord=co) assert len(response) == 1 @pytest.mark.remote_data def test_ogle_list(): co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic') co_list = [co, co, co] response = Ogle.query_region(coord=co_list) assert len(response) == 3 assert response['RA[hr]'][0] == response['RA[hr]'][1] == response['RA[hr]'][2] @pytest.mark.remote_data def test_ogle_list_values(): co_list = [[0, 0, 0], [3, 3, 3]] response = Ogle.query_region(coord=co_list) assert len(response) == 3 assert response['RA[hr]'][0] == response['RA[hr]'][1] == response['RA[hr]'][2]
import pytest import astropy.units as u from astropy.coordinates import SkyCoord from .. import Ogle @pytest.mark.remote_data def test_ogle_single(): co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic') response = Ogle.query_region(coord=co) assert len(response) == 1 @pytest.mark.remote_data def test_ogle_list(): co = SkyCoord(0, 3, unit=(u.degree, u.degree), frame='galactic') co_list = [co, co, co] response = Ogle.query_region(coord=co_list) assert len(response) == 3 assert response['RA/Lon'][0] == response['RA/Lon'][1] == response['RA/Lon'][2] @pytest.mark.remote_data def test_ogle_list_values(): co_list = [[0, 0, 0], [3, 3, 3]] response = Ogle.query_region(coord=co_list) assert len(response) == 3 assert response['RA/Lon'][0] == response['RA/Lon'][1] == response['RA/Lon'][2]
Fix missing extension in course view file
# -*- coding: utf-8 -*- { 'name': "Open Academy", 'summary': """Manage trainings""", 'description': """ Open Academy module for managing trainings: - training courses - training sessions - attendees registration """, 'author': "tebanep", 'website': "https://github.com/tebanep", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Test', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', #'templates.xml', 'view/openacademy_course_view.xml', ], # only loaded in demonstration mode 'demo': [ 'demo/openacademy_course_demo.xml', ], 'installable': True, 'auto_install': False, }
# -*- coding: utf-8 -*- { 'name': "Open Academy", 'summary': """Manage trainings""", 'description': """ Open Academy module for managing trainings: - training courses - training sessions - attendees registration """, 'author': "tebanep", 'website': "https://github.com/tebanep", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml # for the full list 'category': 'Test', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ # 'security/ir.model.access.csv', #'templates.xml', 'view/openacademy_course_view', ], # only loaded in demonstration mode 'demo': [ 'demo/openacademy_course_demo.xml', ], 'installable': True, 'auto_install': False, }
Fix syntax highlighting for es searches
"use strict"; define(function(require) { var SearchView = require('views/searches/search'), NullSearchView = require('views/searches/search/null'), PingSearchView = require('views/searches/search/ping'), HTTPSearchView = require('views/searches/search/http'), GraphiteSearchView = require('views/searches/search/graphite'), ThreatexchangeSearchView = require('views/searches/search/threatexchange'), ElasticsearchSearchView = require('views/searches/search/elasticsearch'), ECLSearchView = require('views/searches/search/ecl'), PushSearchView = require('views/searches/search/push'); /** * Loader for SearchView subclasses. */ SearchView.registerSubclass('null', NullSearchView); SearchView.registerSubclass('ping', PingSearchView); SearchView.registerSubclass('http', HTTPSearchView); SearchView.registerSubclass('graphite', GraphiteSearchView); SearchView.registerSubclass('threatexchange', ThreatexchangeSearchView); SearchView.registerSubclass('es', ElasticsearchSearchView); SearchView.registerSubclass('alert', ElasticsearchSearchView); SearchView.registerSubclass('ecl', ECLSearchView); SearchView.registerSubclass('push', PushSearchView); });
"use strict"; define(function(require) { var SearchView = require('views/searches/search'), NullSearchView = require('views/searches/search/null'), PingSearchView = require('views/searches/search/ping'), HTTPSearchView = require('views/searches/search/http'), GraphiteSearchView = require('views/searches/search/graphite'), ThreatexchangeSearchView = require('views/searches/search/threatexchange'), ElasticsearchSearchView = require('views/searches/search/elasticsearch'), ECLSearchView = require('views/searches/search/ecl'), PushSearchView = require('views/searches/search/push'); /** * Loader for SearchView subclasses. */ SearchView.registerSubclass('null', NullSearchView); SearchView.registerSubclass('ping', PingSearchView); SearchView.registerSubclass('http', HTTPSearchView); SearchView.registerSubclass('graphite', GraphiteSearchView); SearchView.registerSubclass('threatexchange', ThreatexchangeSearchView); SearchView.registerSubclass('logstash', ElasticsearchSearchView); SearchView.registerSubclass('alert', ElasticsearchSearchView); SearchView.registerSubclass('ecl', ECLSearchView); SearchView.registerSubclass('push', PushSearchView); });
Support for Lang in URL in Gfycat plugin
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'gfycat.com', prepareImgLinks:function (callback) { $('a[href*="gfycat.com/"]').one('mouseenter', function() { var link = $(this), gfyId = this.href.replace(/.*gfycat.com\/(..\/)?(gifs\/)?(detail\/)?(\w+).*/, '$4'); $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) { if (data && data.gfyItem) { link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl] link.addClass('hoverZoomLink'); hoverZoom.displayPicFromElement(link); } }); }); } });
var hoverZoomPlugins = hoverZoomPlugins || []; hoverZoomPlugins.push({ name:'gfycat.com', prepareImgLinks:function (callback) { $('a[href*="gfycat.com/"]').one('mouseenter', function() { var link = $(this), gfyId = this.href.replace(/.*gfycat.com\/(gifs\/)?(detail\/)?(\w+).*/, '$3'); $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) { if (data && data.gfyItem) { link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl] link.addClass('hoverZoomLink'); hoverZoom.displayPicFromElement(link); } }); }); } });
[api] Allow for multiple auth header types.
var debug = require('diagnostics')('artsy'); var Mana = require('mana'); Mana.extend({ /** * Do constructor things * * @constructor * @api public * **/ initialise: function initialise (options) { options = options || {}; this.api = options.url || 'https://api.artsy.net/api/v1/'; this.authHeader = options.header || 'X-XAPP-Token'; this.authorization = options.token; if (!this.authorization) { throw new Error('Token required to make api requests, please generate one'); } }, options: function (opts, params) { opts = opts || {} opts.params = opts.params || params || []; var defaults = { page: 1, size: 100 }; Object.keys(defaults).forEach(function (key) { if (Array.isArray(opts.params)) { if (!~opts.params.indexOf(key)) opts.params.push(key); if (!opts[key]) opts[key] = defaults[key]; } else { if (!(key in opts.params)) opts.params[key] = defaults[key]; } }); return opts; } }).drink(module);
var debug = require('diagnostics')('artsy'); var Mana = require('mana'); Mana.extend({ /** * Do constructor things * * @constructor * @api public * **/ initialise: function initialise (options) { options = options || {}; this.api = options.url || 'https://api.artsy.net/api/v1/'; // TODO: Make this conditional because it can be X-Access-Token as well this.authHeader = 'X-XAPP-Token'; this.authorization = options.token; if (!this.authorization) { throw new Error('Token required to make api requests, please generate one'); } }, options: function (opts, params) { opts = opts || {} opts.params = opts.params || params || []; var defaults = { page: 1, size: 100 }; Object.keys(defaults).forEach(function (key) { if (Array.isArray(opts.params)) { if (!~opts.params.indexOf(key)) opts.params.push(key); if (!opts[key]) opts[key] = defaults[key]; } else { if (!(key in opts.params)) opts.params[key] = defaults[key]; } }); return opts; } }).drink(module);
Fix model loader for webpack
const ssaclAttributeRoles = require('ssacl-attribute-roles') const debug = require('debug')('bshed:models') const Sequelize = require('sequelize') const assert = require('assert') /** * List of models to load * Kept manually because there's not that many, and it's a little faster */ const MODEL_LIST = [ 'bike', 'bikeshed', 'rating', 'user', 'vote' ] /** * Models loader * @param {Object} config * @returns {Object} Models */ module.exports = function modelsLoader (config) { assert(config, 'model loader requires config') debug('loader:start') const sequelize = new Sequelize( config.database, config.username, config.password, config ) ssaclAttributeRoles(sequelize) const models = MODEL_LIST.reduce((models, name) => { debug(`loading ${name} model`) const model = require(`./${name}.js`)(sequelize, Sequelize) models[model.name] = model return models }, { sequelize, Sequelize }) // Associate and initialize models Object.keys(models).forEach(name => { if ('associate' in models[name]) { debug(`associate ${name}`) models[name].associate(models) } }) debug('loader:end') return models }
const ssaclAttributeRoles = require('ssacl-attribute-roles') const debug = require('debug')('bshed:models') const Sequelize = require('sequelize') const assert = require('assert') const path = require('path') const fs = require('fs') /** * Models loader * @param {Object} config * @returns {Object} Models */ module.exports = function modelsLoader (config) { assert(config, 'model loader requires config') debug('loader:start') const models = {} const sequelize = new Sequelize( config.database, config.username, config.password, config ) ssaclAttributeRoles(sequelize) // Load models fs.readdirSync(__dirname) .filter(file => file.indexOf('.') !== 0 && file !== 'index.js' && file !== 'test' ) .forEach(file => { const modelPath = path.join(__dirname, file) const model = sequelize.import(modelPath) models[model.name] = model debug(`${model.name} loaded from file ${modelPath}`) }) // Associate and initialize models Object.keys(models).forEach(name => { ['associate', 'initialize'].forEach(action => { if (action in models[name]) { debug(`${action} ${name}`) models[name][action](models) } }) }) models.sequelize = sequelize models.Sequelize = Sequelize debug('loader:end') return models }
Change script to point to AWS
from scapy.all import * import unirest import json def callbackFunction(response): pass # "http://54.68.246.202:3000/rssi" def main(): print "Reading pcap file %s"%sys.argv[1] myreader = PcapReader(sys.argv[1]) packets = [] routerId = sys.argv[2] for pkt in myreader: try: extra = pkt.notdecoded except: extra = None if extra!=None: signal_strength = (256-ord(extra[14:15])) signal_strength = signal_strength - 256 if signal_strength > 127 else signal_strength signal_strength = -signal_strength try: print "[%d] MAC: %s RSSi: %d"%(pkt.time, pkt.addr1, signal_strength) packets.append({'created': pkt.time * 1000, 'mac': pkt.addr1, 'rssi': signal_strength, 'router': routerId, 'processed': False}) if len(packets) > 300: thread = unirest.post("http://54.68.246.202:3000/rssi", headers = {"Content-Type": "application/json"}, params = json.dumps(packets), callback = callbackFunction) packets = [] except: print "Caught exception" if __name__=="__main__": main()
from scapy.all import * import unirest import json def callbackFunction(response): pass # "http://54.68.246.202:3000/rssi" def main(): print "Reading pcap file %s"%sys.argv[1] myreader = PcapReader(sys.argv[1]) packets = [] routerId = sys.argv[2] for pkt in myreader: try: extra = pkt.notdecoded except: extra = None if extra!=None: signal_strength = (256-ord(extra[14:15])) signal_strength = signal_strength - 256 if signal_strength > 127 else signal_strength signal_strength = -signal_strength try: print "[%d] MAC: %s RSSi: %d"%(pkt.time, pkt.addr1, signal_strength) packets.append({'created': pkt.time * 1000, 'mac': pkt.addr1, 'rssi': signal_strength, 'router': routerId, 'processed': False}) if len(packets) > 300: thread = unirest.post("http://127.0.0.1:3000/rssi", headers = {"Content-Type": "application/json"}, params = json.dumps(packets), callback = callbackFunction) packets = [] except: print "Caught exception" if __name__=="__main__": main()
Set worker lifetime to 20 minutes, not 20 seconds
<?php /** * This file configures default behavior for all workers * * To modify these parameters, copy this file into your own CakePHP APP/Config directory. * */ $config['Queue'] = [ // seconds to sleep() when no executable job is found 'sleeptime' => 10, // probability in percent of a old job cleanup happening 'gcprob' => 10, // time (in seconds) after which a job is requeued if the worker doesn't report back 'defaultworkertimeout' => 120, // number of retries if a job fails or times out. 'defaultworkerretries' => 4, // seconds of running time after which the worker will terminate (0 = unlimited) 'workermaxruntime' => 20*60, // minimum time (in seconds) which a task remains in the database before being cleaned up. 'cleanuptimeout' => 2000, // instruct a Workerprocess quit when there are no more tasks for it to execute (true = exit, false = keep running) 'exitwhennothingtodo' => false, // pid file path directory (by default goes to the app/tmp/queue folder) 'pidfilepath' => TMP . 'queue' . DS, // determine whether logging is enabled 'log' => true, // set to false to disable (tmp = file in TMP dir) 'notify' => 'tmp', ];
<?php /** * This file configures default behavior for all workers * * To modify these parameters, copy this file into your own CakePHP APP/Config directory. * */ $config['Queue'] = [ // seconds to sleep() when no executable job is found 'sleeptime' => 10, // probability in percent of a old job cleanup happening 'gcprob' => 10, // time (in seconds) after which a job is requeued if the worker doesn't report back 'defaultworkertimeout' => 120, // number of retries if a job fails or times out. 'defaultworkerretries' => 4, // seconds of running time after which the worker will terminate (0 = unlimited) 'workermaxruntime' => 20, // minimum time (in seconds) which a task remains in the database before being cleaned up. 'cleanuptimeout' => 2000, // instruct a Workerprocess quit when there are no more tasks for it to execute (true = exit, false = keep running) 'exitwhennothingtodo' => false, // pid file path directory (by default goes to the app/tmp/queue folder) 'pidfilepath' => TMP . 'queue' . DS, // determine whether logging is enabled 'log' => true, // set to false to disable (tmp = file in TMP dir) 'notify' => 'tmp', ];