text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Hide link when game has started
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`}, [ h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'submit'}, 'Start') ]), game.playing ? null : h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, dataPlayerId: playerID }, 'Score: ' + player.score) })) ]) ]); };
const h = require('virtual-dom/h'); module.exports = function (data) { const {gameID, game} = data; return h('div', {className: 'room'}, [ game.playing ? null : h('form', {id: 'setup', method: 'post', action: `/${gameID}`}, [ h('input', {type: 'number', name: 'max-score', min: '1', value: game.maxScore}), h('button', {type: 'submit'}, 'Start') ]), h('a', {href: '/new-player/' + gameID}, 'Wanna play along?'), h('div', {id: 'players'}, [ h('ul', Object.keys(game.players).map(playerID => { const player = game.players[playerID]; return h('li', { style: { backgroundColor: `rgb(${player.color[1]}, ${player.color[0]}, ${player.color[2]})` }, dataPlayerId: playerID }, 'Score: ' + player.score) })) ]) ]); };
Tidy up for loop code
'use strict'; angular.module('confRegistrationWebApp') .directive('block', function () { return { templateUrl: 'views/blockDirective.html', restrict: 'E', controller: function ($scope, AnswerCache, RegistrationCache, uuid) { var currentRegistration = RegistrationCache.getCurrentRightNow($scope.conference.id); var answerForThisBlock = _.where(currentRegistration.answers, { 'blockId': $scope.block.id }); if (answerForThisBlock.length > 0) { $scope.answer = answerForThisBlock[0]; } if (!angular.isDefined($scope.answer)) { $scope.answer = { id : uuid(), registrationId : currentRegistration.id, blockId : $scope.block.id, value : {} }; currentRegistration.answers.push($scope.answer); } AnswerCache.syncBlock($scope, 'answer'); } }; });
'use strict'; angular.module('confRegistrationWebApp') .directive('block', function () { return { templateUrl: 'views/blockDirective.html', restrict: 'E', controller: function ($scope, AnswerCache, RegistrationCache, uuid) { var currentRegistration = RegistrationCache.getCurrentRightNow($scope.conference.id); for (var i = 0;i < currentRegistration.answers.length; i++) { if (angular.isDefined(currentRegistration.answers[i]) && currentRegistration.answers[i].blockId === $scope.block.id) { $scope.answer = currentRegistration.answers[i]; break; } } if (!angular.isDefined($scope.answer)) { $scope.answer = { id : uuid(), registrationId : currentRegistration.id, blockId : $scope.block.id, value : {} }; currentRegistration.answers.push($scope.answer); } AnswerCache.syncBlock($scope, 'answer'); } }; });
Add read columns to the notifications migration
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function(Blueprint $table) { $table->increments('id'); $table->string('notifiable_type'); $table->integer('notifiable_id')->unsigned(); $table->string('body'); $table->boolean('read'); $table->timestamp('read_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('notifications'); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateNotificationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('notifications', function(Blueprint $table) { $table->increments('id'); $table->string('notifiable_type'); $table->integer('notifiable_id')->unsigned(); $table->string('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('notifications'); } }
Comment Action members 'Name', and 'Payload', pending clarification on these
package state import () type actionDoc struct { Id string `bson:"_id"` //Name string //Payload map[string]interface{} } // Action represents an instruction to do some "action" and is expected to match // an action definition in a charm. type Action struct { st *State doc actionDoc } func newAction(st *State, adoc actionDoc) *Action { return &Action{ st: st, doc: adoc, } } // Name returns the name of the Action //func (a *Action) Name() string { // return a.doc.Name //} // Id returns the id of the Action func (a *Action) Id() string { return a.doc.Id } // Payload will contain a structure representing arguments or parameters to // an action, and is expected to be validated by the Unit using the Charm // definition of the Action //func (a *Action) Payload() map[string]interface{} { // return a.doc.Payload //}
package state import () type actionDoc struct { Id string `bson:"_id"` Name string Payload map[string]interface{} } // Action represents an instruction to do some "action" and is expected to match // an action definition in a charm. type Action struct { st *State doc actionDoc } func newAction(st *State, adoc actionDoc) *Action { return &Action{ st: st, doc: adoc, } } // Name returns the name of the Action func (a *Action) Name() string { return a.doc.Name } // Id returns the id of the Action func (a *Action) Id() string { return a.doc.Id } // Payload will contain a structure representing arguments or parameters to // an action, and is expected to be validated by the Unit using the Charm // definition of the Action func (a *Action) Payload() map[string]interface{} { return a.doc.Payload }
Change broken course_modes migration to not touch the database. Changing a field name in the way that we did (updating the Python variable name and switching it to point to the old DB column) confuses Django's migration autodetector. No DB changes are actually necessary, but it thinks that a field has been removed and a new one added. This means that Django will ask users to generate the migration it thinks is necessary, which ended up with us dropping data. The fix is to run the same migration on Django's internal model of the DB state, but not actually touch the DB.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.SeparateDatabaseAndState( database_operations=[], state_operations=[ migrations.RemoveField( model_name='coursemode', name='expiration_datetime', ), migrations.AddField( model_name='coursemode', name='_expiration_datetime', field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), ), ] ) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_modes', '0004_auto_20151113_1457'), ] operations = [ migrations.RemoveField( model_name='coursemode', name='expiration_datetime', ), migrations.AddField( model_name='coursemode', name='_expiration_datetime', field=models.DateTimeField(db_column=b'expiration_datetime', default=None, blank=True, help_text='OPTIONAL: After this date/time, users will no longer be able to enroll in this mode. Leave this blank if users can enroll in this mode until enrollment closes for the course.', null=True, verbose_name='Upgrade Deadline'), ), ]
Add assert for main process API call
// Test for examples included in README.md var helpers = require('./global-setup') var path = require('path') var describe = global.describe var it = global.it var beforeEach = global.beforeEach var afterEach = global.afterEach describe('requireName option to Application', function () { helpers.setupTimeout(this) var app = null beforeEach(function () { return helpers.startApplication({ args: [path.join(__dirname, 'fixtures', 'require-name')], requireName: 'electronRequire' }).then(function (startedApp) { app = startedApp }) }) afterEach(function () { return helpers.stopApplication(app) }) it('uses the custom require name to load the electron module', function () { return app.client.waitUntilWindowLoaded() .browserWindow.getBounds().should.eventually.deep.equal({ x: 25, y: 35, width: 200, height: 100 }) .webContents.getTitle().should.eventually.equal('Test') .electron.remote.process.execArgv().should.eventually.be.empty .getText('body').should.eventually.equal('Hello') .getTitle().should.eventually.equal('Test') }) })
// Test for examples included in README.md var helpers = require('./global-setup') var path = require('path') var describe = global.describe var it = global.it var beforeEach = global.beforeEach var afterEach = global.afterEach describe('requireName option to Application', function () { helpers.setupTimeout(this) var app = null beforeEach(function () { return helpers.startApplication({ args: [path.join(__dirname, 'fixtures', 'require-name')], requireName: 'electronRequire' }).then(function (startedApp) { app = startedApp }) }) afterEach(function () { return helpers.stopApplication(app) }) it('uses the custom require name to load the electron module', function () { return app.client.waitUntilWindowLoaded() .browserWindow.getBounds().should.eventually.deep.equal({ x: 25, y: 35, width: 200, height: 100 }) .webContents.getTitle().should.eventually.equal('Test') .getText('body').should.eventually.equal('Hello') .getTitle().should.eventually.equal('Test') }) })
Make the hash function for generic case
"""This module contains utility functions for the Mythril support package.""" from typing import Dict import logging import _pysha3 as sha3 log = logging.getLogger(__name__) class Singleton(type): """A metaclass type implementing the singleton pattern.""" _instances = {} # type: Dict def __call__(cls, *args, **kwargs): """Delegate the call to an existing resource or a a new one. This is not thread- or process-safe by default. It must be protected with a lock. :param args: :param kwargs: :return: """ if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] def get_code_hash(code): """ :param code: bytecode :return: Returns hash of the given bytecode """ code = code[2:] if code[:2] == "0x" else code try: keccak = sha3.keccak_256() keccak.update(bytes.fromhex(code)) return "0x" + keccak.hexdigest() except ValueError: log.debug("Unable to change the bytecode to bytes. Bytecode: {}".format(code)) return ""
"""This module contains utility functions for the Mythril support package.""" from typing import Dict import logging import _pysha3 as sha3 log = logging.getLogger(__name__) class Singleton(type): """A metaclass type implementing the singleton pattern.""" _instances = {} # type: Dict def __call__(cls, *args, **kwargs): """Delegate the call to an existing resource or a a new one. This is not thread- or process-safe by default. It must be protected with a lock. :param args: :param kwargs: :return: """ if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] def get_code_hash(code): """ :param code: bytecode :return: Returns hash of the given bytecode """ try: keccak = sha3.keccak_256() keccak.update(bytes.fromhex(code[2:])) return "0x" + keccak.hexdigest() except ValueError: log.debug("Unable to change the bytecode to bytes. Bytecode: {}".format(code)) return ""
Support hidden details table rows.
const Qh = require('qhell'); const { table, tr, th, td } = require('keys/dist/hh'); module.exports = async ( req, record = req.record, fieldSet = req.action.views.fieldSet(req, record), ) => { const fieldRows = await Qh.deepWhen(fieldSet.map(field => ({ hidden: field.hidden, label: field.label && field.label(req, record), data: field.data(req, record), }))); return table('.keysTable.keysDetailsTable', tr('.keysDetailsTable_headerRow', th('.keysTableHeader.keysDetailsTable_header', { colspan: 999 }, 'Detalhes', ), ), fieldRows.map(row => { const tRow = tr('.keysDetailsTable_dataRow', th('.keysDetailsTable_dataHeader', row.label), td('.keysDetailsTable_dataCell', row.data), ); if (row.hidden) { tRow.classList.add('keysHidden'); } return tRow; }), ); };
const Qh = require('qhell'); const { table, tr, th, td } = require('keys/dist/hh'); module.exports = async ( req, record = req.record, fieldSet = req.action.views.fieldSet(req, record), ) => { const fieldRows = await Qh.deepWhen(fieldSet.map(field => ({ label: field.label && field.label(req, record), data: field.data(req, record), }))); return table('.keysTable.keysDetailsTable', tr('.keysDetailsTable_headerRow', th('.keysTableHeader.keysDetailsTable_header', { colspan: 999 }, 'Detalhes', ), ), fieldRows.map(row => tr('.keysDetailsTable_dataRow', th('.keysDetailsTable_dataHeader', row.label), td('.keysDetailsTable_dataCell', row.data), )), ); };
Set decodeEntities to false for cheerio.
'use strict'; var cheerio = require('cheerio'); module.exports = function (html, options) { var results = {}; var $ = cheerio.load(html, { decodeEntities: false }); results.hrefs = []; $('link').each(function (index, element) { var $el = $(element); if ($el.attr('rel').toLowerCase() === 'stylesheet') { if (options.applyLinkTags) { results.hrefs.push($el.attr('href')); } if (options.removeLinkTags) { $el.remove(); } } }); results.html = $.html(); return results; };
'use strict'; var cheerio = require('cheerio'); module.exports = function (html, options) { var results = {}; var $ = cheerio.load(html); results.hrefs = []; $('link').each(function (index, element) { var $el = $(element); if ($el.attr('rel').toLowerCase() === 'stylesheet') { if (options.applyLinkTags) { results.hrefs.push($el.attr('href')); } if (options.removeLinkTags) { $el.remove(); } } }); results.html = $.html(); return results; };
Fix python-path when WSGIPythonPath is not defined
""" WSGI config for farnsworth project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for farnsworth project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "farnsworth.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Fix output with trailing newlines from sh. Closes #39
import logbook import sh from piper.logging import SEPARATOR class Process: """ Helper class for running processes """ def __init__(self, config, cmd, parent_key): self.config = config self.cmd = cmd self.sh = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') cmd, *args = self.cmd.split() self.sh = sh.Command(cmd)(args, _iter=True) def run(self): self.log.debug('Executing') try: for line in self.sh: self.log.info(line.strip()) except sh.ErrorReturnCode: self.log.error(self.sh.stderr) finally: exit = self.sh.exit_code self.success = exit == 0 self.log.debug('Exitcode {0}'.format(exit))
import logbook import sh from piper.logging import SEPARATOR class Process: """ Helper class for running processes """ def __init__(self, config, cmd, parent_key): self.config = config self.cmd = cmd self.sh = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') cmd, *args = self.cmd.split() self.sh = sh.Command(cmd)(args, _iter=True) def run(self): self.log.debug('Executing') try: for line in self.sh: self.log.info(line) except sh.ErrorReturnCode: self.log.error(self.sh.stderr) finally: exit = self.sh.exit_code self.success = exit == 0 self.log.debug('Exitcode {0}'.format(exit))
Set empty object as default arg
/* * Simple middleware that saves res.locals as stringified JSON to * `res.locals.INITIAL_STATE` * * @module midwest/middleware/bootstrap */ 'use strict' const _ = require('lodash') const defaultOmit = ['settings'] module.exports = function ({ pick, omit, property = 'INITIAL_STATE' } = {}) { if (!pick) { omit = omit ? defaultOmit.concat(omit) : defaultOmit } return function bootstrap (req, res, next) { if (!req.xhr && req.accepts(['json', '*/*']) === '*/*') { let obj = Object.assign({}, res.app.locals, res.locals) if (pick) { obj = _.pick(obj, pick) } else { obj = _.omit(obj, omit) } res.locals[property] = JSON.stringify(obj) } next() } }
/* * Simple middleware that saves res.locals as stringified JSON to * `res.locals.INITIAL_STATE` * * @module midwest/middleware/bootstrap */ 'use strict' const _ = require('lodash') const defaultOmit = ['settings'] module.exports = function ({ pick, omit, property = 'INITIAL_STATE' }) { if (!pick) { omit = omit ? defaultOmit.concat(omit) : defaultOmit } return function bootstrap (req, res, next) { if (!req.xhr && req.accepts(['json', '*/*']) === '*/*') { let obj = Object.assign({}, res.app.locals, res.locals) if (pick) { obj = _.pick(obj, pick) } else { obj = _.omit(obj, omit) } res.locals[property] = JSON.stringify(obj) } next() } }
Use short syntax version for the Fragment.
import React from 'react' import { StaticQuery, graphql } from 'gatsby' import Navigation from '../components/navigation' export default ({ children }) => ( <StaticQuery query={graphql` query NavigationQuery { allMongodbPlacardDevSportsAndCountries { edges { node { name countries { name } } } } } `} render={data => ( <> <Navigation sports={data.allMongodbPlacardDevSportsAndCountries.edges} /> {children} </> )} /> )
import React from 'react' import { StaticQuery, graphql } from 'gatsby' import Navigation from '../components/navigation' export default ({ children }) => ( <StaticQuery query={graphql` query NavigationQuery { allMongodbPlacardDevSportsAndCountries { edges { node { name countries { name } } } } } `} render={data => ( <div> <Navigation sports={data.allMongodbPlacardDevSportsAndCountries.edges} /> {children} </div> )} /> )
Use original case for type in exception
<?php namespace SwaggerGen\Swagger; /** * Describes a Swagger Header object, which may be part of a Response. * * @package SwaggerGen * @author Martijn van der Lee <martijn@vanderlee.com> * @copyright 2014-2015 Martijn van der Lee * @license https://opensource.org/licenses/MIT MIT */ class Header extends AbstractObject { private $type; private $description; public function __construct(AbstractObject $parent, $type, $description = null) { parent::__construct($parent); $this->type = strtolower($type); if (!in_array($this->type, array('string', 'number', 'integer', 'boolean', 'array'))) { throw new \SwaggerGen\Exception('Header type not valid: ' . $type); } $this->description = $description; } public function handleCommand($command, $data = null) { switch (strtolower($command)) { case 'description': $this->description = $data; return $this; } return parent::handleCommand($command, $data); } public function toArray() { return self::array_filter_null(array_merge(array( 'type' => $this->type, 'description' => $this->description, ), parent::toArray())); } public function __toString() { return __CLASS__ . ' ' . $this->type; } }
<?php namespace SwaggerGen\Swagger; /** * Describes a Swagger Header object, which may be part of a Response. * * @package SwaggerGen * @author Martijn van der Lee <martijn@vanderlee.com> * @copyright 2014-2015 Martijn van der Lee * @license https://opensource.org/licenses/MIT MIT */ class Header extends AbstractObject { private $type; private $description; public function __construct(AbstractObject $parent, $type, $description = null) { parent::__construct($parent); $this->type = strtolower($type); if (!in_array($this->type, array('string', 'number', 'integer', 'boolean', 'array'))) { throw new \SwaggerGen\Exception('Header type not valid: ' . $this->type); } $this->description = $description; } public function handleCommand($command, $data = null) { switch (strtolower($command)) { case 'description': $this->description = $data; return $this; } return parent::handleCommand($command, $data); } public function toArray() { return self::array_filter_null(array_merge(array( 'type' => $this->type, 'description' => $this->description, ), parent::toArray())); } public function __toString() { return __CLASS__ . ' ' . $this->type; } }
Increase timeout to avoid Travis issue.
package controllers; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.queries.CategoryQuery; import io.sphere.sdk.queries.PagedQueryResult; import org.junit.Test; import testutils.WithPlayJavaSphereClient; import java.util.Locale; import static org.fest.assertions.Assertions.assertThat; public class ApplicationControllerIntegrationTest extends WithPlayJavaSphereClient { @Test public void itFindsSomeCategories() throws Exception { final PagedQueryResult<Category> queryResult = client.execute(CategoryQuery.of()).get(4000); final int count = queryResult.size(); assertThat(count).isGreaterThan(3); //this is a project specific assertion as example assertThat(queryResult.getResults().get(0).getName().get(Locale.ENGLISH).get()).isEqualTo("Tank tops"); } }
package controllers; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.queries.CategoryQuery; import io.sphere.sdk.queries.PagedQueryResult; import org.junit.Test; import testutils.WithPlayJavaSphereClient; import java.util.Locale; import static org.fest.assertions.Assertions.assertThat; public class ApplicationControllerIntegrationTest extends WithPlayJavaSphereClient { @Test public void itFindsSomeCategories() throws Exception { final PagedQueryResult<Category> queryResult = client.execute(CategoryQuery.of()).get(2000); final int count = queryResult.size(); assertThat(count).isGreaterThan(3); //this is a project specific assertion as example assertThat(queryResult.getResults().get(0).getName().get(Locale.ENGLISH).get()).isEqualTo("Tank tops"); } }
Set state session-id only when state is present Signed-off-by: Ivan Kanakarakis <f60d6943d72436645c4304926eeeac2718a1142c@gmail.com>
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ session_id = get_session_id(state) if state is not None: state[LOGGER_STATE_KEY] = session_id logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
from uuid import uuid4 # The state key for saving the session id in the state LOGGER_STATE_KEY = "SESSION_ID" LOG_FMT = "[{id}] {message}" def get_session_id(state): session_id = ( "UNKNOWN" if state is None else state.get(LOGGER_STATE_KEY, uuid4().urn) ) return session_id def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) :param message: Message :param state: The current state :param kwargs: set exc_info=True to get an exception stack trace in the log """ state[LOGGER_STATE_KEY] = session_id = get_session_id(state) logline = LOG_FMT.format(id=session_id, message=message) logger.log(level, logline, **kwargs)
function: Rename method to std name
/* * * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.common.function; import java.util.function.Consumer; /** * Represents a consumer that accepts three arguments. This is the three-arity * specialization of {@link java.util.function.Consumer}. * * @param <T> the type of the first argument to the consumer * @param <U> the type of the second argument to the consumer * @param <V> the type of the third argument to the consumer * * @see Consumer */ @FunctionalInterface public interface TriConsumer<T, U, V> { /** * Performs this operation on the given argument. * * @param t the first consumer argument * @param u the second consumer argument * @param v the third consumer argument */ void accept(T t, U u, V v); }
/* * * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.common.function; import java.util.function.Consumer; /** * Represents a consumer that accepts three arguments. This is the three-arity * specialization of {@link java.util.function.Consumer}. * * @param <T> the type of the first argument to the consumer * @param <U> the type of the second argument to the consumer * @param <V> the type of the third argument to the consumer * * @see Consumer */ @FunctionalInterface public interface TriConsumer<T, U, V> { /** * Performs this operation on the given argument. * * @param t the first consumer argument * @param u the second consumer argument * @param v the third consumer argument */ void apply(T t, U u, V v); }
Add display name to the constructor for User
import bcrypt from grum import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True) password = db.Column(db.String(128)) display_name = db.Column(db.String(128)) def __init__(self, username=None, display_name=None, password=None): if username: self.username = username if display_name: self.display_name = display_name if password: self.set_password(password) def set_password(self, plaintext_password): self.password = bcrypt.hashpw(plaintext_password.encode('utf-8'), bcrypt.gensalt()) def validate_password(self, plaintext_password): hashed = bcrypt.hashpw(plaintext_password.encode('utf-8'), bytes(self.password.encode('utf-8'))) return hashed == bytes(self.password.encode('utf-8')) class EmailAccount(db.Model): address = db.Column(db.String(128), primary_key=True) owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) mg_api = db.Column(db.String(64))
import bcrypt from grum import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True) password = db.Column(db.String(128)) display_name = db.Column(db.String(128)) def __init__(self, username=None, password=None): if username: self.username = username if password: self.set_password(password) def set_password(self, plaintext_password): self.password = bcrypt.hashpw(plaintext_password.encode('utf-8'), bcrypt.gensalt()) def validate_password(self, plaintext_password): hashed = bcrypt.hashpw(plaintext_password.encode('utf-8'), bytes(self.password.encode('utf-8'))) return hashed == bytes(self.password.encode('utf-8')) class EmailAccount(db.Model): address = db.Column(db.String(128), primary_key=True) owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) mg_api = db.Column(db.String(64))
Fix for 3.3 and 3.4
# -*- encoding: utf-8 -*- # ! python2 from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals """Tests for django-custom-500's decorators""" import unittest import requests from django.test import TestCase, LiveServerTestCase class NormalViewTestCase(TestCase): def test_normal_view(self): ok_response = self.client.get('/normal-view-that-returns-data') self.assertIn('42', ok_response.content) class InternalErrorTestCase(LiveServerTestCase): def test_error_view(self): error_response = requests.get('%s%s' % (self.live_server_url, '/view-that-raises-value-error')) self.assertEqual(error_response.status_code, 500) self.assertIn("500 Internal Server Error", error_response.content) if __name__ == "__main__": unittest.main()
# -*- encoding: utf-8 -*- # ! python2 from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals """Tests for django-custom-500's decorators""" import unittest import requests from django.test import TestCase, LiveServerTestCase class NormalViewTestCase(TestCase): def test_normal_view(self): ok_response = self.client.get('/normal-view-that-returns-data') self.assertTrue('42' in ok_response.content) class InternalErrorTestCase(LiveServerTestCase): def test_error_view(self): error_response = requests.get('%s%s' % (self.live_server_url, '/view-that-raises-value-error')) self.assertEqual(error_response.status_code, 500) self.assertIn("500 Internal Server Error", error_response.content) if __name__ == "__main__": unittest.main()
Fix the output now that we are using the default output (nested) instead of hard coding it to yaml
# -*- coding: utf-8 -*- ''' Tests for the salt-run command ''' # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_active(self): ''' jobs.active ''' ret = self.run_run_plus('jobs.active') self.assertEqual(ret['fun'], {}) self.assertEqual(ret['out'], []) def test_lookup_jid(self): ''' jobs.lookup_jid ''' ret = self.run_run_plus('jobs.lookup_jid', '', '23974239742394') self.assertEqual(ret['fun'], {}) self.assertEqual(ret['out'], []) def test_list_jobs(self): ''' jobs.list_jobs ''' ret = self.run_run_plus('jobs.list_jobs') self.assertIsInstance(ret['fun'], dict) if __name__ == '__main__': from integration import run_tests run_tests(ManageTest)
# -*- coding: utf-8 -*- ''' Tests for the salt-run command ''' # Import Salt Testing libs from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import integration class ManageTest(integration.ShellCase): ''' Test the manage runner ''' def test_active(self): ''' jobs.active ''' ret = self.run_run_plus('jobs.active') self.assertEqual(ret['fun'], {}) self.assertEqual(ret['out'], ['{}']) def test_lookup_jid(self): ''' jobs.lookup_jid ''' ret = self.run_run_plus('jobs.lookup_jid', '', '23974239742394') self.assertEqual(ret['fun'], {}) self.assertEqual(ret['out'], []) def test_list_jobs(self): ''' jobs.list_jobs ''' ret = self.run_run_plus('jobs.list_jobs') self.assertIsInstance(ret['fun'], dict) if __name__ == '__main__': from integration import run_tests run_tests(ManageTest)
Use new golang.org/x/ import paths
package slug import ( "golang.org/x/text/unicode/norm" "regexp" "strings" "unicode" ) // don't even quote these var _SKIP = []*unicode.RangeTable{ unicode.Mark, unicode.Sk, unicode.Lm, } var _SAFE = []*unicode.RangeTable{ unicode.Letter, unicode.Number, } func safe(r rune) rune { switch { case unicode.IsOneOf(_SKIP, r): return -1 case unicode.IsOneOf(_SAFE, r): return unicode.ToLower(r) } return '-' } var _DOUBLEDASH_RE = regexp.MustCompile("--+") func noRepeat(s string) string { return _DOUBLEDASH_RE.ReplaceAllString(s, "-") } // Slugify a string. The result will only contain lowercase letters, // digits and dashes. It will not begin or end with a dash, and it // will not contain runs of multiple dashes. // // It is NOT forced into being ASCII, but may contain any Unicode // characters, with the above restrictions. func Slug(s string) string { s = norm.NFKD.String(s) s = strings.Map(safe, s) s = strings.Trim(s, "-") s = noRepeat(s) return s }
package slug import ( "code.google.com/p/go.text/unicode/norm" "regexp" "strings" "unicode" ) // don't even quote these var _SKIP = []*unicode.RangeTable{ unicode.Mark, unicode.Sk, unicode.Lm, } var _SAFE = []*unicode.RangeTable{ unicode.Letter, unicode.Number, } func safe(r rune) rune { switch { case unicode.IsOneOf(_SKIP, r): return -1 case unicode.IsOneOf(_SAFE, r): return unicode.ToLower(r) } return '-' } var _DOUBLEDASH_RE = regexp.MustCompile("--+") func noRepeat(s string) string { return _DOUBLEDASH_RE.ReplaceAllString(s, "-") } // Slugify a string. The result will only contain lowercase letters, // digits and dashes. It will not begin or end with a dash, and it // will not contain runs of multiple dashes. // // It is NOT forced into being ASCII, but may contain any Unicode // characters, with the above restrictions. func Slug(s string) string { s = norm.NFKD.String(s) s = strings.Map(safe, s) s = strings.Trim(s, "-") s = noRepeat(s) return s }
Fix unbounded long lines breaking log send for gui
// @flow import {forwardLogs, enableActionLogging, immediateStateLogging} from '../local-debug' import {noPayloadTransformer} from '../constants/types/flux' import {stateLogTransformer} from '../constants/reducer' import {setupLogger, immutableToJS} from '../util/periodic-logger' function makeActionToLog (action, oldState) { if (action.logTransformer) { try { return action.logTransformer(action, oldState) } catch (e) { console.warn('Action logger error', e) } } return noPayloadTransformer(action, oldState) } const logger = enableActionLogging ? setupLogger('actionLogger', 100, immediateStateLogging, immutableToJS, 50) : {log: () => {}} export const actionLogger = (store: any) => (next: any) => (action: any) => { const oldState = store.getState() const actionToLog = makeActionToLog(action, oldState) const log1 = [`Dispatching action: ${action.type}: `, forwardLogs ? JSON.stringify(actionToLog) : actionToLog] console.log(log1) const result = next(action) const logState = stateLogTransformer(store.getState()) logger.log('State:', [JSON.stringify(logState, null, 2)]) return result }
// @flow import {forwardLogs, enableActionLogging, immediateStateLogging} from '../local-debug' import {noPayloadTransformer} from '../constants/types/flux' import {stateLogTransformer} from '../constants/reducer' import {setupLogger, immutableToJS} from '../util/periodic-logger' function makeActionToLog (action, oldState) { if (action.logTransformer) { try { return action.logTransformer(action, oldState) } catch (e) { console.warn('Action logger error', e) } } return noPayloadTransformer(action, oldState) } const logger = enableActionLogging ? setupLogger('actionLogger', 100, immediateStateLogging, immutableToJS, 50) : {log: () => {}} export const actionLogger = (store: any) => (next: any) => (action: any) => { const oldState = store.getState() const actionToLog = makeActionToLog(action, oldState) const log1 = [`Dispatching action: ${action.type}: `, forwardLogs ? JSON.stringify(actionToLog) : actionToLog] console.log(log1) const result = next(action) const logState = stateLogTransformer(store.getState()) logger.log('State:', logState) return result }
Clean up middleware aware code docs
<?php declare(strict_types=1); namespace League\Route\Middleware; use Psr\Http\Server\MiddlewareInterface; interface MiddlewareAwareInterface { /** * Add a middleware to the stack * * @param \Psr\Http\Server\MiddlewareInterface $middleware * * @return static */ public function middleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface; /** * Add multiple middleware to the stack * * @param \Psr\Http\Server\MiddlewareInterface[] $middlewares * * @return static */ public function middlewares(array $middlewares) : MiddlewareAwareInterface; /** * Prepend a middleware to the stack * * @param \Psr\Http\Server\MiddlewareInterface $middleware * * @return static */ public function prependMiddleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface; /** * Shift a middleware from beginning of stack * * @return \Psr\Http\Server\MiddlewareInterface|null */ public function shiftMiddleware() : MiddlewareInterface; /** * Get the stack of middleware * * @return \Psr\Http\Server\MiddlewareInterface[] */ public function getMiddlewareStack() : iterable; }
<?php declare(strict_types=1); namespace League\Route\Middleware; use Psr\Http\Server\MiddlewareInterface; interface MiddlewareAwareInterface { /** * Add a middleware to the stack. * * @param \Psr\Http\Server\MiddlewareInterface $middleware * * @return self */ public function middleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface; /** * Add a middleware to the stack. * * @param \Psr\Http\Server\MiddlewareInterface[] $middlewares * * @return self */ public function middlewares(array $middlewares) : MiddlewareAwareInterface; /** * Add a middleware to the stack. * * @param \Psr\Http\Server\MiddlewareInterface $middleware * * @return self */ public function prependMiddleware(MiddlewareInterface $middleware) : MiddlewareAwareInterface; /** * Shift middleware from beginning of stack. * * @return \Psr\Http\Server\MiddlewareInterface */ public function shiftMiddleware() : MiddlewareInterface; /** * Get the stack of middleware * * @return \Psr\Http\Server\MiddlewareInterface[] */ public function getMiddlewareStack() : iterable; }
Fix Checkstyle issues / add missing license header
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.zookeeper.ha; import org.apache.camel.ha.CamelClusterService; import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringZooKeeperClusteredRouteConfigurationTest extends CamelSpringTestSupport { @Test public void test() { assertNotNull(context.hasService(CamelClusterService.class)); assertTrue(context.getRoutePolicyFactories().stream().anyMatch(ClusteredRoutePolicyFactory.class::isInstance)); } // *********************** // Routes // *********************** @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/component/zookeeper/ha/SpringZooKeeperClusteredRouteConfigurationTest.xml"); } }
package org.apache.camel.component.zookeeper.ha; import org.apache.camel.ha.CamelClusterService; import org.apache.camel.impl.ha.ClusteredRoutePolicyFactory; import org.apache.camel.test.spring.CamelSpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringZooKeeperClusteredRouteConfigurationTest extends CamelSpringTestSupport { @Test public void test() { assertNotNull(context.hasService(CamelClusterService.class)); assertTrue(context.getRoutePolicyFactories().stream().anyMatch(ClusteredRoutePolicyFactory.class::isInstance)); } // *********************** // Routes // *********************** @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/component/zookeeper/ha/SpringZooKeeperClusteredRouteConfigurationTest.xml"); } }
Improve error names when running integration test
'use strict'; var opbeat = require('../../'); var inquirer = require('inquirer'); var questions = [ { name: 'app_id', message: 'App ID' }, { name: 'organization_id', message: 'Organization ID' }, { name: 'secret_token', message: 'Secret token' } ]; var test = function (options) { options.env = 'production'; options.level = 'fatal'; options.handleExceptions = false; var client = opbeat.createClient(options); client.handleUncaughtExceptions(function (err) { console.log('Handled uncaught exception correctly'); process.exit(); }); console.log('Capturing error...'); client.captureError(new Error('This is an Error object'), function (err, url) { if (err) console.log('Something went wrong:', err.message); console.log('The error have been logged at:', url); console.log('Capturing message...'); client.captureError('This is a string', function (err, url) { if (err) console.log('Something went wrong:', err.message); console.log('The message have been logged at:', url); console.log('Throwing exception...'); throw new Error('This Error was thrown'); }); }); }; inquirer.prompt(questions, function (answers) { // inquirer gives quite a long stack-trace, so let's do this async process.nextTick(test.bind(null, answers)); });
'use strict'; var opbeat = require('../../'); var inquirer = require('inquirer'); var questions = [ { name: 'app_id', message: 'App ID' }, { name: 'organization_id', message: 'Organization ID' }, { name: 'secret_token', message: 'Secret token' } ]; var test = function (options) { options.env = 'production'; options.level = 'fatal'; options.handleExceptions = false; var client = opbeat.createClient(options); client.handleUncaughtExceptions(function (err) { console.log('Handled uncaught exception correctly'); process.exit(); }); console.log('Capturing error...'); client.captureError(new Error('captureError()'), function (err, url) { if (err) console.log('Something went wrong:', err.message); console.log('The error have been logged at:', url); console.log('Capturing message...'); client.captureError('captureError()', function (err, url) { if (err) console.log('Something went wrong:', err.message); console.log('The message have been logged at:', url); console.log('Throwing exception...'); throw new Error('throw'); }); }); }; inquirer.prompt(questions, function (answers) { // inquirer gives quite a long stack-trace, so let's do this async process.nextTick(test.bind(null, answers)); });
Remove obrigatoriedade da versão para retorno da SEFAZ MG
package com.fincatto.documentofiscal.nfe400.classes; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import com.fincatto.documentofiscal.DFBase; @Root(name = "protNFe") public class NFProtocolo extends DFBase { private static final long serialVersionUID = -784305871769382618L; @Attribute(name = "versao", required = false) private String versao; @Element(name = "infProt", required = true) private NFProtocoloInfo protocoloInfo; public void setVersao(final String versao) { this.versao = versao; } public void setProtocoloInfo(final NFProtocoloInfo protocoloInfo) { this.protocoloInfo = protocoloInfo; } public NFProtocoloInfo getProtocoloInfo() { return this.protocoloInfo; } public String getVersao() { return this.versao; } }
package com.fincatto.documentofiscal.nfe400.classes; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element; import org.simpleframework.xml.Root; import com.fincatto.documentofiscal.DFBase; @Root(name = "protNFe") public class NFProtocolo extends DFBase { private static final long serialVersionUID = -784305871769382618L; @Attribute(name = "versao", required = true) private String versao; @Element(name = "infProt", required = true) private NFProtocoloInfo protocoloInfo; public void setVersao(final String versao) { this.versao = versao; } public void setProtocoloInfo(final NFProtocoloInfo protocoloInfo) { this.protocoloInfo = protocoloInfo; } public NFProtocoloInfo getProtocoloInfo() { return this.protocoloInfo; } public String getVersao() { return this.versao; } }
Add properties datastore to the module datastore.
/** * `modules/analytics-4` data store * * 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. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { STORE_NAME } from './constants'; import baseModuleStore from './base'; import properties from './properties'; const store = Data.combineStores( baseModuleStore, properties, ); export const initialState = store.initialState; export const actions = store.actions; export const controls = store.controls; export const reducer = store.reducer; export const resolvers = store.resolvers; export const selectors = store.selectors; export const registerStore = ( registry ) => { registry.registerStore( STORE_NAME, store ); }; export default store;
/** * `modules/analytics-4` data store * * 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. */ /** * Internal dependencies */ import Data from 'googlesitekit-data'; import baseModuleStore from './base'; import { STORE_NAME } from './constants'; const store = Data.combineStores( baseModuleStore, ); export const initialState = store.initialState; export const actions = store.actions; export const controls = store.controls; export const reducer = store.reducer; export const resolvers = store.resolvers; export const selectors = store.selectors; export const registerStore = ( registry ) => { registry.registerStore( STORE_NAME, store ); }; export default store;
Implement Infested Wolf and Princess Huhuran
from ..utils import * ## # Minions class OG_179: "Fiery Bat" deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1) class OG_292: "Forlorn Stalker" play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e") OG_292e = buff(+1, +1) class OG_216: "Infested Wolf" deathrattle = Summon(CONTROLLER, "OG_216a") * 2 class OG_309: "Princess Huhuran" play = Deathrattle(TARGET) ## # Spells class OG_045: "Infest" play = Buff(FRIENDLY_MINIONS, "OG_045a") class OG_045a: "Nerubian Spores" deathrattle = Give(CONTROLLER, RandomBeast()) tags = {GameTag.DEATHRATTLE: True} class OG_061: "On the Hunt" play = Hit(TARGET, 1), Summon(CONTROLLER, "OG_061t") class OG_211: "Call of the Wild" play = ( Summon(CONTROLLER, "NEW1_034"), Summon(CONTROLLER, "NEW1_033"), Summon(CONTROLLER, "NEW1_032") )
from ..utils import * ## # Minions class OG_179: "Fiery Bat" deathrattle = Hit(RANDOM_ENEMY_CHARACTER, 1) class OG_292: "Forlorn Stalker" play = Buff(FRIENDLY_HAND + MINION + DEATHRATTLE, "OG_292e") OG_292e = buff(+1, +1) ## # Spells class OG_045: "Infest" play = Buff(FRIENDLY_MINIONS, "OG_045a") class OG_045a: "Nerubian Spores" deathrattle = Give(CONTROLLER, RandomBeast()) tags = {GameTag.DEATHRATTLE: True} class OG_061: "On the Hunt" play = Hit(TARGET, 1), Summon(CONTROLLER, "OG_061t") class OG_211: "Call of the Wild" play = ( Summon(CONTROLLER, "NEW1_034"), Summon(CONTROLLER, "NEW1_033"), Summon(CONTROLLER, "NEW1_032") )
Datalogger: Remove time.sleep from example, no longer required
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: i.set_defaults() i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() i.datalogger_stop() i.datalogger_start(start=0, duration=10, use_sd=True, ch1=True, ch2=True, filetype='bin') while True: time.sleep(1) trems, treme = i.datalogger_remaining() samples = i.datalogger_samples() print "Captured (%d samples); %d seconds from start, %d from end" % (samples, trems, treme) if i.datalogger_completed(): break e = i.datalogger_error() if e: print "Error occured: %s" % e i.datalogger_stop() i.datalogger_upload() except Exception as e: print e finally: m.close()
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.INFO) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name('example') i = Oscilloscope() m.attach_instrument(i) try: i.set_defaults() i.set_samplerate(10) i.set_xmode(OSC_ROLL) i.commit() time.sleep(0.8) i.datalogger_stop() i.datalogger_start(start=0, duration=10, use_sd=True, ch1=True, ch2=True, filetype='bin') while True: time.sleep(1) trems, treme = i.datalogger_remaining() samples = i.datalogger_samples() print "Captured (%d samples); %d seconds from start, %d from end" % (samples, trems, treme) if i.datalogger_completed(): break e = i.datalogger_error() if e: print "Error occured: %s" % e i.datalogger_stop() i.datalogger_upload() except Exception as e: print e finally: m.close()
Add Integration test to ensure new stylists are displaying.
import org.fluentlenium.adapter.FluentTest; import org.junit.ClassRule; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.junit.Rule; import static org.assertj.core.api.Assertions.assertThat; import static org.fluentlenium.core.filter.FilterConstructor.*; public class AppTest extends FluentTest { public WebDriver webDriver = new HtmlUnitDriver(); @Override public WebDriver getDefaultDriver() { return webDriver; } @ClassRule public static ServerRule server = new ServerRule(); @Rule public DatabaseRule database = new DatabaseRule(); @Test public void rootTest() { goTo("http://localhost:4567/"); assertThat(pageSource()).contains("Welcome to your Stylist Database"); } @Test public void stylistIsCreatedTest() { Stylist newStylist = new Stylist("Otto Von Bismarck"); newStylist.save(); String stylistPath = String.format("http://localhost:4567/stylist/%d", newStylist.getId()); goTo(stylistPath); assertThat(pageSource()).contains("Otto Von Bismarck"); } @Test public void stylistIsDisplayedTest() { Stylist newStylist = new Stylist("Otto Von Bismarck"); newStylist.save(); String stylistPath = String.format("http://localhost:4567/"); goTo(stylistPath); assertThat(pageSource()).contains("Otto Von Bismarck"); } }
import org.fluentlenium.adapter.FluentTest; import org.junit.ClassRule; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.junit.Rule; import static org.assertj.core.api.Assertions.assertThat; import static org.fluentlenium.core.filter.FilterConstructor.*; public class AppTest extends FluentTest { public WebDriver webDriver = new HtmlUnitDriver(); @Override public WebDriver getDefaultDriver() { return webDriver; } @ClassRule public static ServerRule server = new ServerRule(); @Rule public DatabaseRule database = new DatabaseRule(); @Test public void rootTest() { goTo("http://localhost:4567/"); assertThat(pageSource()).contains("Welcome to your Stylist Database"); } @Test public void categoryIsCreatedTest() { Stylist newStylist = new Stylist("Otto Von Bismarck"); newStylist.save(); String stylistPath = String.format("http://localhost:4567/stylist/%d", newStylist.getId()); goTo(stylistPath); assertThat(pageSource()).contains("Otto Von Bismarck"); } }
Add play, render and Say to toplevel namespace.
# -*- encoding: utf -*- import pyximport pyximport.install() from supriya.tools import * # noqa from supriya.tools.bindingtools import bind # noqa from supriya.tools.nonrealtimetools import Session # noqa from supriya.tools.servertools import ( # noqa AddAction, Buffer, BufferGroup, Bus, BusGroup, Group, Server, Synth, ) from supriya.tools.soundfiletools import ( # noqa HeaderFormat, SampleFormat, SoundFile, play, render, ) from supriya.tools.synthdeftools import ( # noqa CalculationRate, DoneAction, Envelope, Range, SynthDef, SynthDefBuilder, ) from supriya.tools.systemtools import ( # noqa Assets, Profiler, SupriyaConfiguration, ) from supriya.tools.wrappertools import ( # noqa Say, ) from abjad.tools.topleveltools import ( # noqa graph, new, ) from supriya import synthdefs # noqa __version__ = 0.1 supriya_configuration = SupriyaConfiguration() del SupriyaConfiguration
# -*- encoding: utf -*- import pyximport pyximport.install() from supriya.tools import * # noqa from supriya.tools.bindingtools import bind # noqa from supriya.tools.nonrealtimetools import Session # noqa from supriya.tools.servertools import ( # noqa AddAction, Buffer, BufferGroup, Bus, BusGroup, Group, Server, Synth, ) from supriya.tools.soundfiletools import ( # noqa HeaderFormat, SampleFormat, SoundFile, ) from supriya.tools.synthdeftools import ( # noqa CalculationRate, DoneAction, Range, SynthDef, SynthDefBuilder, ) from supriya.tools.systemtools import ( # noqa Assets, SupriyaConfiguration, ) from abjad.tools.topleveltools import ( # noqa graph, new, ) from supriya import synthdefs # noqa __version__ = 0.1 supriya_configuration = SupriyaConfiguration() del SupriyaConfiguration
Fix create user command to work locally and on heroku
import os from flask.ext.script import Manager from flask.ext.migrate import Migrate from flask.ext.migrate import MigrateCommand from flask_security.utils import encrypt_password from service.models import * from service import app from service import db from service import user_datastore app.config.from_object(os.environ['SETTINGS']) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.option('--email', dest='email') @manager.option('--password', dest='password') def create_user(email, password): if not user_datastore.find_user(email=email): user_datastore.create_user(email=email, password=encrypt_password(password)) db.session.commit() if __name__ == '__main__': manager.run()
import os from flask.ext.script import Manager from flask.ext.migrate import Migrate from flask.ext.migrate import MigrateCommand from flask_security.utils import encrypt_password from service.models import * from service import app from service import db from service import user_datastore app.config.from_object(os.environ['SETTINGS']) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.option('-e', '--email', dest='email') @manager.option('-p', '--password', dest='password') def create_user(email, password): if not user_datastore.find_user(email=email): user_datastore.create_user(email=email, password=encrypt_password(password)) db.session.commit() if __name__ == '__main__': manager.run()
Remove useless code +cache improvement
'use strict'; var config = require('./server/config'); var items = require('./server/data/items'); var express = require('express'); var handlebars = require('express-handlebars'); var app = express(); // Middlewares configuration var oneDay = 86400000; app.use(express.static('build', { maxAge: oneDay })); // Handlebars configuration app.set('views', 'client/views'); app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/partials/', 'client/views/components/'], defaultLayout: __dirname + '/client/views/_layout.hbs' })); app.set('view engine', '.hbs'); // Starts application listening app.listen(config.port, (err) => { console.log('running on ' + config.port); }); // Regsiters routes app.use('/', require('./server/routes/sitemapRoute')); app.use('/', require('./server/routes/indexRoute')); app.use('/', require('./server/routes/itemRoute'));
'use strict'; var config = require('./server/config'); var items = require('./server/data/items'); var express = require('express'); var handlebars = require('express-handlebars'); var app = express(); // Middlewares configuration var oneWeek = 604800000; app.use(express.static('build')); app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] })); // Handlebars configuration app.set('views', 'client/views'); app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/partials/', 'client/views/components/'], defaultLayout: __dirname + '/client/views/_layout.hbs' })); app.set('view engine', '.hbs'); // Starts application listening app.listen(config.port, (err) => { console.log('running on ' + config.port); }); // Restore isActive value for every items app.use(function (req, res, next) { items.forEach(function (item) { item.isActive = false; }); next(); }); // Regsiters routes app.use('/', require('./server/routes/sitemapRoute')); app.use('/', require('./server/routes/indexRoute')); app.use('/', require('./server/routes/itemRoute'));
Update default location of server.
'use strict'; var path = require('path'); var nconf = require('nconf'); const DEFAULT_HOST = 'http://next.openspending.org'; const DEFAULT_BASE_PATH = ''; nconf.file({ file: path.join(__dirname, '/../../settings.json') }); var apiHost = process.env.OS_VIEWER_API_HOST || DEFAULT_HOST; var authHost = process.env.OS_VIEWER_AUTH_HOST || DEFAULT_HOST; // this is the object that you want to override in your own local config nconf.defaults({ env: process.env.NODE_ENV || 'development', debug: process.env.DEBUG || false, app: { port: process.env.PORT || 5000 }, api: { url: apiHost + '/api/3' }, authLibraryUrl: authHost + '/permit/lib', basePath: process.env.OS_VIEWER_BASE_PATH || DEFAULT_BASE_PATH }); module.exports = { get: nconf.get.bind(nconf), set: nconf.set.bind(nconf), reset: nconf.reset.bind(nconf) };
'use strict'; var path = require('path'); var nconf = require('nconf'); nconf.file({ file: path.join(__dirname, '/../../settings.json') }); var apiHost = process.env.OS_VIEWER_API_HOST || 'http://s145.okserver.org'; var authHost = process.env.OS_VIEWER_AUTH_HOST || 'http://s145.okserver.org'; // this is the object that you want to override in your own local config nconf.defaults({ env: process.env.NODE_ENV || 'development', debug: process.env.DEBUG || false, app: { port: process.env.PORT || 5000 }, api: { url: apiHost + '/api/3' }, authLibraryUrl: authHost + '/permit/lib', basePath: process.env.OS_VIEWER_BASE_PATH || '' }); module.exports = { get: nconf.get.bind(nconf), set: nconf.set.bind(nconf), reset: nconf.reset.bind(nconf) };
Change to simple removal of the share panel and button
// ==UserScript== // @name Selfish Youtube // @namespace https://github.com/ASzc/selfish-youtube // @description On the watch page, remove the share panel. // @include http://youtube.com/* // @include http://*.youtube.com/* // @include https://youtube.com/* // @include https://*.youtube.com/* // ==/UserScript== var panelName = "action-panel-share"; // Remove panel var actionPanelShare = document.getElementById(panelName); actionPanelShare.parentNode.removeChild(actionPanelShare); // Remove buttons targeting the panel var buttons = document.body.getElementsByTagName("button"); for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; var buttonDTF = button.getAttribute("data-trigger-for"); if (buttonDTF != null && buttonDTF == panelName) { button.parentNode.removeChild(button); } }
// ==UserScript== // @name Selfish Youtube // @namespace https://github.com/ASzc/selfish-youtube // @description On the watch page, prevent the share panel from being switched to after pressing Like // @include http://youtube.com/* // @include http://*.youtube.com/* // @include https://youtube.com/* // @include https://*.youtube.com/* // ==/UserScript== var oldPanelName = "action-panel-share"; var newPanelName = "action-panel-share-foo"; // Change share panel id so Google's JS can't reference it properly unless we give it the new name var actionPanelShare = document.getElementById(oldPanelName); actionPanelShare.id = newPanelName; // Change target of Share UI button so it points at the new panel ID var buttons = document.body.getElementsByTagName("button"); for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; var buttonDTF = button.getAttribute("data-trigger-for"); if (buttonDTF != null && buttonDTF == oldPanelName) { button.setAttribute("data-trigger-for", newPanelName); } }
[PackageBuilder] Improve param typo proofreader test
<?php declare(strict_types=1); namespace Symplify\PackageBuilder\Tests\Parameter\ParameterTypoProofreader; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\ArrayInput; use Symplify\PackageBuilder\Exception\Parameter\ParameterTypoException; use Symplify\PackageBuilder\Tests\ContainerFactory; final class ParameterTypoProofreaderTest extends TestCase { /** * @var ContainerInterface */ private $container; protected function setUp(): void { $this->container = (new ContainerFactory())->createWithConfig(__DIR__ . '/config.yml'); } public function testConsole(): void { /** @var Application $application */ $application = $this->container->get(Application::class); $application->setCatchExceptions(false); $this->expectException(ParameterTypoException::class); $this->expectExceptionMessage('Parameter "parameters > typo" does not exist. Use "parameters > correct" instead.'); $application->run(new ArrayInput(['command' => 'list'])); } }
<?php declare(strict_types=1); namespace Symplify\PackageBuilder\Tests\Parameter\ParameterTypoProofreader; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Symfony\Component\Console\Application; use Symfony\Component\Console\Input\ArrayInput; use Symplify\PackageBuilder\Exception\Parameter\ParameterTypoException; use Symplify\PackageBuilder\Tests\ContainerFactory; final class ParameterTypoProofreaderTest extends TestCase { /** * @var ContainerInterface */ private $container; protected function setUp(): void { $this->container = (new ContainerFactory())->createWithConfig(__DIR__ . '/config.yml'); } public function testConsole(): void { /** @var Application $application */ $application = $this->container->get(Application::class); $application->setCatchExceptions(false); $this->expectException(ParameterTypoException::class); $application->run(new ArrayInput(['command' => 'list'])); } }
Replace WL.Server with MFP.Server in JavaScriptSQL adapter
/** * Copyright 2016 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. */ var getAccountsTransactionsStatement = "SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " + "FROM accounttransactions " + "WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " + "ORDER BY transactionDate DESC " + "LIMIT 20;"; //Invoke prepared SQL query and return invocation result function getAccountTransactions1(accountId){ return MFP.Server.invokeSQLStatement({ preparedStatement : getAccountsTransactionsStatement, parameters : [accountId, accountId] }); } //Invoke stored SQL procedure and return invocation result function getAccountTransactions2(accountId){ return MFP.Server.invokeSQLStoredProcedure({ procedure : "getAccountTransactions", parameters : [accountId] }); }
/** * Copyright 2016 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. */ var getAccountsTransactionsStatement = "SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " + "FROM accounttransactions " + "WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " + "ORDER BY transactionDate DESC " + "LIMIT 20;"; //Invoke prepared SQL query and return invocation result function getAccountTransactions1(accountId){ return WL.Server.invokeSQLStatement({ preparedStatement : getAccountsTransactionsStatement, parameters : [accountId, accountId] }); } //Invoke stored SQL procedure and return invocation result function getAccountTransactions2(accountId){ return WL.Server.invokeSQLStoredProcedure({ procedure : "getAccountTransactions", parameters : [accountId] }); }
Correct typo in test name
import os import numpy import pytest import helpers import meshio @pytest.mark.parametrize( "mesh", [helpers.tri_mesh, helpers.quad_mesh, helpers.tri_quad_mesh] ) def test_obj(mesh): def writer(*args, **kwargs): return meshio._obj.write(*args, **kwargs) for key in mesh.cells: mesh.cells[key] = mesh.cells[key].astype(numpy.int32) helpers.write_read(writer, meshio._obj.read, mesh, 1.0e-12) return @pytest.mark.parametrize( "filename, ref_sum, ref_num_cells", [("elephav.obj", 3.678372172450000e05, 1148)] ) def test_reference_file(filename, ref_sum, ref_num_cells): this_dir = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(this_dir, "meshes", "obj", filename) mesh = meshio.read(filename) tol = 1.0e-5 s = numpy.sum(mesh.points) assert abs(s - ref_sum) < tol * abs(ref_sum) assert len(mesh.cells["triangle"]) == ref_num_cells return
import os import numpy import pytest import helpers import meshio @pytest.mark.parametrize( "mesh", [helpers.tri_mesh, helpers.quad_mesh, helpers.tri_quad_mesh] ) def test_ply(mesh): def writer(*args, **kwargs): return meshio._obj.write(*args, **kwargs) for key in mesh.cells: mesh.cells[key] = mesh.cells[key].astype(numpy.int32) helpers.write_read(writer, meshio._obj.read, mesh, 1.0e-12) return @pytest.mark.parametrize( "filename, ref_sum, ref_num_cells", [("elephav.obj", 3.678372172450000e05, 1148)] ) def test_reference_file(filename, ref_sum, ref_num_cells): this_dir = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(this_dir, "meshes", "obj", filename) mesh = meshio.read(filename) tol = 1.0e-5 s = numpy.sum(mesh.points) assert abs(s - ref_sum) < tol * abs(ref_sum) assert len(mesh.cells["triangle"]) == ref_num_cells return
Remove hasmark from TAP titles.
/** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , n = 1; runner.on('start', function(){ console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pass', function(test){ console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ console.log('not ok %d %s', n, title(test)); console.log(err.stack.replace(/^/gm, ' ')); }); } /** * Return a TAP-safe title of `test` * * @param {Object} test * @return {String} * @api private */ function title(test) { return test.fullTitle().replace(/#/g, ''); }
/** * Module dependencies. */ var Base = require('./base') , cursor = Base.cursor , color = Base.color; /** * Expose `TAP`. */ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * * @param {Runner} runner * @api public */ function TAP(runner) { Base.call(this, runner); var self = this , stats = this.stats , total = runner.total , n = 1; runner.on('start', function(){ console.log('%d..%d', 1, total); }); runner.on('test end', function(){ ++n; }); runner.on('pass', function(test){ console.log('ok %d %s', n, test.fullTitle()); }); runner.on('fail', function(test, err){ console.log('not ok %d %s', n, test.fullTitle()); console.log(err.stack.replace(/^/gm, ' ')); }); }
Use $control as variable name
!function(root, name, make) { if (typeof module != 'undefined' && module.exports) module.exports = make() else if (typeof define == 'function' && define.amd) define(make) else root[name] = make() }(this, 'associated', function() { function control($label) { var id = $label.attr('for') return id ? new $label.constructor('#' + id) : $label.find('input,textarea,select,button') } function label($control) { var $parent = $control.closest('label') return $parent.length ? $parent : forId($control).first() } function forId($control) { var id = $control.attr('id') return new $control.constructor(id ? 'label[for="' + id + '"]' : id) } function labels($control) { return $control.closest('label').add(forId($control)) } return { control: control, label: label, labels: labels } });
!function(root, name, make) { if (typeof module != 'undefined' && module.exports) module.exports = make() else if (typeof define == 'function' && define.amd) define(make) else root[name] = make() }(this, 'associated', function() { function control($label) { var id = $label.attr('for') return id ? new $label.constructor('#' + id) : $label.find('input,textarea,select,button') } function label($input) { var $parent = $input.closest('label') return $parent.length ? $parent : forId($input).first() } function forId($input) { var id = $input.attr('id') return new $input.constructor(id ? 'label[for="' + id + '"]' : id) } function labels($input) { return $input.closest('label').add(forId($input)) } return { control: control, label: label, labels: labels } });
Use globals for major bits of package data
from setuptools import setup VERSION = '2.0.2' VERSION_TAG = 'v%s' % VERSION README_URL = ('https://github.com/briancline/crm114-python' '/blob/%s/README.md' % VERSION_TAG) setup( name='crm114', version=VERSION, author='Brian Cline', author_email='brian.cline@gmail.com', description=('Python wrapper classes for the CRM-114 Discriminator ' '(http://crm114.sourceforge.net/)'), license = 'MIT', keywords = 'crm114 text analysis classifier kubrick', url = 'http://packages.python.org/crm114', packages=['crm114'], long_description='See README.md for full details, or %s.' % README_URL, classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Adaptive Technologies', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing', ], )
from setuptools import setup setup( name='crm114', version='2.0.2', author='Brian Cline', author_email='brian.cline@gmail.com', description=('Python wrapper classes for the CRM-114 Discriminator ' '(http://crm114.sourceforge.net/)'), license = 'MIT', keywords = 'crm114 text analysis classifier', url = 'http://packages.python.org/crm114', packages=['crm114'], long_description='See README.md for full details, or ' 'https://github.com/briancline/crm114-python' '/blob/v2.0.1/README.md.', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Adaptive Technologies', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing', ], )
Simplify fallback behavior for tests
/* * Copyright 2020 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. */ package com.google.android.gnd.persistence.remote.firestore.schema; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gnd.model.User; /** Converts between Firestore objects and {@link User} instances. */ class UserConverter { @NonNull static UserNestedObject toNestedObject(@NonNull User user) { return new UserNestedObject(user.getId(), user.getEmail(), user.getDisplayName()); } @NonNull static User toUser(@Nullable UserNestedObject ud) { // Degrade gracefully when user missing in remote db. if (ud == null || ud.getId() == null) { ud = UserNestedObject.UNKNOWN_USER; } return User.builder() .setId(ud.getId()) .setEmail(ud.getEmail() == null ? "" : ud.getEmail()) .setDisplayName(ud.getDisplayName() == null ? "" : ud.getDisplayName()) .build(); } }
/* * Copyright 2020 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. */ package com.google.android.gnd.persistence.remote.firestore.schema; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gnd.model.User; /** Converts between Firestore objects and {@link User} instances. */ class UserConverter { @NonNull static UserNestedObject toNestedObject(@NonNull User user) { return new UserNestedObject(user.getId(), user.getEmail(), user.getDisplayName()); } @NonNull static User toUser(@Nullable UserNestedObject ud) { if (ud == null || ud.getId() == null || ud.getEmail() == null || ud.getDisplayName() == null) { // Degrade gracefully when user info missing in remote db. ud = UserNestedObject.UNKNOWN_USER; } return User.builder() .setId(ud.getId()) .setEmail(ud.getEmail()) .setDisplayName(ud.getDisplayName()) .build(); } }
Correct icon for web module
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.openapi.module; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.util.IconLoader; import org.jetbrains.annotations.NonNls; import javax.swing.*; /** * @author yole */ public abstract class WebModuleTypeBase<T extends ModuleBuilder> extends ModuleType<T> { @NonNls public static final String WEB_MODULE = "WEB_MODULE"; private static final Icon WEB_MODULE_ICON = IconLoader.getIcon("/javaee/webModuleBig.png"); public WebModuleTypeBase() { super(WEB_MODULE); } public String getName() { return ProjectBundle.message("module.web.title"); } public String getDescription() { return ProjectBundle.message("module.web.description"); } public Icon getBigIcon() { return WEB_MODULE_ICON; } public Icon getNodeIcon(boolean isOpened) { return getBigIcon(); } }
package com.intellij.openapi.module; import com.intellij.ide.util.projectWizard.ModuleBuilder; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.util.IconLoader; import org.jetbrains.annotations.NonNls; import javax.swing.*; /** * @author yole */ public abstract class WebModuleTypeBase<T extends ModuleBuilder> extends ModuleType<T> { @NonNls public static final String WEB_MODULE = "WEB_MODULE"; public WebModuleTypeBase() { super(WEB_MODULE); } public String getName() { return ProjectBundle.message("module.web.title"); } public String getDescription() { return ProjectBundle.message("module.web.description"); } public Icon getBigIcon() { return IconLoader.getIcon(((ApplicationInfoEx)ApplicationInfo.getInstance()).getSmallIconUrl()); } public Icon getNodeIcon(boolean isOpened) { return getBigIcon(); } }
Add an alias !tous for !all
#!/usr/bin/env python2 # -*- coding: utf8 -*- from taemin import plugin class TaeminCafe(plugin.TaeminPlugin): helper = {"all": "Envoie un message à tout le monde", "cafe": "Appelle tout le monde pour prendre un café ;)"} def on_pubmsg(self, msg): if msg.key not in ("all", 'tous', "cafe"): return chan = msg.chan.name message = " ".join([user.name for user in self.taemin.list_users(msg.chan)]) if msg.key == "cafe": message = "<<< CAFE !!! \\o/ %s \\o/ !!! CAFE >>>" % message else: message = "%s %s" % (message, msg.value) self.privmsg(chan, message)
#!/usr/bin/env python2 # -*- coding: utf8 -*- from taemin import plugin class TaeminCafe(plugin.TaeminPlugin): helper = {"all": "Envoie un message à tout le monde", "cafe": "Appelle tout le monde pour prendre un café ;)"} def on_pubmsg(self, msg): if msg.key not in ("all", "cafe"): return chan = msg.chan.name message = " ".join([user.name for user in self.taemin.list_users(msg.chan)]) if msg.key == "cafe": message = "<<< CAFE !!! \\o/ %s \\o/ !!! CAFE >>>" % message else: message = "%s %s" % (message, msg.value) self.privmsg(chan, message)
Update requests requirement from <2.22,>=2.4.2 to >=2.4.2,<2.23 Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version. - [Release notes](https://github.com/requests/requests/releases) - [Changelog](https://github.com/kennethreitz/requests/blob/master/HISTORY.md) - [Commits](https://github.com/requests/requests/compare/v2.4.2...v2.22.0) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.23', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<3.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.1.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.22', 'future>=0.16,<0.18', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<3.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Fix an attribute for fake resource
<?php /** * This file is part of the BEAR.QueryRepository package. * * @license http://opensource.org/licenses/MIT MIT */ namespace FakeVendor\HelloWorld\Resource\App; use BEAR\RepositoryModule\Annotation\Cacheable; use BEAR\Resource\ResourceObject; /** * @Cacheable(type="view") */ #[Cacheable(type: 'view')] class View extends ResourceObject { public static $i = 1; public function toString() { if ($this->view) { return $this->view; } $this->view = (string) self::$i++ . $this['time']; return $this->view; } public function onGet() { $this['time'] = (string) \microtime(true); return $this; } }
<?php /** * This file is part of the BEAR.QueryRepository package. * * @license http://opensource.org/licenses/MIT MIT */ namespace FakeVendor\HelloWorld\Resource\App; use BEAR\RepositoryModule\Annotation\Cacheable; use BEAR\Resource\ResourceObject; /** * @Cacheable(type="view") */ #[Cacheable(type: 'value')] class View extends ResourceObject { public static $i = 1; public function toString() { if ($this->view) { return $this->view; } $this->view = (string) self::$i++ . $this['time']; return $this->view; } public function onGet() { $this['time'] = (string) \microtime(true); return $this; } }
Make python3 default also for the samples
#!/usr/bin/env python3 import pandas as pd import numpy as np import gtabview c_arr = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] columns = pd.MultiIndex.from_tuples(list(zip(*c_arr)), names=['V1', 'V2']) i_arr = [['bar', 'bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'baz'], ['foo', 'foo', 'qux', 'qux', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] index = pd.MultiIndex.from_tuples(list(zip(*i_arr)), names=['H1', 'H2', 'H3']) df = pd.DataFrame(np.random.randn(8, 8), columns=columns, index=index) gtabview.view(df)
#!/usr/bin/env python import pandas as pd import numpy as np import gtabview c_arr = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] columns = pd.MultiIndex.from_tuples(list(zip(*c_arr)), names=['V1', 'V2']) i_arr = [['bar', 'bar', 'bar', 'bar', 'baz', 'baz', 'baz', 'baz'], ['foo', 'foo', 'qux', 'qux', 'foo', 'foo', 'qux', 'qux'], ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']] index = pd.MultiIndex.from_tuples(list(zip(*i_arr)), names=['H1', 'H2', 'H3']) df = pd.DataFrame(np.random.randn(8, 8), columns=columns, index=index) gtabview.view(df)
Remove the restriction on cube element on the expression builder when creating a derived measure.
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs; import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider; import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter; import org.eclipse.birt.report.model.api.DesignElementHandle; /** * */ public class CrosstabComputedMeasureExpressionProvider extends CrosstabExpressionProvider { public CrosstabComputedMeasureExpressionProvider( DesignElementHandle handle ) { super( handle, null ); } // protected void addFilterToProvider( ) // { // this.addFilter( new ExpressionFilter( ) { // // public boolean select( Object parentElement, Object element ) // { // if ( ExpressionFilter.CATEGORY.equals( parentElement ) // && ExpressionProvider.CURRENT_CUBE.equals( element ) ) // { // return false; // } // return true; // } // } ); // } }
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.item.crosstab.internal.ui.dialogs; import org.eclipse.birt.report.designer.ui.dialogs.ExpressionProvider; import org.eclipse.birt.report.designer.ui.expressions.ExpressionFilter; import org.eclipse.birt.report.model.api.DesignElementHandle; /** * */ public class CrosstabComputedMeasureExpressionProvider extends CrosstabExpressionProvider { public CrosstabComputedMeasureExpressionProvider( DesignElementHandle handle ) { super( handle, null ); } protected void addFilterToProvider( ) { this.addFilter( new ExpressionFilter( ) { public boolean select( Object parentElement, Object element ) { if ( ExpressionFilter.CATEGORY.equals( parentElement ) && ExpressionProvider.CURRENT_CUBE.equals( element ) ) { return false; } return true; } } ); } }
Fix bug where white space only paragraphs showed
'use strict' module.exports = wrap wrap.needed = needed var phrasing = require('mdast-util-phrasing') /* Wrap all inline runs of MDAST content in `paragraph` nodes. */ function wrap(nodes) { var result = [] var length = nodes.length var index = -1 var node var queue while (++index < length) { node = nodes[index] if (phrasing(node)) { if (queue === undefined) { queue = [] } queue.push(node) } else { flush() result.push(node) } } flush() return result function flush() { if (queue !== undefined) { if ( queue.length !== 1 || queue[0].type !== 'text' || (queue[0].value !== ' ' && queue[0].value !== '\n') ) { result.push({type: 'paragraph', children: queue}) } } queue = undefined } } /* Check if there are non-inline MDAST nodes returned. * This is needed if a fragment is given, which could just be * a sentence, and doesn’t need a wrapper paragraph. */ function needed(nodes) { var length = nodes.length var index = -1 while (++index < length) { if (!phrasing(nodes[index])) { return true } } return false }
'use strict' module.exports = wrap wrap.needed = needed var phrasing = require('mdast-util-phrasing') /* Wrap all inline runs of MDAST content in `paragraph` nodes. */ function wrap(nodes) { var result = [] var length = nodes.length var index = -1 var node var queue while (++index < length) { node = nodes[index] if (phrasing(node)) { if (queue === undefined) { queue = [] } queue.push(node) } else { if (queue !== undefined) { result.push({type: 'paragraph', children: queue}) queue = undefined } result.push(node) } } if (queue !== undefined) { result.push({type: 'paragraph', children: queue}) } return result } /* Check if there are non-inline MDAST nodes returned. * This is needed if a fragment is given, which could just be * a sentence, and doesn’t need a wrapper paragraph. */ function needed(nodes) { var length = nodes.length var index = -1 while (++index < length) { if (!phrasing(nodes[index])) { return true } } return false }
Bump up version number for PyPI release
from setuptools import setup, find_packages author = 'Michael Maurizi' author_email = 'info@azavea.com' setup( name='django-tinsel', version='0.1.1', description='A python module for decorating function-based Django views', long_description=open('README.rst').read(), author=author, author_email=author_email, maintainer=author, maintainer_email=author_email, url='http://github.com/azavea/django-tinsel', packages=find_packages(exclude=('test_app',)), license='Apache License (2.0)', keywords="django view decorator", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Environment :: Plugins", "Framework :: Django", "License :: OSI Approved :: Apache Software License" ], install_requires=['django>=1.5'], )
from setuptools import setup, find_packages author = 'Michael Maurizi' author_email = 'info@azavea.com' setup( name='django-tinsel', version='0.1.0', description='A python module for decorating function-based Django views', long_description=open('README.rst').read(), author=author, author_email=author_email, maintainer=author, maintainer_email=author_email, url='http://github.com/azavea/django-tinsel', packages=find_packages(exclude=('test_app',)), license='Apache License (2.0)', keywords="django view decorator", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Programming Language :: Python", "Environment :: Plugins", "Framework :: Django", "License :: OSI Approved :: Apache Software License" ], install_requires=['django>=1.5'], )
Make stable builders pull from the 1.9 branch TBR=kasperl@google.com BUG= Review URL: https://codereview.chromium.org/1029093006 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@294541 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.9', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 4), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.8', 2, '-stable', 1), Channel('integration', 'branches/dartium_integration', 3, '-integration', 3), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
[Order] Order 2: Login system by https
import json import requests """ Order 2: Login system by https This is the code which use curl to login system ``` curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{ "credentials": { "username": "admin", "password": "a10" } }' ``` """ class LoginSystemByHttps(object): login_url = 'http://192.168.105.88/axapi/v3/auth' def login(self): """ Note: the dict playload must be use json.dumps() to turn to str. :return: Result string data """ payload = {'credentials': {'username': "admin", 'password': "a10"}} headers = {'content-type': 'application/json', 'Connection': 'keep-alive'} response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers) print(response.text) return response.text # login = LoginSystemByHttps() # login.login()
import json import requests """ Order 2: Login system by https ``` curl -k https://192.168.105.88/axapi/v3/auth -H "Content-type:application/json" -d '{ "credentials": { "username": "admin", "password": "a10" } }' ``` """ class LoginSystemByHttps(object): login_url = 'http://192.168.105.88/axapi/v3/auth' def login(self): """ Note: the dict playload must be use json.dumps() to turn to str. :return: Result string data """ payload = {'credentials': {'username': "admin", 'password': "a10"}} headers = {'content-type': 'application/json', 'Connection': 'keep-alive'} response = requests.post(self.login_url, data=json.dumps(payload), verify=False, headers=headers) print(response.text) return response.text # login = LoginSystemByHttps() # login.login()
Allow to use `url` defined as env variable.
import os # shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url=None, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. If *url* is not defined it will try to use *DATABASE_URL* from environment variable. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ url = os.environ.get('DATABASE_URL', url) return Database(url, reflectMetadata)
# shut up useless SA warning: import warnings warnings.filterwarnings( 'ignore', 'Unicode type received non-unicode bind param value.') from dataset.persistence.database import Database from dataset.persistence.table import Table from dataset.freeze.app import freeze __all__ = ['Database', 'Table', 'freeze', 'connect'] def connect(url, reflectMetadata=True): """ Opens a new connection to a database. *url* can be any valid `SQLAlchemy engine URL`_. Returns an instance of :py:class:`Database <dataset.Database>`. Set *reflectMetadata* to False if you don't want the entire database schema to be pre-loaded. This significantly speeds up connecting to large databases with lots of tables. :: db = dataset.connect('sqlite:///factbook.db') .. _SQLAlchemy Engine URL: http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.create_engine """ return Database(url, reflectMetadata)
Fix Text From Erroring When No requestChange
let React = require("react") let { savedText, errorList, sizeClassNames, formGroupCx, label, } = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: cx(this.props.className, "form-control"), valueLink: { value: this.props.valueLink.value || "", requestChange: this.props.valueLink.requestChange, }, rows: this.props.rows, }) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, label(this.props), div({className: "controls"}, textarea(this._inputHtml()), ), savedText({ saved: this.props.saved && this.props.modified, }), errorList(this.props.errors), ), ) } }
let React = require("react") let { savedText, errorList, sizeClassNames, formGroupCx, label, } = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: cx(this.props.className, "form-control"), valueLink: { value: this.props.valueLink.value || "", }, rows: this.props.rows, }) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: formGroupCx(this.props)}, label(this.props), div({className: "controls"}, textarea(this._inputHtml()), ), savedText({ saved: this.props.saved && this.props.modified, }), errorList(this.props.errors), ), ) } }
[MOD] Add additional context infrmation for different styling of trackers fields in search content git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@36281 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2011 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$ class Search_Formatter_ValueFormatter_Trackerrender implements Search_Formatter_ValueFormatter_Interface { function render($name, $value, array $entry) { if (substr($name, 0, 14) !== 'tracker_field_') { return $value; } $tracker = Tracker_Definition::get($entry['tracker_id']); if (!is_object($tracker)) { return $value; } $field = $tracker->getField(substr($name, 14)); $field['value'] = $value; $item = array(); if ($entry['object_type'] == 'trackeritem') { $item['itemId'] = $entry['object_id']; } $trklib = TikiLib::lib('trk'); return '~np~' . $trklib->field_render_value(array( 'item' => $item, 'field' => $field, 'process' => 'y', 'search_render' => 'y', )) . '~/np~'; } }
<?php // (c) Copyright 2002-2011 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$ class Search_Formatter_ValueFormatter_Trackerrender implements Search_Formatter_ValueFormatter_Interface { function render($name, $value, array $entry) { if (substr($name, 0, 14) !== 'tracker_field_') { return $value; } $tracker = Tracker_Definition::get($entry['tracker_id']); if (!is_object($tracker)) { return $value; } $field = $tracker->getField(substr($name, 14)); $field['value'] = $value; $item = array(); if ($entry['object_type'] == 'trackeritem') { $item['itemId'] = $entry['object_id']; } $trklib = TikiLib::lib('trk'); return '~np~' . $trklib->field_render_value(array( 'item' => $item, 'field' => $field, 'process' => 'y', )) . '~/np~'; } }
Add util for generating named image file
import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from tempfile import NamedTemporaryFile from .models import Photo import pickle def _get_image_file(file_factory): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = file_factory() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def get_image_file(): return _get_image_file(StringIO) def get_named_image_file(): return _get_image_file(NamedTemporaryFile) def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from .models import Photo import pickle def get_image_file(): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = StringIO() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
Change TestCase for PHP 7
<?php Class Globals { public static $VIDEO_FILE = ""; public static $NOVIDEO_FILE = ""; public static $CONFIG = array(); } Globals::$VIDEO_FILE = dirname(__FILE__) . "/../assets/video1s.mp4"; Globals::$NOVIDEO_FILE = dirname(__FILE__) . "/../assets/novideo.mp4"; Globals::$CONFIG = json_decode($_SERVER['argv'][2], TRUE); require_once(dirname(__FILE__) . "/../../Ziggeo.php"); Class ServerApiTestCase extends PHPUnit\Framework\TestCase { protected $ziggeo = NULL; private function init() { if (!@$this->ziggeo) $this->ziggeo = new Ziggeo(Globals::$CONFIG["application_token"], Globals::$CONFIG["private_key"]); if (@Globals::$CONFIG["config"]) $this->ziggeo->config()->config = array_merge($this->ziggeo->config()->config, Globals::$CONFIG["config"]); foreach ($this->ziggeo->videos()->index(array("states" => "all")) as $video) $this->ziggeo->videos()->delete($video->token); } protected function setUp() { $this->init(); } protected function tearDown() { sleep(15); $this->init(); } }
<?php Class Globals { public static $VIDEO_FILE = ""; public static $NOVIDEO_FILE = ""; public static $CONFIG = array(); } Globals::$VIDEO_FILE = dirname(__FILE__) . "/../assets/video1s.mp4"; Globals::$NOVIDEO_FILE = dirname(__FILE__) . "/../assets/novideo.mp4"; Globals::$CONFIG = json_decode($_SERVER['argv'][2], TRUE); require_once(dirname(__FILE__) . "/../../Ziggeo.php"); Class ServerApiTestCase extends PHPUnit_Framework_TestCase { protected $ziggeo = NULL; private function init() { if (!@$this->ziggeo) $this->ziggeo = new Ziggeo(Globals::$CONFIG["application_token"], Globals::$CONFIG["private_key"]); if (@Globals::$CONFIG["config"]) $this->ziggeo->config()->config = array_merge($this->ziggeo->config()->config, Globals::$CONFIG["config"]); foreach ($this->ziggeo->videos()->index(array("states" => "all")) as $video) $this->ziggeo->videos()->delete($video->token); } protected function setUp() { $this->init(); } protected function tearDown() { sleep(15); $this->init(); } }
Use subdomain now it's setup
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/dashboard', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 // ENV.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.WEBSITE_API_URL = "http://int-dev.withregard.io:3001"; ENV.WEBSITE_DATASTORE_URL = "http://int-dev.withregard.io:3002"; } if (environment === 'production') { ENV.WEBSITE_API_URL = "https://website-api.withregard.io"; ENV.WEBSITE_DATASTORE_URL = "https://website-datastore.withregard.io"; } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { environment: environment, baseURL: '/dashboard', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 // ENV.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; ENV.WEBSITE_API_URL = "http://int-dev.withregard.io:3001"; ENV.WEBSITE_DATASTORE_URL = "http://int-dev.withregard.io:3002"; } if (environment === 'production') { ENV.WEBSITE_API_URL = "https://website-api.withregard.io"; ENV.WEBSITE_DATASTORE_URL = "https://regard-website-datastore.azurewebsite.net"; } return ENV; };
Use port 3001 for API server. Currently, the webpack-dev-server and the API server need to be run separately, like so: npm start (separate shell) node api-server.js The app is then served at localhost:3000 for development.
var express = require('express'); var MetaInspector = require('node-metainspector'); var app = express(); // TODO: Improve CSP // http://enable-cors.org/server_expressjs.html app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.get('/api/v1/urlmeta/:url', function(req, res) { var client = new MetaInspector(req.params.url, {}); client.on('fetch', function () { res.json({ url: client.url, title: client.title }); }); client.on('error', function (err) { res.statusCode = 404; res.json(err); }); client.fetch(); }); var server = app.listen(3001, function () { var host = server.address().address; var port = server.address().port; console.log('API server listening at http://%s:%s', host, port); });
var express = require('express'); var MetaInspector = require('node-metainspector'); var app = express(); // TODO: Improve CSP // http://enable-cors.org/server_expressjs.html app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); next(); }); app.get('/api/v1/urlmeta/:url', function(req, res) { var client = new MetaInspector(req.params.url, {}); client.on('fetch', function () { res.json({ url: client.url, title: client.title }); }); client.on('error', function (err) { res.statusCode = 404; res.json(err); }); client.fetch(); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('API server listening at http://%s:%s', host, port); });
Add a delay between process launches. It so happens that the client process was launched before the server causing deadlocks in some cases. Fixed that by adding a small delay. In reality, we may need to logic to vtkTestDriver to make it more featured and parse outputs from processes to handle this correctly. We can do that in next stage. Change-Id: Ief6989c50e816bc8b6b7f8a780fd31b578079f4c
r""" This is a script that can be used to run tests that require multiple executables to be run e.g. those client-server tests. Usage: python vtkTestDriver.py --process exe1 arg11 arg12 ... --process exe2 arg21 arg22 ... --process ... """ import sys import subprocess import time # Extract arguments for each process to execute. command_lists = [] prev = None for idx in range(1, len(sys.argv)): if sys.argv[idx] == "--process": if prev: command_lists.append(sys.argv[prev:idx]) prev = idx+1 if prev <= len(sys.argv): command_lists.append(sys.argv[prev:]) procs = [] for cmdlist in command_lists: print >> sys.stderr, "Executing '", " ".join(cmdlist), "'" proc = subprocess.Popen(cmdlist) procs.append(proc) # sleep to ensure that the process starts. time.sleep(0.1) # Now wait for each of the processes to terminate. # If ctest times out, it will kill this process and all subprocesses will be # terminated anyways, so we don't need to handle timeout specially. for proc in procs: proc.wait() for proc in procs: if proc.returncode != 0: print >> sys.stderr, "ERROR: A process exited with error. Test will fail." sys.exit(1) # error print "All's well!"
r""" This is a script that can be used to run tests that require multiple executables to be run e.g. those client-server tests. Usage: python vtkTestDriver.py --process exe1 arg11 arg12 ... --process exe2 arg21 arg22 ... --process ... """ import sys import subprocess # Extract arguments for each process to execute. command_lists = [] prev = None for idx in range(1, len(sys.argv)): if sys.argv[idx] == "--process": if prev: command_lists.append(sys.argv[prev:idx]) prev = idx+1 if prev <= len(sys.argv): command_lists.append(sys.argv[prev:]) procs = [] for cmdlist in command_lists: print "Executing '", " ".join(cmdlist), "'" proc = subprocess.Popen(cmdlist) procs.append(proc) # Now wait for each of the processes to terminate. # If ctest times out, it will kill this process and all subprocesses will be # terminated anyways, so we don't need to handle timeout specially. for proc in procs: proc.wait() for proc in procs: if proc.returncode != 0: print "ERROR: A process exited with error. Test will fail." sys.exit(1) # error print "All's well!"
Add reduce() and reload() to disabled builtins
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, long, raw_input, reduce, reload, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'long', 'raw_input', 'reduce', 'reload', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
""" This disables builtin functions (and one exception class) which are removed from Python 3.3. This module is designed to be used like this: from future import disable_obsolete_builtins We don't hack __builtin__, which is very fragile because it contaminates imported modules too. Instead, we just create new global functions with the same names as the obsolete builtins from Python 2 which raise exceptions when called. The following functions are disabled: apply, cmp, coerce, execfile, file, raw_input, long, unicode, xrange and this exception class: StandardError (Note that callable() is not among them; this was reintroduced into Python 3.2.) Also to do: - Fix round() - Fix input() - Fix int() """ from __future__ import division, absolute_import, print_function import inspect from . import six OBSOLETE_BUILTINS = ['apply', 'cmp', 'coerce', 'execfile', 'file', 'raw_input', 'long', 'unicode', 'xrange', 'StandardError'] def disabled_function(name): ''' Returns a function that cannot be called ''' def disabled(*args, **kwargs): raise NameError('obsolete Python 2 builtin {} is disabled'.format(name)) return disabled if not six.PY3: caller = inspect.currentframe().f_back for fname in OBSOLETE_BUILTINS: caller.f_globals.__setitem__(fname, disabled_function(fname))
Break how flake8 wants me to break
from base64 import standard_b64encode, standard_b64decode import nacl.bindings import nacl.utils from nacl.secret import SecretBox from pymacaroons.field_encryptors.base_field_encryptor import ( BaseFieldEncryptor ) from pymacaroons.utils import ( truncate_or_pad, convert_to_bytes, convert_to_string ) class SecretBoxEncryptor(BaseFieldEncryptor): def __init__(self, signifier=None, nonce=None): super(SecretBoxEncryptor, self).__init__( signifier=signifier or 'sbe::' ) self.nonce = nonce or nacl.utils.random( nacl.bindings.crypto_secretbox_NONCEBYTES ) def encrypt(self, signature, field_data): encrypt_key = truncate_or_pad(signature) box = SecretBox(key=encrypt_key) encrypted = box.encrypt(convert_to_bytes(field_data), nonce=self.nonce) return self._signifier + standard_b64encode(encrypted) def decrypt(self, signature, field_data): key = truncate_or_pad(signature) box = SecretBox(key=key) encoded = convert_to_bytes(field_data[len(self.signifier):]) decrypted = box.decrypt(standard_b64decode(encoded)) return convert_to_string(decrypted)
from base64 import standard_b64encode, standard_b64decode import nacl.bindings import nacl.utils from nacl.secret import SecretBox from pymacaroons.field_encryptors.base_field_encryptor import ( BaseFieldEncryptor ) from pymacaroons.utils import ( truncate_or_pad, convert_to_bytes, convert_to_string ) class SecretBoxEncryptor(BaseFieldEncryptor): def __init__(self, signifier=None, nonce=None): super(SecretBoxEncryptor, self).__init__( signifier=signifier or 'sbe::' ) self.nonce = (nonce or nacl.utils.random(nacl.bindings.crypto_secretbox_NONCEBYTES)) def encrypt(self, signature, field_data): encrypt_key = truncate_or_pad(signature) box = SecretBox(key=encrypt_key) encrypted = box.encrypt(convert_to_bytes(field_data), nonce=self.nonce) return self._signifier + standard_b64encode(encrypted) def decrypt(self, signature, field_data): key = truncate_or_pad(signature) box = SecretBox(key=key) encoded = convert_to_bytes(field_data[len(self.signifier):]) decrypted = box.decrypt(standard_b64decode(encoded)) return convert_to_string(decrypted)
Add call to open development tools. The Electron Quick Start made a call to open the development tools window. In my original implementation, I forgot this call. This change reverses that omission.
var app = require('app'); // Module controlling application life cyle. var BrowserWindow = require('browser-window'); // Creating native browser windows. // Report crashes to the server (local node process?). require('crash-reporter').start(); // Keep a global reference to the main window; otherwise, when JavaScript garbage collects the instance, // it will destroy the window referred to by the instance. :) (How difficult would that be to debug?) var mainWindow = null; // Quit when the user closes all windows. app.on('window-all-closed', function() { // On OS X, it is common for applications and their menu bar to remain active until the user explicitly // closes the application using Cmd-Q. if (process.platform != 'darwin') { app.quit(); } }) // When electron has finished initialization and is ready to create browser windows, we call the following: app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}); // Load the index page for the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Open the development tools. mainWindow.openDevTools(); // When main window closed mainWindow.on('closed', function() { // Deference the window object. If you app supports multiple windows, you would typically store them // in an array. In this situation, you would delete the corresponding element of the array. mainWindow = null; }) })
var app = require('app'); // Module controlling application life cyle. var BrowserWindow = require('browser-window'); // Creating native browser windows. // Report crashes to the server (local node process?). require('crash-reporter').start(); // Keep a global reference to the main window; otherwise, when JavaScript garbage collects the instance, // it will destroy the window referred to by the instance. :) (How difficult would that be to debug?) var mainWindow = null; // Quit when the user closes all windows. app.on('window-all-closed', function() { // On OS X, it is common for applications and their menu bar to remain active until the user explicitly // closes the application using Cmd-Q. if (process.platform != 'darwin') { app.quit(); } }) // When electron has finished initialization and is ready to create browser windows, we call the following: app.on('ready', function() { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}); // Load the index page for the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Open the development tools. (What is the result of this call?) // When main window closed mainWindow.on('closed', function() { // Deference the window object. If you app supports multiple windows, you would typically store them // in an array. In this situation, you would delete the corresponding element of the array. mainWindow = null; }) })
Add square feet to Location data model.
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') square_footage = models.IntegerField capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
from django.db import models class Event(models.Model): setup_start = models.DateField setup_end = model.DateField event_start = model.DateField event_end = model.DateField teardown_start = model.DateField teardown_end = model.DateField needed_resources = models.ManyToMany(Resource) status = models.CharField(length=255, blank=False) visibility = models.CharField(length=255, blank=False) event_organizer = models.ManyToMany(Organization) location = models.ForeignKey(Location) class Location(models.Model): personel = models.ForeignKey('User') capacity = models.IntegerField location_name = models.CharField(length=255, blank=False) availability = models.CharField(length=255, blank=False) class Organization(models.Model): name = models.CharField(length=255, blank=False) phone_number = models.CharField(length=11, blank=True) email = models.CharField(length=255) class Resource(models.Model): isFixed = models.BooleanField resourceType = models.CharField(length=255, blank=False) description = models.CharField(length=255, blank=True) location = models.ForeignKey(Location, null=True)
Change 404 route to index
CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: 'views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: 'views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: 'views/404.html' }); $routeProvider.otherwise({ redirectTo: '/' }); }); if(isCordova()) $('body').addClass('cordova');
CenterScout.config(function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/home', { controller: 'HomeController', templateUrl: 'views/home.html' }); $routeProvider.when('/class', { controller: 'ClassController', templateUrl: 'views/class.html' }); $routeProvider.when('/about', { controller: 'AboutController', templateUrl: 'views/about.html' }); $routeProvider.when('/404', { controller: 'ErrorController', templateUrl: 'views/404.html' }); $routeProvider.otherwise({ redirectTo: '/404' }); }); if(isCordova()) $('body').addClass('cordova');
Add new test case for JS files
import chai from 'chai'; const expect = chai.expect; import onlyJsFiles from '../../src/resources/onlyJsFiles.js'; describe('test onlyJsFiles', function() { it('should return only JS files', () => { const resources = [ 'https://example.com/jQuery.js', 'https://example.com/js/somejsfile.js', 'https://example.com/css/main.css', 'https://example.com/images/image.jpeg', 'https://example.com/js/subfolder/file.js', 'https://example.com/js/subfolder/file.js?v=1.0.0', 'https://example.com/js/subfolder/file.js?version=1.0.0', 'https://example.com/js/subfolder/file.js?whatever', 'https://example.com/js/subfolder/file.min.js?whatever', ]; const files = onlyJsFiles(resources); expect(files).to.deep.equal([ 'https://example.com/jQuery.js', 'https://example.com/js/somejsfile.js', 'https://example.com/js/subfolder/file.js', 'https://example.com/js/subfolder/file.js?v=1.0.0', 'https://example.com/js/subfolder/file.js?whatever', 'https://example.com/js/subfolder/file.min.js?whatever', ]); }); });
import chai from 'chai'; const expect = chai.expect; import onlyJsFiles from '../../src/resources/onlyJsFiles.js'; describe('test onlyJsFiles', function() { it('should return only JS files', () => { const resources = [ 'https://example.com/jQuery.js', 'https://example.com/js/somejsfile.js', 'https://example.com/css/main.css', 'https://example.com/images/image.jpeg', 'https://example.com/js/subfolder/file.js', 'https://example.com/js/subfolder/file.js?v=1.0.0', 'https://example.com/js/subfolder/file.js?whatever', 'https://example.com/js/subfolder/file.min.js?whatever', ]; const files = onlyJsFiles(resources); expect(files).to.deep.equal([ 'https://example.com/jQuery.js', 'https://example.com/js/somejsfile.js', 'https://example.com/js/subfolder/file.js', 'https://example.com/js/subfolder/file.js?v=1.0.0', 'https://example.com/js/subfolder/file.js?whatever', 'https://example.com/js/subfolder/file.min.js?whatever', ]); }); });
Remove extra support for 1000 classes as no longer needed
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) print('Predicted:', decode_predictions(preds))
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __name__ == '__main__': size = 224 alpha = 1.0 model = MobileNets(input_shape=(size, size, 3), alpha=alpha, weights='imagenet') model.summary() img_path = 'elephant.jpg' img = image.load_img(img_path, target_size=(size, size)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode predictions does not like the 1001th class (UNKNOWN class), # thats why we remove the last prediction and feed it to decode predictions preds = preds[:, 0:1000] print('Predicted:', decode_predictions(preds))
Fix random issue in Abecedarium
 define(["sugar-web/activity/activity","sugar-web/datastore"], function (activity, datastore) { if (!Abcd) { Abcd = {}; } Abcd.activity = activity; Abcd.datastore = datastore; app = null; // Manipulate the DOM only when it is ready. require(['domReady!'], function (doc) { // Initialize the activity Abcd.activity.setup(); // Create sound component Abcd.sound = new Abcd.Audio(); Abcd.sound.renderInto(document.getElementById("header")); // Create and display first screen app = new Abcd.App().renderInto(document.getElementById("body")); // Load context Abcd.loadContext(function() { app.restartLastGame(); }); // Stop sound at end of game to sanitize media environment, specifically on Android document.getElementById("stop-button").addEventListener('click', function (event) { Abcd.sound.pause(); }); }); });
 define(["sugar-web/activity/activity","sugar-web/datastore"], function (activity, datastore) { Abcd.activity = activity; Abcd.datastore = datastore; app = null; // Manipulate the DOM only when it is ready. require(['domReady!'], function (doc) { // Initialize the activity Abcd.activity.setup(); // Create sound component Abcd.sound = new Abcd.Audio(); Abcd.sound.renderInto(document.getElementById("header")); // Create and display first screen app = new Abcd.App().renderInto(document.getElementById("body")); // Load context Abcd.loadContext(function() { app.restartLastGame(); }); // Stop sound at end of game to sanitize media environment, specifically on Android document.getElementById("stop-button").addEventListener('click', function (event) { Abcd.sound.pause(); }); }); });
Delete a stray Python 2 print statement.
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
Update path for local development
// ==UserScript== // @author Robert Slifka (GitHub @rslifka) // @connect docs.google.com // @connect rslifka.github.io // @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools) // @description (DEVELOPMENT) Enhancements to the Destiny Item Manager // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_log // @grant GM_setValue // @grant GM_xmlhttpRequest // @homepage https://github.com/rslifka/fate_of_all_fools // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools // @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.js // @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/public/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
// ==UserScript== // @author Robert Slifka (GitHub @rslifka) // @connect docs.google.com // @connect rslifka.github.io // @copyright 2017-2018, Robert Slifka (https://github.com/rslifka/fate_of_all_fools) // @description (DEVELOPMENT) Enhancements to the Destiny Item Manager // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_log // @grant GM_setValue // @grant GM_xmlhttpRequest // @homepage https://github.com/rslifka/fate_of_all_fools // @license MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt // @match https://*.destinyitemmanager.com/* // @name (DEVELOPMENT) Fate of All Fools // @require file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.js // @resource fateOfAllFoolsCSS file:///Users/rslifka/Dropbox/workspace/fate_of_all_fools/build/fateOfAllFools.css // @run-at document-idle // @supportURL https://github.com/rslifka/fate_of_all_fools/issues // ==/UserScript==
Remove the auth contenttypes thing for now, needs improvement
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a particular migration in a direction ran_migration = Signal(providing_args=["app","migration","method"]) # Compatibility code for django.contrib.auth # Is causing strange errors, removing for now (we might need to fix up orm first) #if 'django.contrib.auth' in settings.INSTALLED_APPS: #def create_permissions_compat(app, **kwargs): #from django.db.models import get_app #from django.contrib.auth.management import create_permissions #create_permissions(get_app(app), (), 0) #post_migrate.connect(create_permissions_compat)
""" South-specific signals """ from django.dispatch import Signal from django.conf import settings # Sent at the start of the migration of an app pre_migrate = Signal(providing_args=["app"]) # Sent after each successful migration of an app post_migrate = Signal(providing_args=["app"]) # Sent after each run of a particular migration in a direction ran_migration = Signal(providing_args=["app","migration","method"]) # Compatibility code for django.contrib.auth if 'django.contrib.auth' in settings.INSTALLED_APPS: def create_permissions_compat(app, **kwargs): from django.db.models import get_app from django.contrib.auth.management import create_permissions create_permissions(get_app(app), (), 0) post_migrate.connect(create_permissions_compat)
Clean up File edit view
from __future__ import unicode_literals from flask import url_for from flask_mongoengine.wtf import model_form from mongoengine import * from core.observables import Observable from core.database import StringListField class File(Observable): value = StringField(verbose_name="Value") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] exclude_fields = Observable.exclude_fields + ['hashes', 'body'] @classmethod def get_form(klass): form = model_form(klass, exclude=klass.exclude_fields) form.filenames = StringListField("Filenames") return form @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
from __future__ import unicode_literals from mongoengine import * from core.observables import Observable from core.observables import Hash class File(Observable): value = StringField(verbose_name="SHA256 hash") mime_type = StringField(verbose_name="MIME type") hashes = DictField(verbose_name="Hashes") body = ReferenceField("AttachedFile") filenames = ListField(StringField(), verbose_name="Filenames") DISPLAY_FIELDS = Observable.DISPLAY_FIELDS + [("mime_type", "MIME Type")] @staticmethod def check_type(txt): return True def info(self): i = Observable.info(self) i['mime_type'] = self.mime_type i['hashes'] = self.hashes return i
Add body classes in div
<!DOCTYPE html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 7]><html class="no-js lt-ie9 lt-ie8 ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]><html class="no-js lt-ie9 ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 9]><html class="no-js lt-ie9 ie9" <?php language_attributes(); ?>> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js" <?php language_attributes() ?>> <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Developed by Hoppinger BV 2014 - 2015 http://www.hoppinger.com --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="body-classes" <?php body_class(); ?>></div> <?php wp_footer(); ?> </html>
<!DOCTYPE html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 7]><html class="no-js lt-ie9 lt-ie8 ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]><html class="no-js lt-ie9 ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 9]><html class="no-js lt-ie9 ie9" <?php language_attributes(); ?>> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js" <?php language_attributes() ?>> <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Developed by Hoppinger BV 2014 - 2015 http://www.hoppinger.com --> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> </body> <?php wp_footer(); ?> </html>
Change requirements to reflect reality * Add `bootstrap` so the scripts get loaded * Remove `module` and `appearanceManager` because they aren't used any more * Stop providing variables in function with modules that are only loaded for side effects
define(['jquery', 'underscore', 'pullManager', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager', 'bootstrap'], // Note that not all of the required items above are represented in the function argument list. Some just need to be loaded, but that's all. function($, _, pullManager, PullFilter, ElementFilter, Column) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); globalPullFilter.update(pullManager.getPulls()); });
define(['jquery', 'underscore', 'pullManager', 'appearanceManager', 'module', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager'], function($, _, pullManager, appearanceManager, module, PullFilter, ElementFilter, Column, ConnectionManager) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); //$(appearanceManager.addCollapseSwaps); globalPullFilter.update(pullManager.getPulls()); });
Correct the HTTP status from GET / - it should be 300 (Multiple Choices) not 200. Implement the details of a given version.
from webob import Response import webob.exc from apiversion import APIVersion from application import Application from apiv1app import APIv1App class VersionsApp(Application): version_classes = [ APIv1App ] def _api_version_detail(self, version): return { "id": version._version_identifier(), "links": [ { "href": "/" + version._version_identifier(), "rel": "self" } ] } def APIVersionList(self, args): return Response(status = 300, content_type = 'application/json', body = self._resultset_to_json([ self._api_version_detail(version) for version in self.version_classes ])) def APIVersion(self, version_identifier): versions = [ version for version in self.version_classes if version._version_identifier() == version_identifier ] if not versions: return webob.exc.HTTPNotFound() if len(versions) > 1: raise RuntimeError("Multiple API versions with identifier '%s'" % version_identifier) return Response(content_type = 'application/json', body = self._resultset_to_json({ self._api_version_detail(versions[0]) })) def factory(global_config, **settings): return VersionsApp()
from webob import Response from apiversion import APIVersion from application import Application from apiv1app import APIv1App class VersionsApp(Application): version_classes = [ APIv1App ] def APIVersionList(self, args): return Response(content_type = 'application/json', body = self._resultset_to_json([ { "id": version._version_identifier(), "links": [ { "href": "/" + version._version_identifier(), "rel": "self" } ] } for version in self.version_classes ])) def APIVersion(self, args): return Response(content_type = 'application/json', body = self._resultset_to_json({ 'todo': 'Report detail' })) def factory(global_config, **settings): return VersionsApp()
Correct remote path for error page
var path = require('path'); var fs = require('fs'); var isUrl = require('is-url'); var notFound = function (settings, store) { return function (req, res, next) { res.statusCode = 404; res.send(getErrorPage(req.config, settings), true); }; function getErrorPage (config, settings) { return (pathExists(config, settings)) ? pathWithRoot(config, settings) : path.resolve(__dirname, '../templates/not_found.html'); } function pathExists (config, settings) { if (!config || !config.error_page) return false; if (isUrl(config.error_page)) return true; // NOTE: If this becomes a bottleneck, convert // to async version of fs.exists() return settings.isFile(config.error_page); } function pathWithRoot (config, settings) { if (isUrl(config.error_page)) return config.error_page; // return settings.rootPathname(config.error_page); console.log('path with root', store.getPath(path.join('/', req.config.cwd, config.error_page))); return store.getPath(path.join('/', req.config.cwd, config.error_page)); } }; module.exports = notFound;
var path = require('path'); var fs = require('fs'); var isUrl = require('is-url'); var notFound = function (settings, store) { return function (req, res, next) { res.statusCode = 404; res.send(getErrorPage(req.config, settings), true); }; function getErrorPage (config, settings) { return (pathExists(config, settings)) ? pathWithRoot(config, settings) : path.resolve(__dirname, '../templates/not_found.html'); } function pathExists (config, settings) { if (!config || !config.error_page) return false; if (isUrl(config.error_page)) return true; // NOTE: If this becomes a bottleneck, convert // to async version of fs.exists() return settings.isFile(config.error_page); } function pathWithRoot (config, settings) { if (isUrl(config.error_page)) return config.error_page; // return settings.rootPathname(config.error_page); console.log('path with root', store.getPath(config.error_page)); return store.getPath(config.error_page); } }; module.exports = notFound;
Fix crash when passport is not on the session
/** * This is the entrypoint for our application on the server. * When the server is started, this code will run. */ // Use Babel to provide support for JSX require('babel-core/register'); const http = require('http'); const ws = require('ws'); const createApp = require('./createApp').default; const WebSocketServer = require('./webSocketServer').default; const sessionParser = require('./config/sessionParser').default; createApp().then((app) => { const server = http.createServer(app); server.listen(3000, () => { console.log('Server started.'); global.wss = new WebSocketServer(new ws.Server({ verifyClient: (info, done) => { sessionParser(info.req, {}, () => { if(!info.req.session.passport) { done(null); return; } done(info.req.session.passport.user); }); }, server })); }); });
/** * This is the entrypoint for our application on the server. * When the server is started, this code will run. */ // Use Babel to provide support for JSX require('babel-core/register'); const http = require('http'); const ws = require('ws'); const createApp = require('./createApp').default; const WebSocketServer = require('./webSocketServer').default; const sessionParser = require('./config/sessionParser').default; createApp().then((app) => { const server = http.createServer(app); server.listen(3000, () => { console.log('Server started.'); global.wss = new WebSocketServer(new ws.Server({ verifyClient: (info, done) => { sessionParser(info.req, {}, () => { done(info.req.session.passport.user); }); }, server })); }); });
Fix back link on filter-common
module.exports = { '/':{ controller: require('../../../controllers/application-country'), fields: ['apply-uk', 'application-country'], controller: require('../../../controllers/go-overseas'), backLink: '/../priority_service_170315/get-urgent-passport/premium-online', next: '/what-do-you-want-to-do', /* if Yes is selected */ nextAlt: '../not-eligible', /* if they are from Germany/France */ nextAltAlt:'what-do-you-want-to-do-overseas' }, '/what-do-you-want-to-do': { fields: ['what-to-do'], backLink: './', next: '/dob' }, '/dob': { fields: ['age-day', 'age-year', 'age-month'], controller: require('../../../controllers/go-overseas'), backLink: './what-do-you-want-to-do', next: '/../filter', /* if they are from the UK */ nextAlt: '../overseas', /* if they are from Germany/France */ nextAltAlt:'../overseas-not-eligible' /* if they are from Afganistan */ } };
module.exports = { '/':{ controller: require('../../../controllers/application-country'), fields: ['apply-uk', 'application-country'], controller: require('../../../controllers/go-overseas'), backLink: '/../priority_service_170215/get-urgent-passport/premium-online', next: '/what-do-you-want-to-do', /* if Yes is selected */ nextAlt: '../not-eligible', /* if they are from Germany/France */ nextAltAlt:'what-do-you-want-to-do-overseas' }, '/what-do-you-want-to-do': { fields: ['what-to-do'], backLink: './', next: '/dob' }, '/dob': { fields: ['age-day', 'age-year', 'age-month'], controller: require('../../../controllers/go-overseas'), backLink: './what-do-you-want-to-do', next: '/../filter', /* if they are from the UK */ nextAlt: '../overseas', /* if they are from Germany/France */ nextAltAlt:'../overseas-not-eligible' /* if they are from Afganistan */ } };
Add a method to test whether an attribute exists
# -*- coding: utf-8 -*- import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def identifier(self): """Return a unique identifier for the service""" # TODO: How do we uniquely identify a service? service_title = self.service_title() dept = self.abbreviated_department() return sanitise_string(u'{0} {1} {2}'.format(self.numeric_id, dept, service_title)) def attribute_exists(self, key): return key in self.detailed_data def get(self, key): return self.detailed_data[key] def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr')
import string def sanitise_string(messy_str): """Whitelist characters in a string""" valid_chars = ' {0}{1}'.format(string.ascii_letters, string.digits) return u''.join(char for char in messy_str if char in valid_chars).strip() class Service(object): def __init__(self, numeric_id, detailed_data): self.numeric_id = numeric_id self.detailed_data = detailed_data def identifier(self): """Return a unique identifier for the service""" # TODO: How do we uniquely identify a service? service_title = self.service_title() dept = self.abbreviated_department() return sanitise_string(u'{0} {1} {2}'.format(self.numeric_id, dept, service_title)) def get(self, key): return self.detailed_data[key] def service_title(self): return self.get('Name of service') def abbreviated_department(self): return self.get('Abbr')
Add entry point for monitor runner
from setuptools import setup, find_packages setup( name='cosmo', version='1.0.1', description='Monitors for HST/COS', keywords=['astronomy'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: BSD-3 :: Association of Universities for Research in Astronomy', 'Operating System :: Linux' ], python_requires='~=3.7', # 3.7 and higher, but not 4 packages=find_packages(), install_requires=[ 'setuptools', 'numpy>=1.11.1', 'astropy>=1.0.1', 'plotly>=4.0.0', 'dask', 'pandas>=0.25.0', 'pytest', 'pyyaml', 'peewee', 'monitorframe @ git+https://github.com/spacetelescope/monitor-framework#egg=monitorframe' ], package_data={'cosmo': ['pytest.ini']}, entry_points={ 'console_scripts': ['cosmo=cosmo.run_monitors:runner'] } )
from setuptools import setup, find_packages setup( name='cosmo', version='1.0.0', description='Monitors for HST/COS', keywords=['astronomy'], classifiers=[ 'Programming Language :: Python :: 3', 'License :: BSD-3 :: Association of Universities for Research in Astronomy', 'Operating System :: Linux' ], python_requires='~=3.7', # 3.7 and higher, but not 4 packages=find_packages(), install_requires=[ 'setuptools', 'numpy>=1.11.1', 'astropy>=1.0.1', 'plotly>=4.0.0', 'dask', 'pandas', 'pytest', 'pyyaml', 'peewee', 'monitorframe @ git+https://github.com/spacetelescope/monitor-framework#egg=monitorframe' ], package_data={'cosmo': ['pytest.ini']} )
Fix wrong indent: replace tabs with whitespace.
/*- * #%L * Secured Properties * =============================================================== * Copyright (C) 2016 - 2019 Brabenetz Harald, Austria * =============================================================== * 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. * #L% */ package net.brabenetz.lib.securedproperties.snippets; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //START SNIPPET: configExample @SpringBootApplication public class SpringBootStarterApplication { public static void main(String[] args) { securePasswords(); SpringApplication.run(SpringBootStarterApplication.class, args); } private static void securePasswords() { // this will encrypt the given properties if there are not already encrypted: SpringBootSecuredPropertiesHelper.encryptProperties( "your.app.props.my-secret-password", "your.app.props.another-secret-password"); } } //END SNIPPET: configExample
/*- * #%L * Secured Properties * =============================================================== * Copyright (C) 2016 - 2019 Brabenetz Harald, Austria * =============================================================== * 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. * #L% */ package net.brabenetz.lib.securedproperties.snippets; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //START SNIPPET: configExample @SpringBootApplication public class SpringBootStarterApplication { public static void main(String[] args) { securePasswords(); SpringApplication.run(SpringBootStarterApplication.class, args); } private static void securePasswords() { // this will encrypt the given properties if there are not already encrypted: SpringBootSecuredPropertiesHelper.encryptProperties( "your.app.props.my-secret-password", "your.app.props.another-secret-password"); } } //END SNIPPET: configExample
Refactor magnet URI link catch logic
module.exports = function (root, cb) { root.addEventListener('click', (ev) => { if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) { return true } var anchor = null for (var n = ev.target; n.parentNode; n = n.parentNode) { if (n.nodeName === 'A') { anchor = n break } } if (!anchor) return true var href = anchor.getAttribute('href') if (href) { var isUrl try { var url = new URL(href) isUrl = true } catch (e) { isUrl = false } if (isUrl && (url.host || url.protocol === 'magnet:')) { cb(href, true) } else if (href !== '#') { cb(href, false, anchor.anchor) } } ev.preventDefault() ev.stopPropagation() }) }
module.exports = function (root, cb) { root.addEventListener('click', (ev) => { if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) { return true } var anchor = null for (var n = ev.target; n.parentNode; n = n.parentNode) { if (n.nodeName === 'A') { anchor = n break } } if (!anchor) return true var href = anchor.getAttribute('href') if (href) { var isUrl try { var url = new URL(href) isUrl = true } catch (e) { isUrl = false } if (isUrl && url.host || isUrl && url.protocol === 'magnet:') { cb(href, true) } else if (href !== '#') { cb(href, false, anchor.anchor) } } ev.preventDefault() ev.stopPropagation() }) }
Change to using PathPrefix for general routes
package main import ( "github.com/NYTimes/gziphandler" "github.com/discoviking/website/server/storage" "github.com/gorilla/mux" "net/http" ) func createRouter(storageService storage.Service) *mux.Router { // Main Router. r := mux.NewRouter() storageHandler := storage.NewHandler(storageService) r.Handle("/storage/{key}", http.StripPrefix("/storage", storageHandler)) appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../app/build/src/app.js") }) r.Handle("/app.js", gziphandler.GzipHandler(appHandler)) // Serve static assets. fs := http.FileServer(http.Dir("../app/build/src/assets/")) r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", fs)) // For all other paths just serve the app and defer to the front-end to handle it. r.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../app/build/src/index.html") }) return r }
package main import ( "github.com/NYTimes/gziphandler" "github.com/discoviking/website/server/storage" "github.com/gorilla/mux" "net/http" ) func createRouter(storageService storage.Service) *mux.Router { // Main Router. r := mux.NewRouter() fs := http.FileServer(http.Dir("../app/build/src/assets/")) r.Handle("/assets/{assetPath:.*}", http.StripPrefix("/assets/", fs)) storageHandler := storage.NewHandler(storageService) r.Handle("/storage/{key}", http.StripPrefix("/storage", storageHandler)) appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../app/build/src/app.js") }) r.Handle("/app.js", gziphandler.GzipHandler(appHandler)) // For all other paths just serve the app and defer to the front-end to handle it. r.HandleFunc("/{path:.*}", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "../app/build/src/index.html") }) return r }
Update netmask test to something that GeoIP and GeoLite (hopefully) agrees on
package geoip import ( "fmt" . "launchpad.net/gocheck" "testing" ) // Hook up gocheck into the gotest runner. func Test(t *testing.T) { TestingT(t) } type GeoIPSuite struct { } var _ = Suite(&GeoIPSuite{}) func (s *GeoIPSuite) Testv4(c *C) { gi, err := Open() if gi == nil || err != nil { fmt.Printf("Could not open GeoIP database: %s\n", err) } c.Check(gi, NotNil) country, netmask := gi.GetCountry("207.171.7.51") c.Check(country, Equals, "US") c.Check(netmask, Equals, 15) country, netmask = gi.GetCountry("149.20.64.42") c.Check(country, Equals, "US") c.Check(netmask, Equals, 13) }
package geoip import ( "fmt" . "launchpad.net/gocheck" "testing" ) // Hook up gocheck into the gotest runner. func Test(t *testing.T) { TestingT(t) } type GeoIPSuite struct { } var _ = Suite(&GeoIPSuite{}) func (s *GeoIPSuite) Testv4(c *C) { gi, err := Open() if gi == nil || err != nil { fmt.Printf("Could not open GeoIP database: %s\n", err) } c.Check(gi, NotNil) country, netmask := gi.GetCountry("207.171.7.51") c.Check(country, Equals, "US") c.Check(netmask, Equals, 15) country, netmask = gi.GetCountry("64.235.248.1") c.Check(country, Equals, "US") c.Check(netmask, Equals, 20) }
Use modern super() python class function
import logging logger = logging.getLogger(__name__) from django.views.generic import TemplateView from voting.models import Bill from voting.models import Member class HomeView(TemplateView): template_name = "website/index.html" context_object_name = "homepage" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class BillsView(TemplateView): template_name = "website/bills.html" context_object_name = "bills" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) bills = Bill.objects.all() for bill in bills: bill.votes = bill.get_votes() context['bills'] = bills return context class MembersView(TemplateView): template_name = "website/members.html" context_object_name = "members" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) members = Member.objects.all() context['members'] = members return context
import logging logger = logging.getLogger(__name__) from django.views.generic import TemplateView from voting.models import Bill from voting.models import Member class HomeView(TemplateView): template_name = "website/index.html" context_object_name = "homepage" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) return context class BillsView(TemplateView): template_name = "website/bills.html" context_object_name = "bills" def get_context_data(self, **kwargs): context = super(BillsView, self).get_context_data(**kwargs) bills = Bill.objects.all() for bill in bills: bill.votes = bill.get_votes() context['bills'] = bills return context class MembersView(TemplateView): template_name = "website/members.html" context_object_name = "members" def get_context_data(self, **kwargs): context = super(MembersView, self).get_context_data(**kwargs) members = Member.objects.all() context['members'] = members return context
Load detected react-intl locale data
import path from "path" import {readdir} from "fs" import {addLocaleData} from "react-intl" const DEFAULT_LANGUAGE = 'fr' export function loadTranslations(langDir) { var messages = {} readdir(langDir, (err, files) => { if(err) { console.log("Unable to load translation files.", err) } var possibleLocale files.forEach(file => { possibleLocale = path.basename(file, '.json') addLocaleData(require(`react-intl/locale-data/${possibleLocale}`)) messages[possibleLocale] = require(path.resolve(langDir, file)) }) }) return messages } export function getLocale(acceptLanguage, messages){ var locale = acceptLanguage ? acceptLanguage.substring(0, 2) : DEFAULT_LANGUAGE //ex: en-US;q=0.4,fr-FR;q=0.2 > en if(! messages[locale]) { locale = DEFAULT_LANGUAGE } return locale } export function getLocaleMessages(locale, messages){ return messages[locale] }
import path from "path" import {readdir} from "fs" import {addLocaleData} from "react-intl" import fr from "react-intl/locale-data/fr" import en from "react-intl/locale-data/en" const DEFAULT_LANGUAGE = 'fr' export function loadTranslations(langDir) { addLocaleData(...fr) addLocaleData(...en) var messages = {} readdir(langDir, (err, files) => { if(err) { console.log("Unable to load translation files.", err) } files.forEach(file => { messages[path.basename(file, '.json')] = require(path.resolve(langDir, file)) }) }) return messages } export function getLocale(acceptLanguage, messages){ var locale = acceptLanguage ? acceptLanguage.substring(0, 2) : DEFAULT_LANGUAGE //ex: en-US;q=0.4,fr-FR;q=0.2 > en if(! messages[locale]) { locale = DEFAULT_LANGUAGE } return locale } export function getLocaleMessages(locale, messages){ return messages[locale] }
Check in improved bower generation script
#!/usr/bin/env node // Renders the bower.json template and prints it to stdout var packageJson = require("../../package.json"); var template = { name: packageJson.name, version: packageJson.version, main: ["dist/" + packageJson.name + ".core.js", "dist/" + packageJson.name + ".core.min.js"], ignore: [ ".*", "README.md", "CHANGELOG.md", "Makefile", "browser.js", "dist/" + packageJson.name + ".js", "dist/" + packageJson.name + ".min.js", "index.js", "karma*", "lib/**", "package.json", "src/**", "test/**" ], dependencies: packageJson.dependencies }; console.log(JSON.stringify(template, null, 2));
#!/usr/bin/env node // Renders the bower.json template and prints it to stdout var template = { name: "graphlib", version: require("../../package.json").version, main: [ "dist/graphlib.core.js", "dist/graphlib.core.min.js" ], ignore: [ ".*", "README.md", "CHANGELOG.md", "Makefile", "browser.js", "dist/graphlib.js", "dist/graphlib.min.js", "index.js", "karma*", "lib/**", "package.json", "src/**", "test/**" ], dependencies: { "lodash": "^2.4.1" } }; console.log(JSON.stringify(template, null, 2));
Test Hash comparisons using assertThat which makes failure messages and assertion code more readable, and avoids http://errorprone.info/bugpattern/SelfEquals.
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.vcs.log.impl; import com.intellij.vcs.log.Hash; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author erokhins */ public class HashEqualsTest { @Test public void testEqualsSelf() { Hash hash = HashImpl.build("adf"); assertThat(hash).isEqualTo(hash); } @Test public void testEqualsNull() { Hash hash = HashImpl.build("adf"); assertThat(hash).isNotNull(); } @Test public void testEquals() { Hash hash1 = HashImpl.build("adf"); Hash hash2 = HashImpl.build("adf"); assertThat(hash1).isEqualTo(hash2); } @Test public void testEqualsNone() { Hash hash1 = HashImpl.build(""); Hash hash2 = HashImpl.build(""); assertThat(hash1).isEqualTo(hash2); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.vcs.log.impl; import com.intellij.vcs.log.Hash; import org.junit.Test; import static org.junit.Assert.*; /** * @author erokhins */ public class HashEqualsTest { @Test public void testEqualsSelf() { Hash hash = HashImpl.build("adf"); //noinspection EqualsWithItself assertTrue(hash.equals(hash)); } @Test public void testEqualsNull() { Hash hash = HashImpl.build("adf"); assertFalse(hash.equals(null)); } @Test public void testEquals() { Hash hash1 = HashImpl.build("adf"); Hash hash2 = HashImpl.build("adf"); assertTrue(hash1.equals(hash2)); } @Test public void testEqualsNone() { Hash hash1 = HashImpl.build(""); Hash hash2 = HashImpl.build(""); assertTrue(hash1.equals(hash2)); } }
Simplify output bundles by making .cjs an UMD bundle
import {join} from 'path' import {terser} from 'rollup-plugin-terser' import size from 'rollup-plugin-size' const options = {mangle: true, compress: false, toplevel: true} const defaults = { onwarn(warning, warn) { switch (warning.code) { case 'CIRCULAR_DEPENDENCY': return default: warn(warning) } }, treeshake: {propertyReadSideEffects: false}, context: 'this' } export default ({configSrc = './', configInput = join(configSrc, 'index.js')}) => { return [ { ...defaults, input: configInput, output: [{file: join(configSrc, 'dist', 'stylis.cjs'), format: 'umd', name: 'stylis', freeze: false, sourcemap: true}], plugins: [terser(options), size()] }, { ...defaults, input: configInput, output: [{file: join(configSrc, 'dist', 'stylis.esm.js'), format: 'esm', name: 'stylis', freeze: false, sourcemap: true}], plugins: [terser(options), size()] } ] }
import {join} from 'path' import {terser} from 'rollup-plugin-terser' import size from 'rollup-plugin-size' const options = {mangle: true, compress: false, toplevel: true} const defaults = { onwarn(warning, warn) { switch (warning.code) { case 'CIRCULAR_DEPENDENCY': return default: warn(warning) } }, treeshake: {propertyReadSideEffects: false}, context: 'this' } export default ({configSrc = './', configInput = join(configSrc, 'index.js')}) => { return [ { ...defaults, input: configInput, output: [{file: join(configSrc, 'dist', 'stylis.cjs'), format: 'cjs', name: 'stylis', freeze: false, sourcemap: true}], plugins: [terser(options), size()] }, { ...defaults, input: configInput, output: [{file: join(configSrc, 'dist', 'stylis.umd.js'), format: 'umd', name: 'stylis', freeze: false, sourcemap: true}], plugins: [terser(options), size()] }, { ...defaults, input: configInput, output: [{file: join(configSrc, 'dist', 'stylis.esm.js'), format: 'esm', name: 'stylis', freeze: false, sourcemap: true}], plugins: [terser(options), size()] } ] }
Add $inject -- to prevent minifiers
(function() { var CustomersController = function($scope) { $scope.sortBy = 'name'; $scope.reverse = false; $scope.customers = [{name:'John', city:'London', joined:'2014-12-02', orderTotal:212.5}, {name:'Paul', city:'Liverpool', joined:'2014-11-02', orderTotal:312.1}, {name:'George', city:'Glasgow', joined:'2014-10-02', orderTotal:435.99}, {name:'Leo', city:'Albuquerque', joined:'2014-01-02', orderTotal:415.99}, {name:'Ringo', city:'Manchester', joined:'2014-11-12', orderTotal:111}]; $scope.doSort = function (propName) { $scope.sortBy = propName; $scope.reverse = !$scope.reverse }; }; CustomersController.$inject = ['$scope']; angular.module('myApp').controller('CustomersController', CustomersController); }());
(function() { var CustomersController = function($scope) { $scope.sortBy = 'name'; $scope.reverse = false; $scope.customers = [{name:'John', city:'London', joined:'2014-12-02', orderTotal:212.5}, {name:'Paul', city:'Liverpool', joined:'2014-11-02', orderTotal:312.1}, {name:'George', city:'Glasgow', joined:'2014-10-02', orderTotal:435.99}, {name:'Leo', city:'Albuquerque', joined:'2014-01-02', orderTotal:415.99}, {name:'Ringo', city:'Manchester', joined:'2014-11-12', orderTotal:111}]; $scope.doSort = function (propName) { $scope.sortBy = propName; $scope.reverse = !$scope.reverse }; }; angular.module('myApp').controller('CustomersController', CustomersController); }());
Create Account works with elastic search
package com.example.whatsmymood; import java.util.ArrayList; import java.util.concurrent.ExecutionException; /** * Created by Malcolm on 2017-03-11. */ public class CreateUserController { public CreateUserController(){ } public boolean create(String username, String password) { // Check that user name is unique in elastic search index ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); getUserTask.execute(username); try { ArrayList<UserAccount> userList = getUserTask.get(); if (!userList.isEmpty()) { return false; } else { UserAccount user = new UserAccount(username, password); ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(user); return true; } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; } }
package com.example.whatsmymood; import java.util.ArrayList; import java.util.concurrent.ExecutionException; /** * Created by Malcolm on 2017-03-11. */ public class CreateUserController { public CreateUserController(){ } public boolean create(String username, String password) { // Check that user name is unique in elastic search index ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); getUserTask.execute(username); try { ArrayList<UserAccount> userList = getUserTask.get(); if (!userList.isEmpty()) { return false; } else { UserAccount user = new UserAccount(username, password); ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask(); addUserTask.execute(user); return true; } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } }
Apply total length of RFC-2821
'use strict'; var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/; // Thanks to: // http://fightingforalostcause.net/misc/2006/compare-email-regex.php // http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx // http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378 exports.validate = function (email) { if (!email) return false; if (email.length > 256) return false; if (!tester.test(email)) return false; // Further checking of some things regex can't handle var [account, address] = email.split('@'); if (account.length > 64) return false; var domainParts = address.split('.'); if (domainParts.some(function (part) { return part.length > 63; })) return false; return true; };
"use strict"; var tester = /^[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/; // Thanks to: // http://fightingforalostcause.net/misc/2006/compare-email-regex.php // http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx // http://stackoverflow.com/questions/201323/what-is-the-best-regular-expression-for-validating-email-addresses/201378#201378 exports.validate = function(email) { if (!email) return false; if(email.length>254) return false; var valid = tester.test(email); if(!valid) return false; // Further checking of some things regex can't handle var parts = email.split("@"); if(parts[0].length>64) return false; var domainParts = parts[1].split("."); if(domainParts.some(function(part) { return part.length>63; })) return false; return true; }
Add dir watch with file created/removed events
import dir from 'node-dir'; import watch from 'watch'; import path from 'path'; import commandLineArgs from 'command-line-args'; const cli = commandLineArgs([ { name: 'dir', alias: 'd', type: String } ]); const options = cli.parse(); function processFile(file) { console.log('file:', file); const [artist, album, songFile] = path.relative(options.dir, file).split(path.sep); console.log('artist:', artist); console.log('album:', album); console.log('song file:', songFile); } dir.files(options.dir, function(err, files) { if (err) { console.log(err); return; } if (files) { files.forEach((file) => { processFile(file); }); } }); watch.createMonitor(options.dir, function(monitor) { monitor.on('created', function(file) { processFile(file); }); monitor.on('removed', function(file) { processFile(file); }); });
import dir from 'node-dir'; import path from 'path'; import commandLineArgs from 'command-line-args'; const cli = commandLineArgs([ { name: 'dir', alias: 'd', type: String } ]); const options = cli.parse(); dir.files(options.dir, function(err, files) { if (err) { console.log(err); return; } if (files) { files.forEach((file) => { console.log('file:', file); const [artist, album, songFile] = path.relative(options.dir, file).split(path.sep); console.log('artist:', artist); console.log('album:', album); console.log('song file:', songFile); }); } });
Update regexp for HTML strip
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[^>]+\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
'use strict'; var config = require('../config/configuration.js'); function htmlReplace(str) { return str.replace(/<\/?[a-z1-9]+(\s+[a-z]+=["'](.*)["'])*\/?>/g, ' ').replace(/ +/g, ' ').replace(/ ?\n ?/g, '\n').trim(); } module.exports = function(path, document, changes, finalCb) { if(document.data.html === undefined) { changes.data.html = document.metadata.text; } else if(document.metadata.text === undefined) { changes.metadata.text = htmlReplace(document.data.html); } changes.metadata.text = (changes.metadata.text) ? changes.metadata.text : document.metadata.text; if(document.data.html) { config.separators_html.some(function(separator) { var tmpHTML = document.data.html.split(separator)[0]; if(tmpHTML !== document.data.html) { changes.metadata.text = htmlReplace(tmpHTML); return true; } return false; }); } if(changes.metadata.text === document.metadata.text) { config.separators_text.some(function(separator) { var tmpText = changes.metadata.text.split(separator)[0]; if(tmpText !== changes.metadata.text) { changes.metadata.text = tmpText; return true; } return false; }); } finalCb(null, changes); };
Add column support for sql server --HG-- extra : convert_revision : svn%3A69d324d9-c39d-4fdc-8679-7745eae9e2c8/trunk%40111
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
Remove unused imports in example
import time from osbrain import random_nameserver from osbrain import run_agent def log(agent, message): agent.log_info(message) def rep_handler(agent, message): if agent.i < 10: if not agent.i % 5: agent.send('rep', 5) else: agent.send('rep', 1) agent.i += 1 def worker_loop(agent): while True: agent.send('dispatcher', 'READY!') x = agent.recv('dispatcher') time.sleep(x) agent.send('results', '%s finished with %s' % (agent.name, x)) if __name__ == '__main__': ns = random_nameserver() results = run_agent('Results', nsaddr=ns) results_addr = results.bind('PULL', handler=log) dispatcher = run_agent('Dispatcher', nsaddr=ns) dispatcher.set_attr(i=0) dispatcher_addr = dispatcher.bind('REP', alias='rep', handler=rep_handler) for i in range(5): worker = run_agent('Worker%s' % i, nsaddr=ns) worker.connect(results_addr, alias='results') worker.connect(dispatcher_addr, alias='dispatcher') worker.stop() worker.set_loop(worker_loop) worker.run()
import time from osbrain import random_nameserver from osbrain import run_agent from osbrain import Agent from osbrain import Proxy def log(agent, message): agent.log_info(message) def rep_handler(agent, message): if agent.i < 10: if not agent.i % 5: agent.send('rep', 5) else: agent.send('rep', 1) agent.i += 1 def worker_loop(agent): while True: agent.send('dispatcher', 'READY!') x = agent.recv('dispatcher') time.sleep(x) agent.send('results', '%s finished with %s' % (agent.name, x)) if __name__ == '__main__': ns = random_nameserver() results = run_agent('Results', nsaddr=ns) results_addr = results.bind('PULL', handler=log) dispatcher = run_agent('Dispatcher', nsaddr=ns) dispatcher.set_attr(i=0) dispatcher_addr = dispatcher.bind('REP', alias='rep', handler=rep_handler) for i in range(5): worker = run_agent('Worker%s' % i, nsaddr=ns) worker.connect(results_addr, alias='results') worker.connect(dispatcher_addr, alias='dispatcher') worker.stop() worker.set_loop(worker_loop) worker.run()
Update hex pattern to only contain hex characters
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.subscription.impl; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Checksums of config definition payload or config payload, * md5 and xxhash64 are the supported types at the moment. * * @author hmusum */ public class PayloadChecksum { private static final Pattern hexChecksumPattern = Pattern.compile("[0-9a-fA-F]+"); private final String checksum; private final Type type; public PayloadChecksum(String checksum) { this.checksum = checksum; this.type = Type.MD5; } public static PayloadChecksum empty() { return new PayloadChecksum(""); } public String asString() { return checksum; } public Type type() { return type; } public enum Type {MD5, XXHASH64} public boolean valid() { if (checksum.equals("")) return true; // Empty checksum is ok (e.g. when running 'vespa-get-config') if (type == Type.MD5 && checksum.length() != 32) { return false; } else if (type == Type.XXHASH64 && checksum.length() != 16) { return false; } Matcher m = hexChecksumPattern.matcher(checksum); return m.matches(); } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.subscription.impl; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Checksums of config definition payload or config payload, * md5 and xxhash64 are the supported types at the moment. * * @author hmusum */ public class PayloadChecksum { private static final Pattern hexChecksumPattern = Pattern.compile("[0-9a-zA-Z]+"); private final String checksum; private final Type type; public PayloadChecksum(String checksum) { this.checksum = checksum; this.type = Type.MD5; } public static PayloadChecksum empty() { return new PayloadChecksum(""); } public String asString() { return checksum; } public Type type() { return type; } public enum Type {MD5, XXHASH64} public boolean valid() { if (checksum.equals("")) return true; // Empty checksum is ok (e.g. when running 'vespa-get-config') if (type == Type.MD5 && checksum.length() != 32) { return false; } else if (type == Type.XXHASH64 && checksum.length() != 16) { return false; } Matcher m = hexChecksumPattern.matcher(checksum); return m.matches(); } }
Reorder filters to make the easier to use.
from bonvortaro.vortaro.models import Root, Word, Definition #, Translation from django.contrib import admin class RootAdmin(admin.ModelAdmin): list_display = ["root", "kind", "begining", "ending", "ofc"] list_filter = ["begining", "ending", "kind", "ofc"] admin.site.register(Root, RootAdmin) class WordAdmin(admin.ModelAdmin): list_display = ["language", "word", "kind", "begining", "root", "ending", "ofc", "mrk", "revo_link"] list_filter = ["kind", "ofc", "language", "ending", "begining"] def revo_link(self, word): return "<a href=\"%s\">%s</a>" % (word.revo_url(), word.revo_url()) revo_link.short_description = "Reta Vortaro" revo_link.allow_tags = True admin.site.register(Word, WordAdmin) class DefinitionAdmin(admin.ModelAdmin): list_display = ["word", "definition"] admin.site.register(Definition, DefinitionAdmin)
from bonvortaro.vortaro.models import Root, Word, Definition #, Translation from django.contrib import admin class RootAdmin(admin.ModelAdmin): list_display = ["root", "kind", "begining", "ending", "ofc"] list_filter = ["begining", "ending", "kind", "ofc"] admin.site.register(Root, RootAdmin) class WordAdmin(admin.ModelAdmin): list_display = ["language", "word", "kind", "begining", "root", "ending", "ofc", "mrk", "revo_link"] list_filter = ["ending", "kind", "ofc", "begining", "language"] def revo_link(self, word): return "<a href=\"%s\">%s</a>" % (word.revo_url(), word.revo_url()) revo_link.short_description = "Reta Vortaro" revo_link.allow_tags = True admin.site.register(Word, WordAdmin) class DefinitionAdmin(admin.ModelAdmin): list_display = ["word", "definition"] admin.site.register(Definition, DefinitionAdmin)
Raise NotImplementedError for basic stuff.
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ raise NotImplementedError @reg.generic def app(obj): """Get the application that this object is associated with. """ raise NotImplementedError @reg.generic def base(model): """Get the base that this model is associated with. """ raise NotImplementedError @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ raise NotImplementedError @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ raise NotImplementedError @reg.generic def link(request, model): """Create a link (URL) to model. """ raise NotImplementedError @reg.generic def traject(obj): """Get traject for obj. """ raise NotImplementedError @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ raise NotImplementedError @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """ raise NotImplementedError
import reg @reg.generic def consumer(obj): """A consumer consumes steps in a stack to find an object. """ @reg.generic def app(obj): """Get the application that this object is associated with. """ @reg.generic def base(model): """Get the base that this model is associated with. """ @reg.generic def lookup(obj): """Get the lookup that this object is associated with. """ @reg.generic def path(request, model): """Get the path for a model in the context of a request. """ @reg.generic def link(request, model): """Create a link (URL) to model. """ @reg.generic def traject(obj): """Get traject for obj. """ @reg.generic def resource(request, model): """Get the resource that represents the model in the context of a request. This resource is a representation of the model that be rendered to a response. It may also return a Response directly. If a string is returned, the string is converted to a Response with the string as the response body. """ @reg.generic def response(request, model): """Get a Response for the model in the context of the request. """
Set properties on new files git-svn-id: 2afc70380305c7078ac9d33db6a1fb988992b501@1771268 13f79535-47bb-0310-9956-ffa450edef68
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.crawler.notifications.slack; public class SlackMessage { private String channel; private String text; private boolean mrkdwn = true; public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isMrkdwn() { return mrkdwn; } public void setMrkdwn(boolean mrkdwn) { this.mrkdwn = mrkdwn; } }
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.crawler.notifications.slack; public class SlackMessage { private String channel; private String text; private boolean mrkdwn = true; public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isMrkdwn() { return mrkdwn; } public void setMrkdwn(boolean mrkdwn) { this.mrkdwn = mrkdwn; } }