text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Change weird `array_map` by `foreach`
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace DocHeader\Filter; /** * @author Jefersson Nathan <[email protected]> * @license MIT */ final class Filter { /** * @var string */ private $docheader; private $defaultFilters = [ CurrentYear::class, ]; /** * @param string $docheader */ public function __construct($docheader) { $this->docheader = $docheader; } /** * @return string */ public function applyFilters() { $docheader = $this->docheader; foreach ($this->defaultFilters as $filterName) { $docheader = (new $filterName)->__invoke($docheader); } return $docheader; } }
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. */ namespace DocHeader\Filter; /** * @author Jefersson Nathan <[email protected]> * @license MIT */ final class Filter { /** * @var string */ private $docheader; private $defaultFilters = [ CurrentYear::class, ]; /** * @param string $docheader */ public function __construct($docheader) { $this->docheader = $docheader; } /** * @return string */ public function applyFilters() { array_map( function ($filterName) { $this->docheader = (new $filterName)->__invoke($this->docheader); }, $this->defaultFilters ); return $this->docheader; } }
Check that each module is valid before trying to import.
"""Database Toolkit This package contains a framework for creating and running scripts designed to download published ecological data, and store the data in a database. """ import os import imp VERSION = '0.4.1' REPOSITORY = 'http://www.ecologicaldata.org/dbtk/' def MODULE_LIST(): """Load scripts from scripts directory and return list of modules.""" files = [file for file in os.listdir("scripts") if file[-3:] == ".py" and file[0] != "_"] modules = [] for script in files: script_name = '.'.join(script.split('.')[:-1]) file, pathname, desc = imp.find_module(script_name, ["scripts"]) try: new_module = imp.load_module(script_name, file, pathname, desc) new_module.SCRIPT modules.append(new_module) except: pass return modules def DBTK_LIST(): return [module.SCRIPT for module in MODULE_LIST()] def ENGINE_LIST(): engines = [ "mysql", "postgres", "sqlite", "msaccess", ] ENGINE_MODULE_LIST = [ __import__("dbtk.engines." + module, fromlist="engines") for module in engines ] return [module.engine() for module in ENGINE_MODULE_LIST]
"""Database Toolkit This package contains a framework for creating and running scripts designed to download published ecological data, and store the data in a database. """ import os import imp VERSION = '0.4.1' REPOSITORY = 'http://www.ecologicaldata.org/dbtk/' def MODULE_LIST(): """Load scripts from scripts directory and return list of modules.""" files = [file for file in os.listdir("scripts") if file[-3:] == ".py" and file[0] != "_"] modules = [] for script in files: script_name = '.'.join(script.split('.')[:-1]) file, pathname, desc = imp.find_module(script_name, ["scripts"]) try: new_module = imp.load_module(script_name, file, pathname, desc) modules.append(new_module) except: pass return modules def DBTK_LIST(): return [module.SCRIPT for module in MODULE_LIST()] def ENGINE_LIST(): engines = [ "mysql", "postgres", "sqlite", "msaccess", ] ENGINE_MODULE_LIST = [ __import__("dbtk.engines." + module, fromlist="engines") for module in engines ] return [module.engine() for module in ENGINE_MODULE_LIST]
Update buildbot packages to >= 1.5.0.
from setuptools import setup, find_packages setup( name='autobuilder', version='1.0.3', packages=find_packages(), license='MIT', author='Matt Madison', author_email='[email protected]', entry_points={ 'console_scripts': [ 'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main', 'update-downloads = autobuilder.scripts.update_downloads:main', 'install-sdk = autobuilder.scripts.install_sdk:main', 'autorev-report = autobuilder.scripts.autorev_report:main' ] }, include_package_data=True, package_data={ 'autobuilder': ['templates/*.txt'] }, install_requires=['buildbot[tls]>=1.5.0', 'buildbot-worker>=1.5.0', 'buildbot-www>=1.5.0', 'buildbot-console-view>=1.5.0', 'buildbot-grid-view>=1.5.0', 'buildbot-waterfall-view>=1.5.0' 'buildbot-badges>=1.5.0', 'boto3', 'botocore', 'treq', 'twisted', 'python-dateutil'] )
from setuptools import setup, find_packages setup( name='autobuilder', version='1.0.3', packages=find_packages(), license='MIT', author='Matt Madison', author_email='[email protected]', entry_points={ 'console_scripts': [ 'update-sstate-mirror = autobuilder.scripts.update_sstate_mirror:main', 'update-downloads = autobuilder.scripts.update_downloads:main', 'install-sdk = autobuilder.scripts.install_sdk:main', 'autorev-report = autobuilder.scripts.autorev_report:main' ] }, include_package_data=True, package_data={ 'autobuilder': ['templates/*.txt'] }, install_requires=['buildbot[tls]>=1.4.0', 'buildbot-worker>=1.4.0', 'buildbot-www>=1.4.0', 'buildbot-console-view>=1.4.0', 'buildbot-grid-view>=1.4.0', 'buildbot-waterfall-view>=1.4.0' 'buildbot-badges>=1.4.0', 'boto3', 'botocore', 'treq', 'twisted', 'python-dateutil'] )
Fix incorrect logic for background color checking
var darkColor; var lightColor; self.port.on("colors", function(colors) { darkColor = colors[0]; lightColor = colors[1]; checkElementContrast(document.getElementsByTagName("html")[0]); }); function checkElementContrast(element) { // Don't look at non-renderable elements switch (element.tagName) { case "HEAD": case "TITLE": case "META": case "SCRIPT": case "IMG": case "STYLE": return; } //console.log("Checking: " + element.tagName); var isFgUndefined = (getComputedStyle(element).color == getDefaultComputedStyle(element).color); var isBgUndefined = (getComputedStyle(element).backgroundColor == 'transparent') || (getComputedStyle(element).backgroundColor == 'none'); if (isFgUndefined && isBgUndefined) { console.log("Both undefined, recursing"); // Both undefined, continue with children var children = element.children for (var i=0; i < children.length; i++) { checkElementContrast(element.children[i]); } } else if (isFgUndefined) { element.style.color = darkColor; } else if (isBgUndefined) { element.style.backgroundColor = lightColor; } return; }
var darkColor; var lightColor; self.port.on("colors", function(colors) { darkColor = colors[0]; lightColor = colors[1]; checkElementContrast(document.getElementsByTagName("html")[0]); }); function checkElementContrast(element) { // Don't look at non-renderable elements switch (element.tagName) { case "HEAD": case "TITLE": case "META": case "SCRIPT": case "IMG": case "STYLE": return; } //console.log("Checking: " + element.tagName); var isFgDefined = (getComputedStyle(element).color != getDefaultComputedStyle(element).color); var isBgDefined = (getComputedStyle(element).backgroundColor != 'transparent') || (getComputedStyle(element).backgroundColor != 'none'); if (!isFgDefined && !isBgDefined) { // Both undefined, continue with children var children = element.children for (var i=0; i < children.length; i++) { checkElementContrast(element.children[i]); } } else if (!isFgDefined) { element.style.color = darkColor; } else if (!isBgDefined) { element.style.backgroundColor = lightColor; } return; }
Add link references to function docs
<?php namespace Phamda\Builder\Docs; use Phamda\Builder\CommentExampleBuilder; use Phamda\Builder\PhamdaFunction; use Phamda\Phamda; class ListDocFunctionBuilder { public static function getSection(PhamdaFunction $function) { return implode("\n", [ '', '', sprintf('.. _%s:', $function->getName()), '', $function->getName(), str_repeat('-', strlen($function->getName())), sprintf('``%s``', ((new MethodSignatureBuilder($function))->getSignature())), '', self::getSummary($function), '', self::getExamples($function), ]); } private static function getSummary(PhamdaFunction $function) { $process = Phamda::pipe( Phamda::implode("\n"), Phamda::explode('`'), Phamda::implode('``') ); return $process($function->getComment()->summary); } private static function getExamples(PhamdaFunction $function) { $process = Phamda::pipe( Phamda::construct(CommentExampleBuilder::class), Phamda::invoker(0, 'getRows'), Phamda::map(Phamda::concat(' ')), Phamda::ifElse(Phamda::isEmpty(), Phamda::identity(), Phamda::merge(['.. code-block:: php', ''])), Phamda::implode("\n") ); return $process($function); } }
<?php namespace Phamda\Builder\Docs; use Phamda\Builder\CommentExampleBuilder; use Phamda\Builder\PhamdaFunction; use Phamda\Phamda; class ListDocFunctionBuilder { public static function getSection(PhamdaFunction $function) { return implode("\n", [ '', '', $function->getName(), str_repeat('-', strlen($function->getName())), sprintf('``%s``', ((new MethodSignatureBuilder($function))->getSignature())), '', self::getSummary($function), '', self::getExamples($function), ]); } private static function getSummary(PhamdaFunction $function) { $process = Phamda::pipe( Phamda::implode("\n"), Phamda::explode('`'), Phamda::implode('``') ); return $process($function->getComment()->summary); } private static function getExamples(PhamdaFunction $function) { $process = Phamda::pipe( Phamda::construct(CommentExampleBuilder::class), Phamda::invoker(0, 'getRows'), Phamda::map(Phamda::concat(' ')), Phamda::ifElse(Phamda::isEmpty(), Phamda::identity(), Phamda::merge(['.. code-block:: php', ''])), Phamda::implode("\n") ); return $process($function); } }
Fix stupid migration? Maybe? Might be more trouble later
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateActionlogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasTable('action_logs')) { Schema::create('action_logs', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable(); $table->string('action_type'); $table->integer('target_id')->nullable(); // Was checkedout_to $table->integer('target_type')->nullable(); // For polymorphic thingies $table->integer('location_id')->nullable(); $table->text('note')->nullable(); $table->text('filename')->nullable(); $table->string('item_type'); $table->integer('item_id'); // Replaces asset_id, accessory_id, etc. $table->date('expected_checkin')->nullable()->default(null); $table->integer('accepted_id')->nullable(); $table->timestamps(); $table->softDeletes(); $table->integer('thread_id') ->nullable() ->default(null); $table->index('thread_id'); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('action_logs'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateActionlogTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('action_logs', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->nullable(); $table->string('action_type'); $table->integer('target_id')->nullable(); // Was checkedout_to $table->integer('target_type')->nullable(); // For polymorphic thingies $table->integer('location_id')->nullable(); $table->text('note')->nullable(); $table->text('filename')->nullable(); $table->string('item_type'); $table->integer('item_id'); // Replaces asset_id, accessory_id, etc. $table->date('expected_checkin')->nullable()->default(null); $table->integer('accepted_id')->nullable(); $table->timestamps(); $table->softDeletes(); $table->integer('thread_id') ->nullable() ->default(null); $table->index('thread_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('action_logs'); } }
Define missing local variable "connection"
var socketIo = require('socket.io'); function deepClone(base) { if (!base || typeof base != 'object') return base; var cloned = Object.create(null); Object.keys(base).forEach(function(key) { cloned[key] = deepClone(base[key]); }); return cloned; } function buildResultData(envelope) { return { statusCode: envelope.statusCode, body: deepClone(envelope.body) }; } exports.buildResultData = buildResultData; exports.registerHandlers = function(application, server, params) { params = params || {}; var connection = params.connection; if (!connection) throw new Error('Connection to the backend is required!'); function createRequestHandler(command, socket) { return (function(data) { connection.emitMessage(command, data); }); } function createResultHandler(command, socket) { return (function(envelope) { if (/\.result/.test(envelope.type)) { var data = buildResultData(envelope); socket.emit(envelope.type, data); } }); } var io = socketIo.listen(server); io.sockets.on('connection', function(socket) { [ 'status', 'search', 'createtable', 'removetable', 'createcolumn', 'removecolumn', 'loadrecord', 'loadrecords', ].forEach(function(command) { socket.on(command, createRequestHandler(command, socket)); connection.on('message', createResultHandler(command, socket)); }); }); }
var socketIo = require('socket.io'); function deepClone(base) { if (!base || typeof base != 'object') return base; var cloned = Object.create(null); Object.keys(base).forEach(function(key) { cloned[key] = deepClone(base[key]); }); return cloned; } function buildResultData(envelope) { return { statusCode: envelope.statusCode, body: deepClone(envelope.body) }; } exports.buildResultData = buildResultData; exports.registerHandlers = function(application, server, params) { params = params || {}; if (!connection) throw new Error('Connection to the backend is required!'); function createRequestHandler(command, socket) { return (function(data) { connection.emitMessage(command, data); }); } function createResultHandler(command, socket) { return (function(envelope) { if (/\.result/.test(envelope.type)) { var data = buildResultData(envelope); socket.emit(envelope.type, data); } }); } var io = socketIo.listen(server); io.sockets.on('connection', function(socket) { [ 'status', 'search', 'createtable', 'removetable', 'createcolumn', 'removecolumn', 'loadrecord', 'loadrecords', ].forEach(function(command) { socket.on(command, createRequestHandler(command, socket)); connection.on('message', createResultHandler(command, socket)); }); }); }
fix: Correct typo checkboses --> checkboxes [ci-skip]
/** * Configurable settings for `ivh-treeview` * * @package ivh.treeview * @copyright 2014 iVantage Health Analytics, Inc. */ angular.module('ivh.treeview').provider('ivhTreeviewSettings', function() { 'use strict'; var settings = { /** * Collection item attribute to use for labels */ labelAttribute: 'label', /** * Collection item attribute to use for child nodes */ childrenAttribute: 'children', /** * Collection item attribute to use for selected state */ selectedAttribute: 'selected', /** * Controls whether branches are initially expanded or collapsed * * A value of `0` means the tree will be entirely collapsd (the default * state) otherwise branches will be expanded up to the specified depth. Use * `-1` to have the tree entirely expanded. * * @todo Implement handling non-zero values */ expandByDefaultDepth: 0, /** * Whether or not to use checkboxes * * If `false` the markup to support checkboxes is not included in the * directive. */ useCheckboxes: true, /** * (internal) Collection item attribute to track intermediate states */ indeterminateAttribute: '__ivhTreeviewIntermediate', /** * (internal) Collection item attribute to track visible states */ visibleAttribute: '__ivhTreeviewVisible' }; this.set = function(opts) { angular.extend(settings, opts); }; this.$get = function() { return { get: function() { return angular.copy(settings); } }; }; });
/** * Configurable settings for `ivh-treeview` * * @package ivh.treeview * @copyright 2014 iVantage Health Analytics, Inc. */ angular.module('ivh.treeview').provider('ivhTreeviewSettings', function() { 'use strict'; var settings = { /** * Collection item attribute to use for labels */ labelAttribute: 'label', /** * Collection item attribute to use for child nodes */ childrenAttribute: 'children', /** * Collection item attribute to use for selected state */ selectedAttribute: 'selected', /** * Controls whether branches are initially expanded or collapsed * * A value of `0` means the tree will be entirely collapsd (the default * state) otherwise branches will be expanded up to the specified depth. Use * `-1` to have the tree entirely expanded. * * @todo Implement handling non-zero values */ expandByDefaultDepth: 0, /** * Whether or not to use checkboxes * * If `false` the markup to support checkboxes is not included in the * directive. */ useCheckboses: true, /** * (internal) Collection item attribute to track intermediate states */ indeterminateAttribute: '__ivhTreeviewIntermediate', /** * (internal) Collection item attribute to track visible states */ visibleAttribute: '__ivhTreeviewVisible' }; this.set = function(opts) { angular.extend(settings, opts); }; this.$get = function() { return { get: function() { return angular.copy(settings); } }; }; });
Fix broken redirect after login
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import Paper from 'material-ui/Paper'; import styles from './styles.css'; import LoginForm from './LoginForm'; const LoginPage = ({ isAuthenticated, location }) => { const { from } = location.state || { from: { pathname: '/' } }; return isAuthenticated ? <Redirect to={ from } /> : <div className="login"> <div className="login__modal"> <Paper className="modal"> <Toolbar> <ToolbarTitle text="Welcome back." style={{ color: 'white '}} /> </Toolbar> <LoginForm /> </Paper> </div> </div> }; export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }) )(LoginPage);
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import Paper from 'material-ui/Paper'; import styles from './styles.css'; import LoginForm from './LoginForm'; const LoginPage = ({ isAuthenticated, location }) => { const { from } = location.state || { from: { pathname: '/' } }; return isAuthenticated ? <Redirect t={ from } /> : <div className="login"> <div className="login__modal"> <Paper className="modal"> <Toolbar> <ToolbarTitle text="Welcome back." style={{ color: 'white '}} /> </Toolbar> <LoginForm /> </Paper> </div> </div> }; export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }) )(LoginPage);
Mark internal methods as such
<?php declare(strict_types=1); namespace Brick\Di; /** * Base class for definitions. */ abstract class Definition { /** * @var Scope|null */ private $scope = null; /** * Changes the scope of this definition. * * @param Scope $scope * * @return static */ public function in(Scope $scope) : Definition { $this->scope = $scope; return $this; } /** * Resolves the value of this definition, according to the current scope. * * This method is for internal use by the Container. * * @internal * * @param Container $container * * @return mixed */ public function get(Container $container) { if ($this->scope === null) { $this->scope = $this->getDefaultScope(); } return $this->scope->get($this, $container); } /** * Resolves the value of this definition, regardless of the Scope. * * This method is for internal use by the Scopes. * * @internal * * @param Container $container * * @return mixed */ abstract public function resolve(Container $container); /** * Returns the default Scope for this definition when not set explicitly. * * @return Scope */ abstract protected function getDefaultScope() : Scope; }
<?php declare(strict_types=1); namespace Brick\Di; /** * Base class for definitions. */ abstract class Definition { /** * @var Scope|null */ private $scope = null; /** * Changes the scope of this definition. * * @param Scope $scope * * @return static */ public function in(Scope $scope) : Definition { $this->scope = $scope; return $this; } /** * Resolves the value of this definition, according to the current scope. * * This method is for internal use by the Container. * * @param Container $container * * @return mixed */ public function get(Container $container) { if ($this->scope === null) { $this->scope = $this->getDefaultScope(); } return $this->scope->get($this, $container); } /** * Resolves the value of this definition, regardless of the Scope. * * This method is for internal use by the Scopes. * * @param Container $container * * @return mixed */ abstract public function resolve(Container $container); /** * Returns the default Scope for this definition when not set explicitly. * * @return Scope */ abstract protected function getDefaultScope() : Scope; }
Make sure that the registration serialiser doesn't require the signup date. Signed-off-by: Michael Willmott <[email protected]>
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'strapline', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) signup_date = serializers.DateTimeField(required=False) class Meta: model = RideRiders fields = ('id', 'ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
import requests from django.conf import settings from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from server.api.serializers.chapters import ChapterSerializer from .riders import RiderSerializer from server.core.models.rides import Ride, RideRiders class RideSerializer(serializers.ModelSerializer): chapter = ChapterSerializer() riders = RiderSerializer(source='registered_riders', many=True, read_only=True) class Meta: model = Ride fields = ('id', 'name', 'slug', 'strapline', 'description_html', 'start_location', 'end_location', 'start_date', 'end_date', 'chapter', 'rider_capacity', 'riders', 'spaces_left', 'price', 'full_cost', 'currency', 'is_over', 'fundraising_total', 'fundraising_target') class RideRiderSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = RideRiders fields = ('id', 'ride', 'user', 'signup_date', 'signup_expires', 'status', 'paid', 'expired', 'payload') validators = [ UniqueTogetherValidator( queryset=RideRiders.objects.all(), fields=('user', 'ride'), message='You have already registered for this ride.' ) ]
Remove default for zone, add method for searching for specified zone in environ vars.
from __future__ import absolute_import from toil import version import logging import os logger = logging.getLogger(__name__) def addBasicProvisionerOptions(parser): parser.add_argument("--version", action='version', version=version) parser.add_argument('-p', "--provisioner", dest='provisioner', choices=['aws', 'azure', 'gce'], required=False, default="aws", help="The provisioner for cluster auto-scaling. Only aws is currently " "supported") parser.add_argument('-z', '--zone', dest='zone', required=False, default=None, help="The availability zone of the master. This parameter can also be set via the 'TOIL_X_ZONE' " "environment variable, where X is AWS, GCE, or AZURE, or by the ec2_region_name parameter " "in your .boto file, or derived from the instance metadata if using this utility on an " "existing EC2 instance.") parser.add_argument("clusterName", help="The name that the cluster will be identifiable by. " "Must be lowercase and may not contain the '_' " "character.") return parser def getZoneFromEnv(provisioner): """ Find the zone specified in an environment variable. The user can specify zones in environment variables in leiu of writing them at the commandline every time. Given a provisioner, this method will look for the stored value and return it. :param str provisioner: One of the supported provisioners ('azure', 'aws', 'gce') :rtype: str :return: None or the value stored in a 'TOIL_X_ZONE' environment variable. """ return os.environ.get('TOIL_' + provisioner.upper() + '_ZONE')
from __future__ import absolute_import from toil import version import logging logger = logging.getLogger(__name__) def addBasicProvisionerOptions(parser): parser.add_argument("--version", action='version', version=version) parser.add_argument('-p', "--provisioner", dest='provisioner', choices=['aws', 'azure', 'gce'], required=False, default="aws", help="The provisioner for cluster auto-scaling. Only aws is currently " "supported") try: from toil.provisioners.aws import getCurrentAWSZone currentZone = getCurrentAWSZone() except ImportError: currentZone = None zoneString = currentZone if currentZone else 'No zone could be determined' parser.add_argument('-z', '--zone', dest='zone', required=False, default=currentZone, help="The AWS availability zone of the master. This parameter can also be " "set via the TOIL_AWS_ZONE environment variable, or by the ec2_region_name " "parameter in your .boto file, or derived from the instance metadata if " "using this utility on an existing EC2 instance. " "Currently: %s" % zoneString) parser.add_argument("clusterName", help="The name that the cluster will be identifiable by. " "Must be lowercase and may not contain the '_' " "character.") return parser
[AllBundles] Fix incorrect namespaces in test classes
<?php namespace Kunstmaan\PagePartBundle\Tests\PageTemplate; use Kunstmaan\PagePartBundle\PageTemplate\PageTemplate; use Kunstmaan\PagePartBundle\PageTemplate\PageTemplateConfigurationParser; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\KernelInterface; class PageTemplateConfigurationParserTest extends TestCase { public function testParseSymfony4Flow() { $kernel = $this->createMock(KernelInterface::class); $pageTemplateConfigurationParser = new PageTemplateConfigurationParser($kernel, [ 'contentpage' => [ 'name' => 'Content page', 'rows' => [ ['regions' => [['name' => 'main', 'span' => 12]]], ], 'template' => 'Pages\\ContentPage\\pagetemplate.html.twig', ], ]); $result = $pageTemplateConfigurationParser->parse('contentpage'); $this->assertInstanceOf(PageTemplate::class, $result); $this->assertEquals('Content page', $result->getName()); } public function testParseSymfony3Flow() { $kernel = $this->createMock(KernelInterface::class); $kernel->method('locateResource')->willReturn(__DIR__ . '/Resources/config/pagetemplates/test.yml'); $pageTemplateConfigurationParser = new PageTemplateConfigurationParser($kernel, []); $result = $pageTemplateConfigurationParser->parse('MyWebsiteBundle:test'); $this->assertInstanceOf(PageTemplate::class, $result); $this->assertEquals('Test page', $result->getName()); } }
<?php namespace Kunstmaan\PagePartBundle\Tests\PagePartConfigurationReader; use Kunstmaan\PagePartBundle\PageTemplate\PageTemplate; use Kunstmaan\PagePartBundle\PageTemplate\PageTemplateConfigurationParser; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\KernelInterface; class PageTemplateConfigurationParserTest extends TestCase { public function testParseSymfony4Flow() { $kernel = $this->createMock(KernelInterface::class); $pageTemplateConfigurationParser = new PageTemplateConfigurationParser($kernel, [ 'contentpage' => [ 'name' => 'Content page', 'rows' => [ ['regions' => [['name' => 'main', 'span' => 12]]], ], 'template' => 'Pages\\ContentPage\\pagetemplate.html.twig', ], ]); $result = $pageTemplateConfigurationParser->parse('contentpage'); $this->assertInstanceOf(PageTemplate::class, $result); $this->assertEquals('Content page', $result->getName()); } public function testParseSymfony3Flow() { $kernel = $this->createMock(KernelInterface::class); $kernel->method('locateResource')->willReturn(__DIR__ . '/Resources/config/pagetemplates/test.yml'); $pageTemplateConfigurationParser = new PageTemplateConfigurationParser($kernel, []); $result = $pageTemplateConfigurationParser->parse('MyWebsiteBundle:test'); $this->assertInstanceOf(PageTemplate::class, $result); $this->assertEquals('Test page', $result->getName()); } }
Hide the tree dropdowns if the admin has selected a unknown type
(function($) { $.entwine('kapost', function($) { $(window).resize(function() { $('#Form_ConvertObjectForm').layout(); }); $('#Form_ConvertObjectForm').entwine({ onadd: function(e) { $(this).layout(); } }); $('#Form_ConvertObjectForm_ConvertMode').entwine({ onadd: function(e) { this.updateVisibleFields(); }, updateVisibleFields: function() { var selectedVal=$('#Form_ConvertObjectForm_ConvertMode input.radio:checked').val(); if(selectedVal=='ReplacePage') { $('#Form_ConvertObjectForm #ParentPageID').hide(); $('#Form_ConvertObjectForm #ReplacePageID').show(); }else if(selectedVal=='NewPage') { $('#Form_ConvertObjectForm #ParentPageID').show(); $('#Form_ConvertObjectForm #ReplacePageID').hide(); }else { $('#Form_ConvertObjectForm #ParentPageID, #Form_ConvertObjectForm #ReplacePageID').hide(); } } }); $('#Form_ConvertObjectForm_ConvertMode input.radio').entwine({ onchange: function(e) { $(this).closest('ul').updateVisibleFields(); } }); }); })(jQuery);
(function($) { $.entwine('kapost', function($) { $(window).resize(function() { $('#Form_ConvertObjectForm').layout(); }); $('#Form_ConvertObjectForm').entwine({ onadd: function(e) { $(this).layout(); } }); $('#Form_ConvertObjectForm_ConvertMode').entwine({ onadd: function(e) { this.updateVisibleFields(); }, updateVisibleFields: function() { var selectedVal=$('#Form_ConvertObjectForm_ConvertMode input.radio:checked').val(); if(selectedVal=='ReplacePage') { $('#Form_ConvertObjectForm #ParentPageID').hide(); $('#Form_ConvertObjectForm #ReplacePageID').show(); }else if(selectedVal=='NewPage') { $('#Form_ConvertObjectForm #ParentPageID').show(); $('#Form_ConvertObjectForm #ReplacePageID').hide(); } } }); $('#Form_ConvertObjectForm_ConvertMode input.radio').entwine({ onchange: function(e) { $(this).closest('ul').updateVisibleFields(); } }); }); })(jQuery);
Build wheel excluding local backports
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.6', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='[email protected]', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
from setuptools import find_packages, setup setup( name='caar', version='5.0.0-beta.5', url='http://github.com/nickpowersys/CaaR/', license='BSD 3-Clause License', author='Nicholas A. Brown', author_email='[email protected]', description='Accelerating analysis of time stamped sensor observations and ' 'cycling device operations.', install_requires=[ 'configparser', 'future', 'numpy', 'pandas', ], packages=find_packages(exclude=['docs']), package_data={ }, data_files=[ ], include_package_data=True, platforms='any', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', ], extras_require={ 'testing': ['pytest'], } )
Fix warning caused by undefined index
<?php namespace Hodor\MessageQueue; use Exception; use PHPUnit_Framework_TestCase; class QueueFactoryTest extends PHPUnit_Framework_TestCase { /** * @var array */ private $config; /** * @var QueueFactory */ private $queue_factory; public function setUp() { parent::setUp(); $config_path = __DIR__ . '/../../../../config/config.test.php'; if (!file_exists($config_path)) { throw new Exception("'{$config_path}' not found"); } $this->config = require $config_path; $this->queue_factory = new QueueFactory(); } public function testQueueCanBeGenerated() { $config_template = $this->config['test']['rabbitmq']; $config = [ 'host' => $config_template['host'], 'port' => $config_template['port'], 'username' => $config_template['username'], 'password' => $config_template['password'], 'queue_name' => $config_template['queue_prefix'] . uniqid(), 'fetch_count' => 1, ]; $this->assertInstanceOf( '\Hodor\MessageQueue\Queue', $this->queue_factory->getQueue($config) ); } }
<?php namespace Hodor\MessageQueue; use Exception; use PHPUnit_Framework_TestCase; class QueueFactoryTest extends PHPUnit_Framework_TestCase { /** * @var array */ private $config; /** * @var QueueFactory */ private $queue_factory; public function setUp() { parent::setUp(); $config_path = __DIR__ . '/../../../../config/config.test.php'; if (!file_exists($config_path)) { throw new Exception("'{$config_path}' not found"); } $this->config = require $config_path; $this->queue_factory = new QueueFactory(); } public function testQueueCanBeGenerated() { $config_template = $this->config['test']['rabbitmq']; $config = [ 'host' => $config_template['host'], 'port' => $config_template['port'], 'username' => $config_template['username'], 'password' => $config_template['password'], 'queue_name' => $config_template['queue_prefix'] . uniqid(), ]; $this->assertInstanceOf( '\Hodor\MessageQueue\Queue', $this->queue_factory->getQueue($config) ); } }
Make the package installable at the same time of its requirements. `python setup.py --version` now works even if sqlalchemy is not installed.
import os import re from setuptools import setup with open(os.path.join('sqlalchemy_mptt', '__init__.py'), 'rb') as fh: __version__ = (re.search(r'__version__\s*=\s*u?"([^"]+)"', fh.read()) .group(1).strip()) setup( name='sqlalchemy_mptt', version=__version__, url='http://github.com/ITCase/sqlalchemy_mptt/', author='Svintsov Dmitry', author_email='[email protected]', packages=['sqlalchemy_mptt', ], include_package_data=True, zip_safe=False, test_suite="nose.collector", license="MIT", description='SQLAlchemy MPTT mixins (Nested Sets)', package_data={ '': ['*.txt', '*.rst', '*.md'], }, long_description="http://github.com/ITCase/sqlalchemy_mptt/", install_requires=[ "sqlalchemy", ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Natural Language :: English', 'Natural Language :: Russian', 'Operating System :: OS Independent', 'Programming Language :: Python', "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Framework :: Pyramid ", "Framework :: Flask", "Topic :: Internet", "Topic :: Database", 'License :: OSI Approved :: MIT License', ], )
from sqlalchemy_mptt import __version__ from setuptools import setup setup( name='sqlalchemy_mptt', version=__version__, url='http://github.com/ITCase/sqlalchemy_mptt/', author='Svintsov Dmitry', author_email='[email protected]', packages=['sqlalchemy_mptt', ], include_package_data=True, zip_safe=False, test_suite="nose.collector", license="MIT", description='SQLAlchemy MPTT mixins (Nested Sets)', package_data={ '': ['*.txt', '*.rst', '*.md'], }, long_description="http://github.com/ITCase/sqlalchemy_mptt/", install_requires=[ "sqlalchemy", ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Natural Language :: English', 'Natural Language :: Russian', 'Operating System :: OS Independent', 'Programming Language :: Python', "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Framework :: Pyramid ", "Framework :: Flask", "Topic :: Internet", "Topic :: Database", 'License :: OSI Approved :: MIT License', ], )
Add fix for sqlite bulk_create breaking with loading lots of points
import csv from chemtools.ml import get_decay_feature_vector from chemtools.mol_name import get_exact_name from models import DataPoint def main(path): with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') points = [] count = 0 for row in reader: if row == []: continue try: band_gap = row[10] if band_gap == '---': band_gap = None options = row[4] try: exact_name = get_exact_name(row[1]) try: decay_feature = get_decay_feature_vector(exact_name) except: decay_feature = None except: exact_name = None decay_feature = None point = DataPoint( name=row[1], options=row[4], homo=row[5], lumo=row[6], homo_orbital=row[7], dipole=row[8], energy=row[9], band_gap=band_gap, exact_name=exact_name, decay_feature=decay_feature) point.clean_fields() points.append(point) count += 1 if len(points) > 50: DataPoint.objects.bulk_create(points) points = [] except Exception as e: pass DataPoint.objects.bulk_create(points) print "Added %d datapoint(s)." % count
import csv from chemtools.ml import get_decay_feature_vector from chemtools.mol_name import get_exact_name from models import DataPoint def main(path): with open(path, "r") as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') points = [] count = 0 for row in reader: if row == []: continue try: band_gap = row[10] if band_gap == '---': band_gap = None options = row[4] try: exact_name = get_exact_name(row[1]) try: decay_feature = get_decay_feature_vector(exact_name) except: decay_feature = None except: exact_name = None decay_feature = None point = DataPoint( name=row[1], options=row[4], homo=row[5], lumo=row[6], homo_orbital=row[7], dipole=row[8], energy=row[9], band_gap=band_gap, exact_name=exact_name, decay_feature=decay_feature) point.clean_fields() points.append(point) count += 1 except Exception as e: pass DataPoint.objects.bulk_create(points) print "Added %d datapoints." % count
Remove (currently) unused service instance field
# coding: utf-8 import json from collections import namedtuple from pysuru.base import BaseAPI, ObjectMixin SERVICE_INSTANCE_ATTRS = ( 'name', 'description', 'type', 'plan', ) _ServiceInstance = namedtuple('ServiceInstance', SERVICE_INSTANCE_ATTRS) class ServiceInstance(_ServiceInstance, ObjectMixin): pass class ServiceInstanceAPI(BaseAPI): def filter_by_app(self, name): http_response = self.request('GET', '/services/instances?app=' + name) response = json.loads(http_response.data.decode('utf-8')) services = [] for service_data in response: for index, instance in enumerate(service_data['instances']): data = { 'name': instance, 'type': service_data['service'], 'plan': service_data['plans'][index], } services.append(ServiceInstance.create(**data)) return services def add(self, data): http_response = self.post_json('/services/instances', data) response = json.loads(http_response.data.decode('utf-8')) if response.status == 409: raise ServiceAlreadyExists() elif response.status == 200: return True else: return False class ServiceAlreadyExists(Exception): pass
# coding: utf-8 import json from collections import namedtuple from pysuru.base import BaseAPI, ObjectMixin SERVICE_INSTANCE_ATTRS = ( 'name', 'description', 'type', 'plan', 'teamOwner', ) _ServiceInstance = namedtuple('ServiceInstance', SERVICE_INSTANCE_ATTRS) class ServiceInstance(_ServiceInstance, ObjectMixin): pass class ServiceInstanceAPI(BaseAPI): def filter_by_app(self, name): http_response = self.request('GET', '/services/instances?app=' + name) response = json.loads(http_response.data.decode('utf-8')) services = [] for service_data in response: for index, instance in enumerate(service_data['instances']): data = { 'name': instance, 'type': service_data['service'], 'plan': service_data['plans'][index], } services.append(ServiceInstance.create(**data)) return services def add(self, data): http_response = self.post_json('/services/instances', data) response = json.loads(http_response.data.decode('utf-8')) if response.status == 409: raise ServiceAlreadyExists() elif response.status == 200: return True else: return False class ServiceAlreadyExists(Exception): pass
Allow to import roles when importing people
from zou.app.blueprints.source.csv.base import BaseCsvImportResource from zou.app.models.person import Person from zou.app.utils import auth, permissions from sqlalchemy.exc import IntegrityError class PersonsCsvImportResource(BaseCsvImportResource): def check_permissions(self): return permissions.check_admin_permissions() def import_row(self, row): first_name = row["First Name"] last_name = row["Last Name"] email = row["Email"] phone = row["Phone"] role = row.get("Role", None) if role == "Studio Manager": role = "admin" elif role == "Supervisor": role = "manager" elif role == "Client": role = "client" if role is not None and \ len(role) > 0 and \ role not in ["admin", "manager"]: role = "user" try: password = auth.encrypt_password("default") person = Person.get_by(email=email) if person is None: person = Person.create( email=email, password=password, first_name=first_name, last_name=last_name, phone=phone, role=role ) else: data = { "first_name": first_name, "last_name": last_name, "phone": phone } if role is not None and len(role) > 0: data["role"] = role person.update(data) except IntegrityError: person = Person.get_by(email=email) return person.serialize_safe()
from zou.app.blueprints.source.csv.base import BaseCsvImportResource from zou.app.models.person import Person from zou.app.utils import auth, permissions from sqlalchemy.exc import IntegrityError class PersonsCsvImportResource(BaseCsvImportResource): def check_permissions(self): return permissions.check_admin_permissions() def import_row(self, row): first_name = row["First Name"] last_name = row["Last Name"] email = row["Email"] phone = row["Phone"] try: password = auth.encrypt_password("default") person = Person.get_by(email=email) if person is None: person = Person.create( email=email, password=password, first_name=first_name, last_name=last_name, phone=phone ) else: person.update({ "first_name": first_name, "last_name": last_name, "phone": phone }) except IntegrityError: person = Person.get_by(email=email) return person.serialize_safe()
Add docblocks to observer function
<?php /** * MinTotalQty observer model * * @category Jvs * @package Jvs_MinTotalQty * @author Javier Villanueva <[email protected]> */ class Jvs_MinTotalQty_Model_Observer extends Mage_CatalogInventory_Helper_Minsaleqty { /** * Check minimun order totals * * @param Varien_Event_Observer $observer * @return void */ public function checkTotalQtyBeforeCheckout(Varien_Event_Observer $observer) { $quote = $observer->getDataObject(); $customer = Mage::helper('customer')->getCustomer(); // If the minimun total quantity is not met // redirect to cart page with error message if ($minQty = Mage::helper('jvs_mintotalqty')->minimunOrderQty($quote, $customer)) { Mage::getSingleton('checkout/session')->addUniqueMessages( Mage::getSingleton('core/message') ->error( Mage::helper('cataloginventory') ->__( 'The minimum quantity allowed for purchase is %s.', $minQty ) ) ); // Check if we are not already on the cart page if (!Mage::helper('jvs_mintotalqty')->isCartPage()) { Mage::app()->getFrontController()->getResponse() ->setRedirect(Mage::getUrl('checkout/cart')); Mage::app()->getRequest()->setDispatched(true); } } } }
<?php /** * MinTotalQty observer model * * @category Jvs * @package Jvs_MinTotalQty * @author Javier Villanueva <[email protected]> */ class Jvs_MinTotalQty_Model_Observer extends Mage_CatalogInventory_Helper_Minsaleqty { public function checkTotalQtyBeforeCheckout(Varien_Event_Observer $observer) { $quote = $observer->getDataObject(); $customer = Mage::helper('customer')->getCustomer(); // If the minimun total quantity is not met // redirect to cart page with error message if ($minQty = Mage::helper('jvs_mintotalqty')->minimunOrderQty($quote, $customer)) { Mage::getSingleton('checkout/session')->addUniqueMessages( Mage::getSingleton('core/message') ->error( Mage::helper('cataloginventory') ->__( 'The minimum quantity allowed for purchase is %s.', $minQty ) ) ); // Check if we are not already on the cart page if (!Mage::helper('jvs_mintotalqty')->isCartPage()) { Mage::app()->getFrontController()->getResponse() ->setRedirect(Mage::getUrl('checkout/cart')); Mage::app()->getRequest()->setDispatched(true); } } } }
Remove "Pilotissa mukana" section from footer Closes #159.
import Radium from 'radium'; import React, { Component } from 'react'; import { Grid, Row, Col } from 'react-bootstrap'; import { Link } from 'react-router'; import styles from './Footer.styles'; import logoSrc from 'assets/images/helsinki-coat-of-arms-white.png'; class Footer extends Component { render() { const RadiumLink = Radium(Link); return ( <footer style={styles.footer}> <Grid> <Row> <Col lg={3} md={3}> <RadiumLink style={styles.brandLink} to="/"> <img alt="Helsingin vaakuna" src={logoSrc} style={styles.logo} /> Respa </RadiumLink> </Col> <Col lg={6} md={6}> <p>Tämä on palvelun ensimmäinen pilottiversio, josta toivomme käyttäjiltä palautetta.</p> <p>Palautetta voit lähettää sähköpostilla osoitteeseen <a href="mailto:[email protected]" style={styles.link}>[email protected]</a>.</p> </Col> </Row> </Grid> </footer> ); } } Footer.propTypes = {}; export default Radium(Footer);
import Radium from 'radium'; import React, { Component } from 'react'; import { Grid, Row, Col } from 'react-bootstrap'; import { Link } from 'react-router'; import styles from './Footer.styles'; import logoSrc from 'assets/images/helsinki-coat-of-arms-white.png'; class Footer extends Component { render() { const RadiumLink = Radium(Link); return ( <footer style={styles.footer}> <Grid> <Row> <Col lg={3} md={3}> <RadiumLink style={styles.brandLink} to="/"> <img alt="Helsingin vaakuna" src={logoSrc} style={styles.logo} /> Respa </RadiumLink> </Col> <Col lg={5} md={5}> <p>Tämä on palvelun ensimmäinen pilottiversio, josta toivomme käyttäjiltä palautetta.</p> <p>Palautetta voit lähettää sähköpostilla osoitteeseen <a href="mailto:[email protected]" style={styles.link}>[email protected]</a>.</p> </Col> <Col lg={3} lgOffset={1} md={3} mdOffset={1}> <p>Pilotissa mukana</p> <ul> <li>Kirjasto 10</li> <li>Kaupunkiverstas</li> </ul> </Col> </Row> </Grid> </footer> ); } } Footer.propTypes = {}; export default Radium(Footer);
Reset input for second "request"
from __future__ import absolute_import from __future__ import unicode_literals import django.test from django_digest.test.methods.basic import BasicAuth from django_digest.test.methods.detect import DetectAuth from django_digest.test.methods.digest import DigestAuth class Client(django.test.Client): AUTH_METHODS = {'Basic': BasicAuth, 'Digest': DigestAuth} def __init__(self, *args, **kwargs): super(Client, self).__init__(*args, **kwargs) self.clear_authorization() def request(self, **request): if self.auth_method: request.update(self.auth_method(request)) # This payload object can only be read once. Since digest auth involves # two requests, refresh it for the second "request" payload = request['wsgi.input'].read() request['wsgi.input'] = django.test.client.FakePayload(payload) response = super(Client, self).request(**request) if response.status_code == 401 and self.auth_method: # Try to authenticate request.update(self.auth_method(request, response)) request['wsgi.input'] = django.test.client.FakePayload(payload) response = super(Client, self).request(**request) return response def set_authorization(self, username, password, method=None): self.username = username self.password = password if method is None: self.auth_method = DetectAuth(client=self, username=username, password=password) else: self.auth_method = self.AUTH_METHODS[method](username=username, password=password) def clear_authorization(self): self.username = None self.password = None self.auth_method = None
from __future__ import absolute_import from __future__ import unicode_literals import django.test from django_digest.test.methods.basic import BasicAuth from django_digest.test.methods.detect import DetectAuth from django_digest.test.methods.digest import DigestAuth class Client(django.test.Client): AUTH_METHODS = {'Basic': BasicAuth, 'Digest': DigestAuth} def __init__(self, *args, **kwargs): super(Client, self).__init__(*args, **kwargs) self.clear_authorization() def request(self, **request): if self.auth_method: request.update(self.auth_method(request)) response = super(Client, self).request(**request) if response.status_code == 401 and self.auth_method: # Try to authenticate request.update(self.auth_method(request, response)) response = super(Client, self).request(**request) return response def set_authorization(self, username, password, method=None): self.username = username self.password = password if method is None: self.auth_method = DetectAuth(client=self, username=username, password=password) else: self.auth_method = self.AUTH_METHODS[method](username=username, password=password) def clear_authorization(self): self.username = None self.password = None self.auth_method = None
Watch only tests root folder
module.exports = function(grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), watch: { php: { files: ["src/**/*.php", "tests/*.php"], tasks: ["testphp"] } }, phpunit: { unit: { dir: "tests" }, options: { bin: "vendor/bin/phpunit --coverage-text --coverage-html ./report", colors: true, testdox: false } }, phplint: { options: { swapPath: "/tmp" }, all: ["src/**/*.php", "tests/**/*.php"] }, phpcs: { application: { src: ["src/**/*.php", "tests/**/*.php"] }, options: { bin: "vendor/bin/phpcs", standard: "PSR2" } } }); require("load-grunt-tasks")(grunt); grunt.registerTask("testphp", ["phplint", "phpcs", "phpunit"]); grunt.registerTask("default", ["testphp"]); };
module.exports = function(grunt) { "use strict"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), watch: { php: { files: ["src/**/*.php", "tests/**/*.php"], tasks: ["testphp"] } }, phpunit: { unit: { dir: "tests" }, options: { bin: "vendor/bin/phpunit --coverage-text --coverage-html ./report", colors: true, testdox: false } }, phplint: { options: { swapPath: "/tmp" }, all: ["src/**/*.php", "tests/**/*.php"] }, phpcs: { application: { src: ["src/**/*.php", "tests/**/*.php"] }, options: { bin: "vendor/bin/phpcs", standard: "PSR2" } } }); require("load-grunt-tasks")(grunt); grunt.registerTask("testphp", ["phplint", "phpcs", "phpunit"]); grunt.registerTask("default", ["testphp"]); };
Fix root URL in / link
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link rel="stylesheet" href="{{ $config->baseUrl }}/css/main.css"> </head> <body class="border-t-3 border-primary full-height"> <nav class="navbar navbar-brand"> <div class="container"> <div class="navbar-content"> <div> <a class="link-plain text-xxl flex-y-center" href="{{ $config->baseUrl }}"> <strong>Jigsaw Collections Demo</strong> </a> </div> </div> </div> </nav> <div class="container m-xs-b-6"> <div class="row"> <div class="col-xs-4"> @include('_layouts.sidebar.sections') @include('_layouts.sidebar.meta') @yield('sidebar') </div> <div class="col-xs-8 demo-page"> @yield('body') </div> </div> </div> </body> </html> <!DOCTYPE html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link rel="stylesheet" href="{{ $config->baseUrl }}/css/main.css"> </head> <body class="border-t-3 border-primary full-height"> <nav class="navbar navbar-brand"> <div class="container"> <div class="navbar-content"> <div> <a class="link-plain text-xxl flex-y-center" href="/"> <strong>Jigsaw Collections Demo</strong> </a> </div> </div> </div> </nav> <div class="container m-xs-b-6"> <div class="row"> <div class="col-xs-4"> @include('_layouts.sidebar.sections') @include('_layouts.sidebar.meta') @yield('sidebar') </div> <div class="col-xs-8 demo-page"> @yield('body') </div> </div> </div> </body> </html> <!DOCTYPE html>
Fix online phone number if empty
@extends('template.skeleton') @section('title') {{ Auth::user()->username.' | '._('Online phones') }} @stop @section('content') <div class="container"> <h1>{{ _('Online Phones') }}</h1> <p>Last update: {{ count($online_phones) > 0 ? $online_phones[0]->created_at : ''}}</p> @include('template.messages') <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>{{ _('Phone Number (E.164)') }}</th> <th>{{ _('Local Phone Number') }}</th> <th>{{ _('Domain') }}</th> <th>{{ _('Description') }}</th> </tr> @foreach ($online_phones as $online_phone) <tr> <td>+{{ Config::get('settings.global_prefix') }}-{{ $online_phone->domain->prefix }}-{{ $online_phone->username }}</td> <td>{{ $online_phone->username }}</td> <td>{{ $online_phone->sip_server }}</td> <td>{{ $online_phone->phonenumber->description }}</td> </tr> @endforeach </table> </div> </div> @stop
@extends('template.skeleton') @section('title') {{ Auth::user()->username.' | '._('Online phones') }} @stop @section('content') <div class="container"> <h1>{{ _('Online Phones') }}</h1> <p>Last update: {{ $online_phones[0]->created_at }}</p> @include('template.messages') <div class="table-responsive"> <table class="table table-bordered table-striped"> <tr> <th>{{ _('Phone Number (E.164)') }}</th> <th>{{ _('Local Phone Number') }}</th> <th>{{ _('Domain') }}</th> <th>{{ _('Description') }}</th> </tr> @foreach ($online_phones as $online_phone) <tr> <td>+{{ Config::get('settings.global_prefix') }}-{{ $online_phone->domain->prefix }}-{{ $online_phone->username }}</td> <td>{{ $online_phone->username }}</td> <td>{{ $online_phone->sip_server }}</td> <td>{{ $online_phone->phonenumber->description }}</td> </tr> @endforeach </table> </div> </div> @stop
Fix a little last bug.
<?php namespace AdminBundle\Controller; use DemandeSubventionBundle\Entity\Demandessubvention; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\VarDumper\VarDumper; class DefaultController extends Controller { public function indexAction() { if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { // Get Association $associations = $this->getDoctrine() ->getRepository('AssociationBundle:Associations') ->findAll(); $demandessubvention = array(); //Array of Demande de Subvention $demandessubvention = $this->getDoctrine() ->getRepository('DemandeSubventionBundle:Demandessubvention') ->findAll(); // redirect authenticated users to homepage return $this->render('AdminBundle:Default:index.html.twig',array('associations' => $associations, 'demandessubvention' => $demandessubvention)); } else if ($this->get('security.authorization_checker')->isGranted('ROLE_USER')) { // redirect authenticated admin to homepage return $this->redirectToRoute('AssociationBundle_homepage'); } else { return $this->redirectToRoute('UserBundle_login'); } } }
<?php namespace AdminBundle\Controller; use DemandeSubventionBundle\Entity\Demandessubvention; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\VarDumper\VarDumper; class DefaultController extends Controller { public function indexAction() { if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')) { // Get Association $associations = $this->getDoctrine() ->getRepository('AssociationBundle:Associations') ->findAll(); $demandessubvention = array(); //Array of Demande de Subvention foreach($associations as $assoc) { // Get Demande Subvention $demandessubvention = $this->getDoctrine() ->getRepository('DemandeSubventionBundle:Demandessubvention') ->findBy(array('associationsNumassoc' => $assoc)); }; // redirect authenticated users to homepage return $this->render('AdminBundle:Default:index.html.twig',array('associations' => $associations, 'demandessubvention' => $demandessubvention)); } else if ($this->get('security.authorization_checker')->isGranted('ROLE_USER')) { // redirect authenticated admin to homepage return $this->redirectToRoute('AssociationBundle_homepage'); } else { return $this->redirectToRoute('UserBundle_login'); } } }
Mark monkey patching code test as parallel false
// Load modules var Hapi = require('hapi'); var Code = require('code'); var Lab = require('lab'); var Server = require('../lib'); var Version = require('../lib/version'); // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.experiment; var expect = Code.expect; var it = lab.test; describe('Server', function() { it('starts server and return hapi server object', function (done) { Server.init(0, function (err, server) { expect(err).to.not.exist(); expect(server).to.be.instanceof(Hapi.Server); server.stop(done); }); }); it('starts server on provided port', function (done) { Server.init(5000, function (err, server) { expect(err).to.not.exist(); expect(server.info.port).to.equal(5000); server.stop(done); }); }); it('handles register plugin errors', { parallel: true }, function (done) { var register = Version.register; Version.register = function (server, options, next) { return next(new Error('register version failed')); }; Version.register.attributes = { name: 'fake version' }; Server.init(0, function (err, server) { expect(err).to.exist(); expect(err.message).to.equal('register version failed'); Version.register = register; done(); }); }); });
// Load modules var Hapi = require('hapi'); var Code = require('code'); var Lab = require('lab'); var Server = require('../lib'); var Version = require('../lib/version'); // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.experiment; var expect = Code.expect; var it = lab.test; describe('Server', function() { it('starts server and return hapi server object', function (done) { Server.init(0, function (err, server) { expect(err).to.not.exist(); expect(server).to.be.instanceof(Hapi.Server); server.stop(done); }); }); it('starts server on provided port', function (done) { Server.init(5000, function (err, server) { expect(err).to.not.exist(); expect(server.info.port).to.equal(5000); server.stop(done); }); }); it('handles register plugin errors', function (done) { var register = Version.register; Version.register = function (server, options, next) { return next(new Error('register version failed')); }; Version.register.attributes = { name: 'fake version' }; Server.init(0, function (err, server) { expect(err).to.exist(); expect(err.message).to.equal('register version failed'); Version.register = register; done(); }); }); });
Adjust the coefficient of classifiers
# Headers __author__ = 'Somsubhra Bairi' __email__ = '[email protected]' # All imports from extras import Logger from nltk import PorterStemmer # Classify according to document frequency class ITFIDFClassifier: # Constructor for the ITFIDFClassifier def __init__(self, dict_file): dictionary_file = open(dict_file) self.itfidf_dictionary = {} self.avg_itfidf = 0 # Construct the document frequency dictionary for line in dictionary_file.readlines(): cols = line.split(";") self.itfidf_dictionary[cols[0]] = int(cols[1]) self.avg_itfidf += int(cols[1]) self.avg_itfidf /= len(self.itfidf_dictionary) dictionary_file.close() # Classify the word def is_difficult(self, word): if word.isdigit(): return False sanitized_word = ''.join(e for e in word if e.isalnum()).lower() stemmed_word = PorterStemmer().stem_word(sanitized_word) if stemmed_word in self.itfidf_dictionary: return self.itfidf_dictionary[stemmed_word] > self.avg_itfidf / 16 else: return True
# Headers __author__ = 'Somsubhra Bairi' __email__ = '[email protected]' # All imports from extras import Logger from nltk import PorterStemmer # Classify according to document frequency class ITFIDFClassifier: # Constructor for the ITFIDFClassifier def __init__(self, dict_file): dictionary_file = open(dict_file) self.itfidf_dictionary = {} self.avg_itfidf = 0 # Construct the document frequency dictionary for line in dictionary_file.readlines(): cols = line.split(";") self.itfidf_dictionary[cols[0]] = int(cols[1]) self.avg_itfidf += int(cols[1]) self.avg_itfidf /= len(self.itfidf_dictionary) dictionary_file.close() # Classify the word def is_difficult(self, word): if word.isdigit(): return False sanitized_word = ''.join(e for e in word if e.isalnum()).lower() stemmed_word = PorterStemmer().stem_word(sanitized_word) if stemmed_word in self.itfidf_dictionary: return self.itfidf_dictionary[stemmed_word] > self.avg_itfidf * 1 else: return True
Add method to create tempfile with content easily
import subprocess32 as subprocess import threading import signal import tempfile import os def external_process(process_args, input_data='', timeout=None): ''' Pipes input_data via stdin to the process specified by process_args and returns the results Arguments: process_args -- passed directly to subprocess.Popen(), see there for more details input_data -- the data to pipe in via STDIN (optional) timeout -- number of seconds to time out the process after (optional) IF the process timesout, a subprocess32.TimeoutExpired exception will be raised Returns: (exit_status, stdout, stderr) -- a tuple of the exit status code and strings containing stdout and stderr data Examples: >>> external_process(['grep', 'Data'], input_data="Some String\nWith Data") (0, 'With Data\n', '') ''' process = subprocess.Popen(process_args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = process.communicate(input_data, timeout) except subprocess.TimeoutExpired as e: # cleanup process # see https://docs.python.org/3.3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate process.kill() process.communicate() raise e exit_status = process.returncode return (exit_status, stdout, stderr) def temp_file(data, suffix=''): handle, file_path = tempfile.mkstemp(suffix=suffix) f = os.fdopen(handle, 'w') f.write(data) f.close() return file_path
import subprocess32 as subprocess import threading import signal def external_process(process_args, input_data='', timeout=None): ''' Pipes input_data via stdin to the process specified by process_args and returns the results Arguments: process_args -- passed directly to subprocess.Popen(), see there for more details input_data -- the data to pipe in via STDIN (optional) timeout -- number of seconds to time out the process after (optional) IF the process timesout, a subprocess32.TimeoutExpired exception will be raised Returns: (exit_status, stdout, stderr) -- a tuple of the exit status code and strings containing stdout and stderr data Examples: >>> external_process(['grep', 'Data'], input_data="Some String\nWith Data") (0, 'With Data\n', '') ''' process = subprocess.Popen(process_args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) try: (stdout, stderr) = process.communicate(input_data, timeout) except subprocess.TimeoutExpired as e: # cleanup process # see https://docs.python.org/3.3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate process.kill() process.communicate() raise e exit_status = process.returncode return (exit_status, stdout, stderr)
Send values of items in withArray with the model array
<?php namespace Laraquick\Models\Traits; use Illuminate\Database\Eloquent\Builder; trait Helper { /** * A shortcut to withoutGlobalScope() * * @param string|array $attributes * @return Builder */ public function without($attributes) { return $this->withoutGlobalScope($attributes); } /** * Excludes the given values from being selected from the database * Thanks to Ikechi Michael (@mykeels) * * @param Builder $query * @param string|array $value * @return void */ public function scopeExcept($query, $value) { $defaultColumns = ['id', 'created_at', 'updated_at']; if (in_array_('deleted_at', $this->dates)) { $defaultColumns[] = 'deleted_at'; } if (is_string($value)) { $value = [$value]; } return $query->select(array_diff(array_merge($defaultColumns, $this->fillable), (array) $value)); } public function toArray() { $withArray = property_exists($this, 'withArray') ? $this->withArray : []; $fillable = array_merge($this->fillable, $withArray); array_unshift($fillable, 'id'); $array = collect(parent::toArray()) // Show only fillables ->only($fillable) // Hide hidden ones ->except($this->hidden) ->all(); // merge with relations and return return array_merge($array, $this->relations); } }
<?php namespace Laraquick\Models\Traits; use Illuminate\Database\Eloquent\Builder; trait Helper { /** * A shortcut to withoutGlobalScope() * * @param string|array $attributes * @return Builder */ public function without($attributes) { return $this->withoutGlobalScope($attributes); } /** * Excludes the given values from being selected from the database * Thanks to Ikechi Michael (@mykeels) * * @param Builder $query * @param string|array $value * @return void */ public function scopeExcept($query, $value) { $defaultColumns = ['id', 'created_at', 'updated_at']; if (in_array_('deleted_at', $this->dates)) { $defaultColumns[] = 'deleted_at'; } if (is_string($value)) { $value = [$value]; } return $query->select(array_diff(array_merge($defaultColumns, $this->fillable), (array) $value)); } public function toArray() { $fillable = $this->fillable; array_unshift($fillable, 'id'); $array = collect(parent::toArray()) // Show only fillables ->only($fillable) // Hide hidden ones ->except($this->hidden) ->all(); // merge with relations and return return array_merge($array, $this->relations); } }
Fix notifications building from JSON Sometimes (like in welcome messages), notifications don't have a 'title' property, so we shouldn't assume there is one. Bug: T139015 Change-Id: I83e480d04e8e09aa9bcb5edef4f56b47d150e199
# -*- coding: utf-8 -*- """Classes and functions for working with the Echo extension.""" from __future__ import absolute_import, unicode_literals import pywikibot class Notification(object): """A notification issued by the Echo extension.""" def __init__(self, site): """Construct an empty Notification object.""" self.site = site @classmethod def fromJSON(cls, site, data): """ Construct a Notification object from JSON data returned by the API. @rtype: Notification """ notif = cls(site) notif.id = data['id'] # TODO: use numeric id ? notif.type = data['type'] notif.category = data['category'] notif.timestamp = pywikibot.Timestamp.fromtimestampformat(data['timestamp']['mw']) if 'title' in data and 'full' in data['title']: notif.page = pywikibot.Page(site, data['title']['full']) else: notif.page = None if 'agent' in data and 'name' in data['agent']: notif.agent = pywikibot.User(site, data['agent']['name']) else: notif.agent = None if 'read' in data: notif.read = pywikibot.Timestamp.fromtimestampformat(data['read']) else: notif.read = False notif.content = data.get('*', None) return notif def mark_as_read(self): """Mark the notification as read.""" return self.site.notifications_mark_read(list=self.id)
# -*- coding: utf-8 -*- """Classes and functions for working with the Echo extension.""" from __future__ import absolute_import, unicode_literals import pywikibot class Notification(object): """A notification issued by the Echo extension.""" def __init__(self, site): """Construct an empty Notification object.""" self.site = site @classmethod def fromJSON(cls, site, data): """ Construct a Notification object from JSON data returned by the API. @rtype: Notification """ notif = cls(site) notif.id = data['id'] # TODO: use numeric id ? notif.type = data['type'] notif.category = data['category'] notif.timestamp = pywikibot.Timestamp.fromtimestampformat(data['timestamp']['mw']) # TODO: use 'namespace-key' + 'text' ? notif.page = pywikibot.Page(site, data['title']['full']) if 'agent' in data and 'name' in data['agent']: notif.agent = pywikibot.User(site, data['agent']['name']) else: notif.agent = None if 'read' in data: notif.read = pywikibot.Timestamp.fromtimestampformat(data['read']) else: notif.read = False notif.content = data.get('*', None) return notif def mark_as_read(self): """Mark the notification as read.""" return self.site.notifications_mark_read(list=self.id)
Fix removing scrolls from equipment inventory
package net.wayward_realms.waywardcharacters; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import java.util.Arrays; public class InventoryClickListener implements Listener { @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getTitle().equalsIgnoreCase("Equipment")) { if (event.isShiftClick()) { event.setCancelled(true); return; } if (Arrays.asList(0, 1, 2, 3, 4, 5, 9, 12, 13, 14, 18, 19, 20, 21, 22, 23).contains(event.getRawSlot())) { event.setCancelled(true); return; } if (Arrays.asList(6, 7, 8, 15, 16, 17, 24, 25, 26).contains(event.getRawSlot())) { if ((event.getCursor().getType() != Material.PAPER || !event.getCursor().hasItemMeta() || !event.getCursor().getItemMeta().hasDisplayName() || !event.getCursor().getItemMeta().getDisplayName().equals(ChatColor.YELLOW + "Scroll")) && event.getCursor().getType() != Material.AIR) { event.setCancelled(true); return; } } } } }
package net.wayward_realms.waywardcharacters; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import java.util.Arrays; public class InventoryClickListener implements Listener { @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().getTitle().equalsIgnoreCase("Equipment")) { if (event.isShiftClick()) { event.setCancelled(true); return; } if (Arrays.asList(0, 1, 2, 3, 4, 5, 9, 12, 13, 14, 18, 19, 20, 21, 22, 23).contains(event.getRawSlot())) { event.setCancelled(true); return; } if (Arrays.asList(6, 7, 8, 15, 16, 17, 24, 25, 26).contains(event.getRawSlot())) { if (event.getCursor().getType() != Material.PAPER || !event.getCursor().hasItemMeta() || !event.getCursor().getItemMeta().hasDisplayName() || !event.getCursor().getItemMeta().getDisplayName().equals(ChatColor.YELLOW + "Scroll")) { event.setCancelled(true); return; } } } } }
Use new namespace for ClassLookup
<?php namespace Kunstmaan\FormBundle\Entity\PageParts; use Kunstmaan\UtilitiesBundle\Helper\ClassLookup; use Kunstmaan\FormBundle\Entity\FormAdaptorInterface; use Kunstmaan\PagePartBundle\Entity\AbstractPagePart; use Doctrine\ORM\Mapping as ORM; /** * Abstract version of a form page part */ abstract class AbstractFormPagePart extends AbstractPagePart implements FormAdaptorInterface { const ERROR_REQUIRED_FIELD = "field.required"; /** * The label * * @ORM\Column(type="string", nullable=true) */ protected $label; /** * Returns a unique id for the current page part * * @return string */ public function getUniqueId() { return str_replace('\\', ':', ClassLookup::getClass($this)) . $this->id; //TODO } /** * Set the label used for this page part * * @param int $label */ public function setLabel($label) { $this->label = $label; } /** * Get the label used for this page part * * @return string */ public function getLabel() { return $this->label; } /** * Returns the view used in the backend * * @return string */ public function getAdminView() { return "KunstmaanFormBundle:AbstractFormPagePart:admin-view.html.twig"; } }
<?php namespace Kunstmaan\FormBundle\Entity\PageParts; use Kunstmaan\AdminBundle\Helper\ClassLookup; use Kunstmaan\FormBundle\Entity\FormAdaptorInterface; use Kunstmaan\PagePartBundle\Entity\AbstractPagePart; use Doctrine\ORM\Mapping as ORM; /** * Abstract version of a form page part */ abstract class AbstractFormPagePart extends AbstractPagePart implements FormAdaptorInterface { const ERROR_REQUIRED_FIELD = "field.required"; /** * The label * * @ORM\Column(type="string", nullable=true) */ protected $label; /** * Returns a unique id for the current page part * * @return string */ public function getUniqueId() { return str_replace('\\', ':', ClassLookup::getClass($this)) . $this->id; //TODO } /** * Set the label used for this page part * * @param int $label */ public function setLabel($label) { $this->label = $label; } /** * Get the label used for this page part * * @return string */ public function getLabel() { return $this->label; } /** * Returns the view used in the backend * * @return string */ public function getAdminView() { return "KunstmaanFormBundle:AbstractFormPagePart:admin-view.html.twig"; } }
Build gc-orders-server from commit bd221fb on branch master
'use strict'; let passport = require('passport'); let LocalStrategy = require('passport-local').Strategy; const AUTH_ERROR = {message: 'Invalid email or password.'}; let localPassport = { localAuthenticate, setup }; function localAuthenticate(userService, email, password, done) { userService.getByEmail(email.toLowerCase()) .then(user => { if (!user) { return done(null, false, AUTH_ERROR); } user.authenticate(password, function (authError, authenticated) { if (authError) { return done(authError); } if (authenticated) { return done(null, user); } else { return done(null, false, AUTH_ERROR); } }); }) .catch(err => { console.log('ERROR!'); done(err) }); } function setup(userService, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function (email, password, done) { return localAuthenticate(userService, email, password, done); })); } module.exports = localPassport;
let passport = require('passport'); let LocalStrategy = require('passport-local').Strategy; const AUTH_ERROR = {message: 'Invalid email or password.'}; let localPassport = { localAuthenticate, setup }; function localAuthenticate(userService, email, password, done) { userService.getByEmail(email.toLowerCase()) .then(user => { if (!user) { return done(null, false, AUTH_ERROR); } user.authenticate(password, function (authError, authenticated) { if (authError) { return done(authError); } if (authenticated) { return done(null, user); } else { return done(null, false, AUTH_ERROR); } }); }) .catch(err => { console.log('ERROR!'); done(err) }); } function setup(userService, config) { passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' // this is the virtual field on the model }, function (email, password, done) { return localAuthenticate(userService, email, password, done); })); } module.exports = localPassport;
Move seq size to const
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: max_seq_size = 1000 loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get('ENV_FILE'))) if not os.path.exists(env_file_path): raise FileNotFoundError('Can''t find site config file') load_dotenv(env_file_path) Config.loaded = True @staticmethod def get(key, default_value=None): if Config.loaded is False: Config.load() value = os.environ.get(key) if not value: if default_value is not None: return default_value raise ValueError('Empty config value, name {}'.format(key)) return value @staticmethod def get_seq(key, sep='_'): if Config.loaded is False: Config.load() array = [] counter = 1 while True: value = os.environ.get('{}{}{}'.format(key, sep, counter)) if value is None or counter > Config.max_seq_size: break array.append(value) counter += 1 if len(array) == 0: raise ValueError('Empty seq values') return array
import os from os.path import join, dirname, abspath from dotenv import load_dotenv class Config: loaded = False @staticmethod def load(file_name='../config/.env'): load_dotenv(join(dirname(__file__), file_name)) env_file_path = abspath(join(dirname(__file__), '../config', os.environ.get('ENV_FILE'))) if not os.path.exists(env_file_path): raise FileNotFoundError('Can''t find site config file') load_dotenv(env_file_path) Config.loaded = True @staticmethod def get(key, default_value=None): if Config.loaded is False: Config.load() value = os.environ.get(key) if not value: if default_value: return default_value raise ValueError('Empty config value, name {}'.format(key)) return value @staticmethod def get_seq(key, sep='_'): if Config.loaded is False: Config.load() array = [] counter = 1 while True: value = os.environ.get('{}{}{}'.format(key, sep, counter)) if value is None or counter > 1000: break array.append(value) counter += 1 if len(array) == 0: raise ValueError('Empty seq values') return array
telemetry: Fix an import path in the Android screen recorder Review URL: https://codereview.chromium.org/1301613004 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#343960}
# 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. import os import subprocess from telemetry.core import util from telemetry.internal.platform import profiler from telemetry.internal.backends.chrome import android_browser_finder class AndroidScreenRecordingProfiler(profiler.Profiler): """Captures a screen recording on Android.""" def __init__(self, browser_backend, platform_backend, output_path, state): super(AndroidScreenRecordingProfiler, self).__init__( browser_backend, platform_backend, output_path, state) self._output_path = output_path + '.mp4' self._recorder = subprocess.Popen( [os.path.join(util.GetChromiumSrcDir(), 'build', 'android', 'screenshot.py'), '--video', '--file', self._output_path, '--device', browser_backend.device.adb.GetDeviceSerial()], stdin=subprocess.PIPE, stdout=subprocess.PIPE) @classmethod def name(cls): return 'android-screen-recorder' @classmethod def is_supported(cls, browser_type): if browser_type == 'any': return android_browser_finder.CanFindAvailableBrowsers() return browser_type.startswith('android') def CollectProfile(self): self._recorder.communicate(input='\n') print 'Screen recording saved as %s' % self._output_path print 'To view, open in Chrome or a video player' return [self._output_path]
# 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. import os import subprocess from telemetry.internal.platform import profiler from telemetry.internal import util from telemetry.internal.backends.chrome import android_browser_finder class AndroidScreenRecordingProfiler(profiler.Profiler): """Captures a screen recording on Android.""" def __init__(self, browser_backend, platform_backend, output_path, state): super(AndroidScreenRecordingProfiler, self).__init__( browser_backend, platform_backend, output_path, state) self._output_path = output_path + '.mp4' self._recorder = subprocess.Popen( [os.path.join(util.GetChromiumSrcDir(), 'build', 'android', 'screenshot.py'), '--video', '--file', self._output_path, '--device', browser_backend.device.adb.GetDeviceSerial()], stdin=subprocess.PIPE, stdout=subprocess.PIPE) @classmethod def name(cls): return 'android-screen-recorder' @classmethod def is_supported(cls, browser_type): if browser_type == 'any': return android_browser_finder.CanFindAvailableBrowsers() return browser_type.startswith('android') def CollectProfile(self): self._recorder.communicate(input='\n') print 'Screen recording saved as %s' % self._output_path print 'To view, open in Chrome or a video player' return [self._output_path]
Remove prefix '_' while passing context param to templates
const BaseDataview = require('./base'); const debug = require('debug')('windshaft:dataview:list'); const TYPE = 'list'; const listSqlTpl = ctx => `select ${ctx.columns} from (${ctx.query}) as _cdb_list`; /** { type: 'list', options: { columns: ['name', 'description'] } } */ module.exports = class List extends BaseDataview { constructor (query, options = {}) { super(); this._checkOptions(options); this.query = query; this.columns = options.columns; } _checkOptions (options) { if (!Array.isArray(options.columns)) { throw new Error('List expects `columns` array in dataview options'); } } sql (psql, override, callback) { if (!callback) { callback = override; } const listSql = listSqlTpl({ query: this.query, columns: this.columns.join(', ') }); debug(listSql); return callback(null, listSql); } format (result) { return { rows: result.rows }; } getType () { return TYPE; } toString () { return JSON.stringify({ _type: TYPE, _query: this.query, _columns: this.columns.join(', ') }); }; }
const BaseDataview = require('./base'); const debug = require('debug')('windshaft:dataview:list'); const TYPE = 'list'; const listSqlTpl = ctx => `select ${ctx._columns} from (${ctx._query}) as _cdb_list`; /** { type: 'list', options: { columns: ['name', 'description'] } } */ module.exports = class List extends BaseDataview { constructor (query, options = {}) { super(); this._checkOptions(options); this.query = query; this.columns = options.columns; } _checkOptions (options) { if (!Array.isArray(options.columns)) { throw new Error('List expects `columns` array in dataview options'); } } sql (psql, override, callback) { if (!callback) { callback = override; } const listSql = listSqlTpl({ _query: this.query, _columns: this.columns.join(', ') }); debug(listSql); return callback(null, listSql); } format (result) { return { rows: result.rows }; } getType () { return TYPE; } toString () { return JSON.stringify({ _type: TYPE, _query: this.query, _columns: this.columns.join(', ') }); }; }
Fix Jackson no suitable constructor found
package com.github.couchmove.pojo; import com.couchbase.client.java.Bucket; import lombok.*; import org.jetbrains.annotations.NotNull; import java.util.Date; import static lombok.AccessLevel.PRIVATE; /** * a {@link CouchbaseEntity} representing a change in Couchbase {@link Bucket} * * @author ctayeb * Created on 27/05/2017 */ @AllArgsConstructor @NoArgsConstructor(access = PRIVATE) @EqualsAndHashCode(callSuper = false) @Builder(toBuilder = true) @Data public class ChangeLog extends CouchbaseEntity implements Comparable<ChangeLog> { /** * The version of the change */ private String version; /** * The execution order of the change */ private Integer order; /** * The description of the change */ private String description; /** * The {@link Type} of the change */ private Type type; /** * The script file or folder that was executed in the change */ private String script; /** * A unique identifier of the file or folder of the change */ private String checksum; /** * The OS username of the process that executed the change */ private String runner; /** * Date of execution of the change */ private Date timestamp; /** * The duration of the execution of the change in milliseconds */ private Long duration; /** * The {@link Status} of the change */ private Status status; @Override public int compareTo(@NotNull ChangeLog o) { return version == null ? 0 : version.compareTo(o.version); } }
package com.github.couchmove.pojo; import com.couchbase.client.java.Bucket; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import org.jetbrains.annotations.NotNull; import java.util.Date; /** * a {@link CouchbaseEntity} representing a change in Couchbase {@link Bucket} * * @author ctayeb * Created on 27/05/2017 */ @EqualsAndHashCode(callSuper = false) @Builder(toBuilder = true) @Data public class ChangeLog extends CouchbaseEntity implements Comparable<ChangeLog> { /** * The version of the change */ private String version; /** * The execution order of the change */ private Integer order; /** * The description of the change */ private String description; /** * The {@link Type} of the change */ private Type type; /** * The script file or folder that was executed in the change */ private String script; /** * A unique identifier of the file or folder of the change */ private String checksum; /** * The OS username of the process that executed the change */ private String runner; /** * Date of execution of the change */ private Date timestamp; /** * The duration of the execution of the change in milliseconds */ private Long duration; /** * The {@link Status} of the change */ private Status status; @Override public int compareTo(@NotNull ChangeLog o) { return version == null ? 0 : version.compareTo(o.version); } }
Increase default max image size to 3 MB. This should allow uploads from most phones with their default settings.
// Disable auto discover for all elements: //Dropzone.autoDiscover = false; var submissionDropzone; Dropzone.options.submissionDropzone = { url: "/images/upload", maxFilesize: 3, paramName: "uploadfile", maxThumbnailFilesize: 3, clickable: true, maxFiles: 1, acceptedFiles: "image/jpeg,image/png", thumbnailWidth: 250, resize: function(file) { var ratio = 250 / file.width; var imgHeight = file.height * ratio; if (imgHeight > 250) { imgHeight = 250; //constrain } var resizeInfo = { srcX: 0, srcY: 0, trgX: 0, trgY: 0, srcWidth: file.width, srcHeight: file.height, trgWidth: this.options.thumbnailWidth, trgHeight: imgHeight }; $('.dz-details img').height(imgHeight); return resizeInfo; }, init: function() { submissionDropzone = this; this.on('success', function(file, json) { $("#imagefile").val(json.img); }); this.on('error', function(file, errorMessage, xhr) { $(".dz-error-mark").click(function() { submissionDropzone.removeFile(file); }); }); this.on('addedfile', function(file) { }); this.on('drop', function(file) { }); } };
// Disable auto discover for all elements: //Dropzone.autoDiscover = false; var submissionDropzone; Dropzone.options.submissionDropzone = { url: "/images/upload", maxFilesize: 2, paramName: "uploadfile", maxThumbnailFilesize: 2, clickable: true, maxFiles: 1, acceptedFiles: "image/jpeg,image/png", thumbnailWidth: 250, resize: function(file) { var ratio = 250 / file.width; var imgHeight = file.height * ratio; if (imgHeight > 250) { imgHeight = 250; //constrain } var resizeInfo = { srcX: 0, srcY: 0, trgX: 0, trgY: 0, srcWidth: file.width, srcHeight: file.height, trgWidth: this.options.thumbnailWidth, trgHeight: imgHeight }; $('.dz-details img').height(imgHeight); return resizeInfo; }, init: function() { submissionDropzone = this; this.on('success', function(file, json) { $("#imagefile").val(json.img); }); this.on('error', function(file, errorMessage, xhr) { $(".dz-error-mark").click(function() { submissionDropzone.removeFile(file); }); }); this.on('addedfile', function(file) { }); this.on('drop', function(file) { }); } };
Move game specific JS into its own script.
$(function() { socket = io.connect(':9000', { transports: ['websocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'] }); socket.on('users', function(users) { console.log('users: ', users); }); socket.on('join', function(user) { console.log('joined: ', user); }); socket.on('leave', function(user) { console.log('left: ', user); }); socket.on('notice', function(notice) { alert(notice); }); socket.on('game_users', function(game, users) { var text = users.length > 0 ? 'Players: ' + users.join(', ') : ''; $('.game-' + game + ' .players').html(text); }); socket.on('game_end', function(game, results) { $('.game-' + game + ' .players').html(''); }); socket.emit('start'); $('.game form').each(function(i, form) { $(form).submit(function() { var game, amount, args = []; $.each($(form).serializeArray(), function(i, field) { switch (field.name) { case 'game': game = field.value; break; case 'amount': amount = field.value; break; default: args[args.length] = field.value; } }); socket.emit('bet', game, amount, args); return false; }); }); });
$(function() { socket = io.connect(':9000', { transports: ['websocket', 'htmlfile', 'xhr-multipart', 'xhr-polling', 'jsonp-polling'] }); socket.on('users', function(users) { console.log('users: ', users); }); socket.on('join', function(user) { console.log('joined: ', user); }); socket.on('leave', function(user) { console.log('left: ', user); }); socket.on('notice', function(notice) { alert(notice); }); socket.on('game_users', function(game, users) { var text = users.length > 0 ? 'Players: ' + users.join(', ') : ''; $('.game-' + game + ' .players').html(text); }); socket.on('game_end', function(game, results) { $('.game-' + game + ' .players').html(''); }); socket.on('roulette_landed_on', function(landed_on) { alert('Roulette landed on: ' + landed_on); }); socket.emit('start'); $('.game form').each(function(i, form) { $(form).submit(function() { var game, amount, args = []; $.each($(form).serializeArray(), function(i, field) { switch (field.name) { case 'game': game = field.value; break; case 'amount': amount = field.value; break; default: args[args.length] = field.value; } }); socket.emit('bet', game, amount, args); return false; }); }); });
Add a sitekey for localhost
import { h, render, Component } from 'preact'; import "preact/debug"; import ReCaptcha from '../src'; const sitekey = '6LfeHx4UAAAAAAKUx5rO5nfKMtc9-syDTdFLftnm'; let recaptchaInstance, recaptchaInvisibleInstance; const changeCallback = (response) => { console.log('onChange: ' + response); }; const expiredCallback = () => { console.log('onExpired'); }; const getResponse = () => { console.log(recaptchaInstance.getResponse()); }; const getInvisibleResponse = () => { recaptchaInvisibleInstance.execute(); }; class Example extends Component { render() { return ( <div> <h1>Google Recaptcha</h1> <ReCaptcha ref={e => recaptchaInstance = e} sitekey={sitekey} size="compact" render="explicit" onChange={changeCallback} onExpired={expiredCallback} /> <br /> <button onClick={getResponse}>Get response</button> <hr /> <ReCaptcha ref={e => recaptchaInvisibleInstance = e} sitekey={sitekey} size="invisible" render="explicit" onChange={changeCallback} onExpired={expiredCallback} /> <br /> <button onClick={getInvisibleResponse}>Get response from invisible captcha</button> </div>); } } render(<Example />, document.body);
import { h, render, Component } from 'preact'; import "preact/debug"; import ReCaptcha from '../src'; const sitekey = 'xxxxx'; let recaptchaInstance, recaptchaInvisibleInstance; const changeCallback = (response) => { console.log('onChange: ' + response); }; const expiredCallback = () => { console.log('onExpired'); }; const getResponse = () => { console.log(recaptchaInstance.getResponse()); }; const getInvisibleResponse = () => { recaptchaInvisibleInstance.execute(); }; class Example extends Component { render() { return ( <div> <h1>Google Recaptcha</h1> <ReCaptcha ref={e => recaptchaInstance = e} sitekey={sitekey} size="compact" render="explicit" onChange={changeCallback} onExpired={expiredCallback} /> <br /> <button onClick={getResponse}>Get response</button> <hr /> <ReCaptcha ref={e => recaptchaInvisibleInstance = e} sitekey={sitekey} size="invisible" render="explicit" onChange={changeCallback} onExpired={expiredCallback} /> <br /> <button onClick={getInvisibleResponse}>Get response from invisible captcha</button> </div>); } } render(<Example />, document.body);
Update category admin page copy.
@extends('app') @section('content') <div class="wrapper"> <div class="row"> <h1 class="highlighted">All Categories</h1> <p>These are all categories in the database. Each candidate may be in one category.</p> </div> <table> <thead> <tr> <td>Name</td> <td>Candidates</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </thead> @forelse($categories as $category) <tr> <td>{{ $category->name }}</td> <td>{{ $category->candidates->count() }} </td> <td><a href="{{ route('categories.show', [$category->slug]) }}">view</a></td> <td><a href="{{ route('categories.edit', [$category->slug]) }}">edit</a></td> </tr> @empty <tr> <td class="empty">No winners... yet!</td> <td></td> <td></td> <td></td> </tr> @endforelse </table> <div class="form-actions"> <a class="button" href="{{ route('categories.create') }}">New Category</a> </div> </div> @stop
@extends('app') @section('content') <div class="wrapper"> <div class="row"> <h1 class="highlighted">All Categories</h1> <p>These are all categories in the database. Categories will automatically show up in the site navigation above.</p> </div> <table> <thead> <tr> <td>Name</td> <td>Candidates</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </thead> @forelse($categories as $category) <tr> <td>{{ $category->name }}</td> <td>{{ $category->candidates->count() }} </td> <td><a href="{{ route('categories.show', [$category->slug]) }}">view</a></td> <td><a href="{{ route('categories.edit', [$category->slug]) }}">edit</a></td> </tr> @empty <tr> <td class="empty">No winners... yet!</td> <td></td> <td></td> <td></td> </tr> @endforelse </table> <div class="form-actions"> <a class="button" href="{{ route('categories.create') }}">New Category</a> </div> </div> @stop
Remove ipython from test deps as Travis is broken
from setuptools import setup NAME = "toxiproxy" VERSION = "0.1.0" DESCRIPTION = "Python library for Toxiproxy" LONG_DESCRIPTION = """\ A Python library for controlling Toxiproxy. Can be used in resiliency testing.""" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author="Douglas Soares de Andrade", author_email="[email protected]", url="https://github.com/douglas/toxiproxy-python", packages=["toxiproxy"], scripts=[], license="MIT License", install_requires=[ "future", "requests" ], test_suite="test", setup_requires=[ "pytest-runner", "pytest" ], tests_require=[ "pytest-sugar", "pytest", "profilehooks" ], platforms="Any", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Software Development", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Python Modules" ] )
from setuptools import setup NAME = "toxiproxy" VERSION = "0.1.0" DESCRIPTION = "Python library for Toxiproxy" LONG_DESCRIPTION = """\ A Python library for controlling Toxiproxy. Can be used in resiliency testing.""" setup( name=NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, author="Douglas Soares de Andrade", author_email="[email protected]", url="https://github.com/douglas/toxiproxy-python", packages=["toxiproxy"], scripts=[], license="MIT License", install_requires=[ "future", "requests" ], test_suite="test", setup_requires=[ "pytest-runner", "pytest" ], tests_require=[ "pytest-sugar", "pytest", "ipdb", "profilehooks" ], platforms="Any", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Topic :: Software Development", "Topic :: Software Development :: Libraries", "Topic :: Software Development :: Libraries :: Python Modules" ] )
Make ignore browser.js from jshint
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish'), ignores: 'browser.js' }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
'use strict'; module.exports = function (grunt) { // Show elapsed time at the end require('time-grunt')(grunt); // Load all grunt tasks require('load-grunt-tasks')(grunt); grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, gruntfile: { src: ['Gruntfile.js'] }, js: { src: ['*.js'] }, test: { src: ['test/**/*.js'] } }, mochacli: { options: { reporter: 'nyan', bail: true }, all: ['test/*.js'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, js: { files: '<%= jshint.js.src %>', tasks: ['jshint:js', 'mochacli'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'mochacli'] } } }); grunt.registerTask('default', ['jshint', 'mochacli']); };
Fix double-no clicking on participants
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', '[email protected]', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('member.id', this.get('member.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
import Ember from 'ember'; import { task } from 'ember-concurrency'; export default Ember.Component.extend({ store: Ember.inject.service(), flashMessages: Ember.inject.service(), isDisabled: false, isSelected: Ember.computed( 'member', '[email protected]', function(){ let mapped = this.get('participants').mapBy('member.id'); if (mapped.includes(this.get('member.id'))) { return true; } else { return false; } }), toggleParticipant: task(function* (property, value){ if (value) { let newParticipant = this.get('store').createRecord('participant', { member: this.get('member'), entry: this.get('model'), }); try { yield newParticipant.save(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); newParticipant.deleteRecord(); } } else { let participant = this.get('model.participants').findBy('contest.id', this.get('contest.id')); if (participant) { try { yield participant.destroyRecord(); this.get('flashMessages').success("Saved"); } catch(e) { e.errors.forEach((error) => { this.get('flashMessages').danger(error.detail); }); } } } }).restartable(), });
Fix checkprovider - parameters on service provider missing
<?php namespace Sympla\Auth\Laravel; use GuzzleHttp\Client as Guzzle; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use Sympla\Auth\Laravel\OAuthUserProvider; use Sympla\Auth\PasswordClient; class ServiceProvider extends BaseServiceProvider { public function boot() { $this->publishes([$this->configPath() => config_path('sympla.php')]); $auth = $this->app->make('auth'); $auth->provider('oauth', function ($app, array $config) { return new OAuthUserProvider( $app->make('sympla.oauth.password_client'), $config, $app->make('request') ); }); } public function register() { $this->mergeConfigFrom($this->configPath(), 'sympla'); $this->app->bind('sympla.oauth.password_client', function ($app) { $config = $app->config['sympla']['oauth']; return new PasswordClient( new Guzzle(), $config['client_id'], $config['client_secret'], $config['user_endpoint'], $config['token_endpoint'], $config['auth_method'], $config['client_provider'], $config['client_domain'], $config['client_service_account'] ); }); } protected function configPath() { return __DIR__ . '/../../config/sympla.php'; } }
<?php namespace Sympla\Auth\Laravel; use GuzzleHttp\Client as Guzzle; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use Sympla\Auth\Laravel\OAuthUserProvider; use Sympla\Auth\PasswordClient; class ServiceProvider extends BaseServiceProvider { public function boot() { $this->publishes([$this->configPath() => config_path('sympla.php')]); $auth = $this->app->make('auth'); $auth->provider('oauth', function ($app, array $config) { return new OAuthUserProvider( $app->make('sympla.oauth.password_client'), $config, $app->make('request') ); }); } public function register() { $this->mergeConfigFrom($this->configPath(), 'sympla'); $this->app->bind('sympla.oauth.password_client', function ($app) { $config = $app->config['sympla']['oauth']; return new PasswordClient( new Guzzle(), $config['client_id'], $config['client_secret'], $config['user_endpoint'], $config['token_endpoint'], $config['auth_method'] ); }); } protected function configPath() { return __DIR__ . '/../../config/sympla.php'; } }
Add more desktop browsers to list of browsers to test Currently don’t test mobile browsers as it looks like sauce are in the middle of restructuring how all the stuff works.
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ require('dotenv').config(); const testUrl = 'http://localhost:3000/tests.html'; module.exports = (grunt) => { const browsers = [ { browserName: 'safari', platform: 'macOS 10.12', }, { browserName: 'safari', platform: 'OS X 10.8', version: '6.0' }, { browserName: 'internet explorer', platform: 'Windows 7', version: '9.0' }, { browserName: 'internet explorer', platform: 'Windows 7', version: '11.0' }, { browserName: 'microsoftedge', platform: 'Windows 10' }, { browserName: 'googlechrome', platform: 'Windows 10' }, { browserName: 'firefox', platform: 'linux' }, ]; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { server: { options: { base: '', port: 9999 } } }, 'saucelabs-mocha': { all: { options: { urls: [ testUrl ], browsers, build: process.env.TRAVIS_JOB_ID, testname: 'js-set-functions mocha tests', throttled: 5, sauceConfig: { 'video-upload-on-pass': false } } } }, watch: {} }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-saucelabs'); grunt.registerTask('sauce', ['connect', 'saucelabs-mocha']); };
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ require('dotenv').config(); const testUrl = 'http://localhost:3000/tests.html'; module.exports = (grunt) => { const browsers = [ { browserName: 'googlechrome', platform: 'WIN10' }, { browserName: 'firefox', platform: 'linux' } ]; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { server: { options: { base: '', port: 9999 } } }, 'saucelabs-mocha': { all: { options: { urls: [ testUrl ], browsers, build: process.env.TRAVIS_JOB_ID, testname: 'mocha tests', throttled: 1, sauceConfig: { 'video-upload-on-pass': false } } } }, watch: {} }); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-saucelabs'); grunt.registerTask('sauce', ['connect', 'saucelabs-mocha']); };
Fix FileSystem class due to symfony update
<?php namespace Ivory\GoogleMapBundle\Tests\Emulation; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\Filesystem\Filesystem; /** * Web test case * * @author GeLo <[email protected]> */ class WebTestCase extends BaseWebTestCase { /** * @var boolean TRUE if the web test case has been initialized else FALSE */ protected static $initialize = array(); /** * Remove emulation cache & logs directories for the given environment * * @param string $environment */ protected static function initialize($environment) { if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment])) { $filesystem = new Filesystem(); $filesystem->remove(__DIR__.'/cache/'.$environment); if(empty(self::$initialize)) $filesystem->remove(__DIR__.'/logs'); self::$initialize[$environment] = true; } } /** *@override */ protected static function getKernelClass() { $kernelClass = 'AppKernel'; require_once __DIR__.'/'.$kernelClass.'.php'; return $kernelClass; } /** * Gets the kernel container * * @return Symfony\Component\DependencyInjection\ContainerInterface */ public static function createContainer(array $options = array('environment' => 'default')) { self::initialize($options['environment']); $kernel = self::createKernel($options); $kernel->boot(); return $kernel->getContainer(); } }
<?php namespace Ivory\GoogleMapBundle\Tests\Emulation; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase; use Symfony\Component\HttpKernel\Util\Filesystem; /** * Web test case * * @author GeLo <[email protected]> */ class WebTestCase extends BaseWebTestCase { /** * @var boolean TRUE if the web test case has been initialized else FALSE */ protected static $initialize = array(); /** * Remove emulation cache & logs directories for the given environment * * @param string $environment */ protected static function initialize($environment) { if(!isset(self::$initialize[$environment]) || (isset(self::$initialize[$environment]) && !self::$initialize[$environment])) { $filesystem = new Filesystem(); $filesystem->remove(__DIR__.'/cache/'.$environment); if(empty(self::$initialize)) $filesystem->remove(__DIR__.'/logs'); self::$initialize[$environment] = true; } } /** *@override */ protected static function getKernelClass() { $kernelClass = 'AppKernel'; require_once __DIR__.'/'.$kernelClass.'.php'; return $kernelClass; } /** * Gets the kernel container * * @return Symfony\Component\DependencyInjection\ContainerInterface */ public static function createContainer(array $options = array('environment' => 'default')) { self::initialize($options['environment']); $kernel = self::createKernel($options); $kernel->boot(); return $kernel->getContainer(); } }
Add test response to frequency
from braces.views import CsrfExemptMixin from django.core.mail import send_mail from django.http import HttpResponse from django.views.generic import TemplateView, View from clowder_server.models import Alert, Ping class APIView(CsrfExemptMixin, View): def post(self, request): name = request.POST.get('name') frequency = request.POST.get('frequency') value = request.POST.get('value') status = int(request.POST.get('status', 1)) if status == -1: send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False) if frequency: expiration_date = datetime.datetime.now() + int(frequency) Alert.objects.filter(name=name).delete() Alert.objects.create( name=name, expire_at=expiration_date ) return HttpResponse('test') Ping.objects.create( name=name, value=value, ) return HttpResponse('ok') class DashboardView(TemplateView): template_name = "dashboard.html" def get_context_data(self, **context): context['pings'] = Ping.objects.all().order_by('name', 'create') return context
from braces.views import CsrfExemptMixin from django.core.mail import send_mail from django.http import HttpResponse from django.views.generic import TemplateView, View from clowder_server.models import Alert, Ping class APIView(CsrfExemptMixin, View): def post(self, request): name = request.POST.get('name') frequency = request.POST.get('frequency') value = request.POST.get('value') status = int(request.POST.get('status', 1)) if status == -1: send_mail('Subject here', 'Here is the message.', '[email protected]', ['[email protected]'], fail_silently=False) if frequency: expiration_date = datetime.datetime.now() + int(frequency) Alert.objects.filter(name=name).delete() Alert.objects.create( name=name, expire_at=expiration_date ) Ping.objects.create( name=name, value=value, ) return HttpResponse('ok') class DashboardView(TemplateView): template_name = "dashboard.html" def get_context_data(self, **context): context['pings'] = Ping.objects.all().order_by('name', 'create') return context
Set optimization runs to 200
const HDWalletProvider = require("truffle-hdwallet-provider"); const privateKey = "<PRIVATE>"; module.exports = { networks: { testing: { host: '127.0.0.1', port: 10545, network_id: 420123 }, development: { host: '127.0.0.1', port: 9545, network_id: 420123 }, kovan: { provider: new HDWalletProvider(privateKey, "https://kovan.infura.io/v3/<API_KEY>"), network_id: 42, skipDryRun: true }, mainnet: { provider: new HDWalletProvider(privateKey, "https://mainnet.infura.io/v3/<API_KEY>"), network_id: 1, gasPrice: 10000000000, skipDryRun: true } }, compilers: { solc: { version: "0.4.25", optimizer: { enabled: true, runs: 200 } } }, mocha: { reporter: 'eth-gas-reporter', reporterOptions: { currency: 'USD', gasPrice: 10 } } };
const HDWalletProvider = require("truffle-hdwallet-provider"); const privateKey = "<PRIVATE>"; module.exports = { networks: { testing: { host: '127.0.0.1', port: 10545, network_id: 420123 }, development: { host: '127.0.0.1', port: 9545, network_id: 420123 }, kovan: { provider: new HDWalletProvider(privateKey, "https://kovan.infura.io/v3/<API_KEY>"), network_id: 42, skipDryRun: true }, mainnet: { provider: new HDWalletProvider(privateKey, "https://mainnet.infura.io/v3/<API_KEY>"), network_id: 1, gasPrice: 10000000000, skipDryRun: true } }, compilers: { solc: { version: "0.4.25", optimizer: { enabled: true, runs: 1000 } } }, mocha: { reporter: 'eth-gas-reporter', reporterOptions: { currency: 'USD', gasPrice: 10 } } };
Update local config cache settings.
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', true); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values are: file, memcached and apc // c::set('cache.options', array('prefix' => 'altair_')); // Prefix memcached keys (prevent collision of caches when pages are named the same, acros sites in a multisite environment) /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') c::set('thumbs.bin', '/usr/local/bin/convert'); // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('google.analytics', false);
<?php // direct access protection if(!defined('KIRBY')) die('Direct access is not allowed'); /* ----------------------------------------------------------------------------- Troubleshooting -------------------------------------------------------------------------------- */ c::set('troubleshoot', false); /* ----------------------------------------------------------------------------- Debug -------------------------------------------------------------------------------- */ c::set('debug', true); /* ----------------------------------------------------------------------------- Environment -------------------------------------------------------------------------------- */ c::set('environment', 'local'); /* ----------------------------------------------------------------------------- URL -------------------------------------------------------------------------------- */ c::set('url', ''); // To use root relative URLs: c::set('url', '/'); /* ----------------------------------------------------------------------------- Timezone -------------------------------------------------------------------------------- */ c::set('timezone', 'UTC'); /* ----------------------------------------------------------------------------- Cache -------------------------------------------------------------------------------- */ c::set('cache', false); c::set('cache.driver', 'file'); // Valid values: file, memcached or apc /* ----------------------------------------------------------------------------- Thumbs -------------------------------------------------------------------------------- */ c::set('thumbs.driver','im'); // The thumbnail library which is being used by Kirby's thumb function/class ('gd' or 'im') c::set('thumbs.bin', '/usr/local/bin/convert'); // Path to the convert bin for 'im' thumb driver setting (see: http://j.mp/1LJ8n9E) /* ----------------------------------------------------------------------------- Analytics, tracking, site stats -------------------------------------------------------------------------------- */ c::set('google.analytics', false);
Use format=5 in YT search to prevent "embedding disabled"
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.format = '5' query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search("\b(concert|cover)\b", title): return False return True
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search("\b(concert|cover)\b", title): return False return True
Add example for when there is no book cover url
import os, os.path import random import string import json import cherrypy from . import get_pic class StringGenerator(object): @cherrypy.expose def index(self): return """<html> <head> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> wrong page </body> </html>""" @cherrypy.expose def get_picture(self, url=""): return get_pic.base64_picture(url) @cherrypy.expose def search(self, query): return json.dumps({"book": {"title":"Gs", "author":"Bash Gs", "url":"https://chitanka.info/text/1"}, "recommended":[{"title":"Gs1", "author":"Bash Gs1", "url":"https://chitanka.info/text/2"}, {"title":"Gs2", "author":"Bash Gs2", "url":None}]}) @cherrypy.expose def display(self): return cherrypy.session['mystring'] def main(): conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join( os.path.abspath(os.path.dirname(os.path.realpath(__file__))), 'web' ) }, } cherrypy.quickstart(StringGenerator(), '/', conf) if __name__ == '__main__': main()
import os, os.path import random import string import json import cherrypy from . import get_pic class StringGenerator(object): @cherrypy.expose def index(self): return """<html> <head> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> wrong page </body> </html>""" @cherrypy.expose def get_picture(self, url=""): return get_pic.base64_picture(url) @cherrypy.expose def search(self, query): return json.dumps({"book": {"title":"Gs", "author":"Bash Gs", "url":"https://chitanka.info/text/1"}, "recommended":[{"title":"Gs1", "author":"Bash Gs1", "url":"https://chitanka.info/text/2"}, {"title":"Gs2", "author":"Bash Gs2", "url":"https://chitanka.info/text/3"}]}) @cherrypy.expose def display(self): return cherrypy.session['mystring'] def main(): conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join( os.path.abspath(os.path.dirname(os.path.realpath(__file__))), 'web' ) }, } cherrypy.quickstart(StringGenerator(), '/', conf) if __name__ == '__main__': main()
Change path of sysctl to /sbin for ubuntu on azure
import subprocess import uuid def test_if_default_systctls_are_set(dcos_api_session): """This test verifies that default sysctls are set for tasks. We use a `mesos-execute` to check for the values to make sure any task from any framework would be affected by default. The job then examines the default sysctls, and returns a failure if another value is found.""" test_command = ('test "$(/sbin/sysctl vm.swappiness)" = ' '"vm.swappiness = 1"' ' && test "$(/sbin/sysctl vm.max_map_count)" = ' '"vm.max_map_count = 262144"') argv = [ '/opt/mesosphere/bin/mesos-execute', '--master=leader.mesos:5050', '--command={}'.format(test_command), '--shell=true', '--env={"LC_ALL":"C"}'] def run_and_check(argv): name = 'test-sysctl-{}'.format(uuid.uuid4().hex) output = subprocess.check_output( argv + ['--name={}'.format(name)], stderr=subprocess.STDOUT, universal_newlines=True) expected_output = \ "Received status update TASK_FINISHED for task '{name}'".format( name=name) assert expected_output in output run_and_check(argv) run_and_check(argv + ['--role=slave_public'])
import subprocess import uuid def test_if_default_systctls_are_set(dcos_api_session): """This test verifies that default sysctls are set for tasks. We use a `mesos-execute` to check for the values to make sure any task from any framework would be affected by default. The job then examines the default sysctls, and returns a failure if another value is found.""" test_command = ('test "$(/usr/sbin/sysctl vm.swappiness)" = ' '"vm.swappiness = 1"' ' && test "$(/usr/sbin/sysctl vm.max_map_count)" = ' '"vm.max_map_count = 262144"') argv = [ '/opt/mesosphere/bin/mesos-execute', '--master=leader.mesos:5050', '--command={}'.format(test_command), '--shell=true', '--env={"LC_ALL":"C"}'] def run_and_check(argv): name = 'test-sysctl-{}'.format(uuid.uuid4().hex) output = subprocess.check_output( argv + ['--name={}'.format(name)], stderr=subprocess.STDOUT, universal_newlines=True) expected_output = \ "Received status update TASK_FINISHED for task '{name}'".format( name=name) assert expected_output in output run_and_check(argv) run_and_check(argv + ['--role=slave_public'])
Fix issue with styling on error pages Using the correct path_to_root now in ErrorCreator.
<?php /** * Met deze PHP class kunnen pagina's voor de custom error pages gemaakt worden. */ class ErrorCreator { /** * De titel van de test. */ var $title; /** * De error code. */ var $code; /** * Het bericht dat moet worden weergegeven als error message. */ var $message; /** * Print de testpagina op de website. Gebruikt de variabelen uit deze * TestCreator instance. */ function create() { // '../' omdat deze class altijd aangeroepen wordt vanuit de /error/ map. require_once '../resources/includes/PageCreator.php'; $page = new PageCreator; $page->path_to_root = "../"; $page->title = $this->title; $page->body = <<<CONTENT <section class="water"> <div class="content"> <div class="row"> <div class="medium-10 medium-centered columns"> <div class="medium-9 columns medium-offset-3"> <h1>Error $this->code</h1> <p> Beste bezoeker, <br><br> $this->message <br> Onze excuses voor het ongemak. </p> </div> </div> </div> </div> </section> CONTENT; $page->create(); } }
<?php /** * Met deze PHP class kunnen pagina's voor de custom error pages gemaakt worden. */ class ErrorCreator { /** * De titel van de test. */ var $title; /** * De error code. */ var $code; /** * Het bericht dat moet worden weergegeven als error message. */ var $message; /** * Print de testpagina op de website. Gebruikt de variabelen uit deze * TestCreator instance. */ function create() { // '../' omdat deze class altijd aangeroepen wordt vanuit de /error/ map. require_once '../resources/includes/PageCreator.php'; $page = new PageCreator; $page->title = $this->title; $page->body = <<<CONTENT <section class="water"> <div class="content"> <div class="row"> <div class="medium-10 medium-centered columns"> <div class="medium-9 columns medium-offset-3"> <h1>Error $this->code</h1> <p> Beste bezoeker, <br><br> $this->message <br> Onze excuses voor het ongemak. </p> </div> </div> </div> </div> </section> CONTENT; $page->create(); } }
Fix deletion of non empty temp directory
const axios = require('axios'); const fs = require('fs'); const path = require('path'); const tmp = require('tmp'); tmp.setGracefulCleanup(); function getTempDir() { return new Promise((resolve, reject) => { tmp.dir({unsafeCleanup: true}, (error, dirPath) => { if (error) { reject(error); return; } resolve(dirPath); }); }); } function saveToFile(data) { return getTempDir() .then(dirPath => { return new Promise(function(resolve, reject) { const saveDir = path.join(dirPath, 'someicon.ico'); fs.writeFile(saveDir, data, function (error) { if (error) { reject(error); return; } resolve(saveDir); }); }); }); } function downloadIcon(iconUrl) { const iconData = new Promise(function (resolve, reject) { axios.get(iconUrl, {responseType: 'arraybuffer'}) .then(function(response) { resolve(response.data); }) .catch(function(error) { reject(error); }) }); return iconData.then(saveToFile); } function downloadIcons(iconUrls) { const promises = iconUrls.map(downloadIcon); return Promise.all(promises); } module.exports = downloadIcons;
const axios = require('axios'); const fs = require('fs'); const path = require('path'); const tmp = require('tmp'); tmp.setGracefulCleanup(); function getTempDir() { return new Promise((resolve, reject) => { tmp.dir((error, dirPath) => { if (error) { reject(error); return; } resolve(dirPath); }); }); } function saveToFile(data) { return getTempDir() .then(dirPath => { return new Promise(function(resolve, reject) { const saveDir = path.join(dirPath, 'someicon.ico'); fs.writeFile(saveDir, data, function (error) { if (error) { reject(error); return; } resolve(saveDir); }); }); }); } function downloadIcon(iconUrl) { const iconData = new Promise(function (resolve, reject) { axios.get(iconUrl, {responseType: 'arraybuffer'}) .then(function(response) { resolve(response.data); }) .catch(function(error) { reject(error); }) }); return iconData.then(saveToFile); } function downloadIcons(iconUrls) { const promises = iconUrls.map(downloadIcon); return Promise.all(promises); } module.exports = downloadIcons;
Allow profile page for bot
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\User; use App\Exceptions\UserProfilePageLookupException; use App\Models\User; class FindForProfilePage { public static function find($id, ?string $type = null, ?bool $assertCanonicalId = null) { $user = User::lookupWithHistory($id, $type, true); $request = request(); if ($user === null || !priv_check('UserShow', $user)->can()) { throw new UserProfilePageLookupException(function () { if (is_json_request()) { abort(404); } return ext_view('users.show_not_found', null, null, 404); }); } if (($assertCanonicalId ?? !is_json_request()) && (string) $user->getKey() !== (string) $id) { $redirectTarget = route( $request->route()->getName(), array_merge($request->query(), $request->route()->parameters(), compact('user')) ); throw new UserProfilePageLookupException(fn () => ujs_redirect($redirectTarget)); } return $user; } }
<?php // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. namespace App\Libraries\User; use App\Exceptions\UserProfilePageLookupException; use App\Models\User; class FindForProfilePage { public static function find($id, ?string $type = null, ?bool $assertCanonicalId = null) { $user = User::lookupWithHistory($id, $type, true); $request = request(); if ($user === null || $user->isBot() || !priv_check('UserShow', $user)->can()) { throw new UserProfilePageLookupException(function () { if (is_json_request()) { abort(404); } return ext_view('users.show_not_found', null, null, 404); }); } if (($assertCanonicalId ?? !is_json_request()) && (string) $user->getKey() !== (string) $id) { $redirectTarget = route( $request->route()->getName(), array_merge($request->query(), $request->route()->parameters(), compact('user')) ); throw new UserProfilePageLookupException(fn () => ujs_redirect($redirectTarget)); } return $user; } }
Comment out part done code
""" Tests for helper function for updating a target from a Vuforia database. """ import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ # target_id = client.add_target( # name='x', # width=1, # image=high_quality_image, # ) # # client.update_target(target_id=target_id) # result = client.get_target(target_id=target_id) # expected_keys = { # 'target_id', # 'active_flag', # 'name', # 'width', # 'tracking_rating', # 'reco_rating', # } # assert result['target_record'].keys() == expected_keys # # def test_no_such_target( # self, # client: VWS, # high_quality_image: io.BytesIO, # ) -> None: # """ # An ``UnknownTarget`` exception is raised when getting a target which # does not exist. # """ # with pytest.raises(UnknownTarget): # client.get_target(target_id='a')
""" Tests for helper function for updating a target from a Vuforia database. """ import io import pytest from vws import VWS from vws.exceptions import UnknownTarget class TestUpdateTarget: """ Test for updating a target. """ def test_get_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ Details of a target are returned by ``get_target``. """ target_id = client.add_target( name='x', width=1, image=high_quality_image, ) client.update_target(target_id=target_id) result = client.get_target(target_id=target_id) expected_keys = { 'target_id', 'active_flag', 'name', 'width', 'tracking_rating', 'reco_rating', } assert result['target_record'].keys() == expected_keys def test_no_such_target( self, client: VWS, high_quality_image: io.BytesIO, ) -> None: """ An ``UnknownTarget`` exception is raised when getting a target which does not exist. """ with pytest.raises(UnknownTarget): client.get_target(target_id='a')
Refresh the grid every 20 seconds.
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 20 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
from django.core import serializers from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect, render_to_response from django.template import RequestContext from django.template.loader import get_template import json from models import Game, Week def index(request): ben_teams = [] brian_teams = [] wk = Week.objects.latest() for game in wk.game_set.all(): picked = game.picked_team other = game.away_team if game.home_team == picked else game.home_team if game.picker == "BEN": ben_teams.append(picked) brian_teams.append(other) else: brian_teams.append(picked) ben_teams.append(other) interval = 1 * 60 * 1000 return render_to_response('grid/index.html', {'ben_teams': json.dumps(ben_teams), 'brian_teams': json.dumps(brian_teams), 'interval': interval }, context_instance=RequestContext(request)) def scores(request): wk = Week.objects.latest() games = wk.game_set.all() ret = serializers.serialize('json', games) return HttpResponse(ret, "application/javascript")
Add still_running to build result serializer
from rest_framework import serializers from frigg.projects.models import Project from .models import Build, BuildResult class ProjectInlineSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', ) class BuildResultSerializer(serializers.ModelSerializer): class Meta: model = BuildResult fields = ( 'id', 'coverage', 'succeeded', 'tasks', 'setup_tasks', 'still_running', ) class BuildInlineSerializer(serializers.ModelSerializer): result = BuildResultSerializer(read_only=True) class Meta: model = Build fields = ( 'id', 'build_number', 'branch', 'sha', 'pull_request_id', 'start_time', 'end_time', 'result', 'short_message', 'message', 'color', 'pull_request_url', 'commit_url', ) class BuildSerializer(serializers.ModelSerializer): project = ProjectInlineSerializer(read_only=True) result = BuildResultSerializer(read_only=True) class Meta: model = Build fields = ( 'id', 'project', 'result', 'build_number', 'branch', 'pull_request_id', 'sha', 'start_time', 'end_time', 'short_message', 'message', 'color', 'pull_request_url', 'commit_url', )
from rest_framework import serializers from frigg.projects.models import Project from .models import Build, BuildResult class ProjectInlineSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', ) class BuildResultSerializer(serializers.ModelSerializer): class Meta: model = BuildResult fields = ( 'id', 'coverage', 'succeeded', 'tasks', 'setup_tasks', ) class BuildInlineSerializer(serializers.ModelSerializer): result = BuildResultSerializer(read_only=True) class Meta: model = Build fields = ( 'id', 'build_number', 'branch', 'sha', 'pull_request_id', 'start_time', 'end_time', 'result', 'short_message', 'message', 'color', 'pull_request_url', 'commit_url', ) class BuildSerializer(serializers.ModelSerializer): project = ProjectInlineSerializer(read_only=True) result = BuildResultSerializer(read_only=True) class Meta: model = Build fields = ( 'id', 'project', 'result', 'build_number', 'branch', 'pull_request_id', 'sha', 'start_time', 'end_time', 'short_message', 'message', 'color', 'pull_request_url', 'commit_url', )
Add ability to pass explicit arguments to LaunchControlDispatcher
""" Module with LaunchControlDispatcher - the command dispatcher """ import argparse from .interface import Command class LaunchControlDispatcher(object): """ Class implementing command line interface for launch control """ def __init__(self): self.parser = argparse.ArgumentParser( description=""" Command line tool for interacting with Launch Control """, epilog=""" Please report all bugs using the Launchpad bug tracker: http://bugs.launchpad.net/launch-control/+filebug """, add_help=False) self.subparsers = self.parser.add_subparsers(title="Sub-command to invoke") for command_cls in Command.get_subclasses(): sub_parser = self.subparsers.add_parser( command_cls.get_name(), help=command_cls.get_help()) sub_parser.set_defaults(command_cls=command_cls) command_cls.register_arguments(sub_parser) def dispatch(self, args=None): args = self.parser.parse_args(args) command = args.command_cls(self.parser, args) command.invoke(args) def main(): LaunchControlDispatcher().dispatch()
""" Module with LaunchControlDispatcher - the command dispatcher """ import argparse from .interface import Command class LaunchControlDispatcher(object): """ Class implementing command line interface for launch control """ def __init__(self): self.parser = argparse.ArgumentParser( description=""" Command line tool for interacting with Launch Control """, epilog=""" Please report all bugs using the Launchpad bug tracker: http://bugs.launchpad.net/launch-control/+filebug """, add_help=False) self.subparsers = self.parser.add_subparsers(title="Sub-command to invoke") for command_cls in Command.get_subclasses(): sub_parser = self.subparsers.add_parser( command_cls.get_name(), help=command_cls.get_help()) sub_parser.set_defaults(command_cls=command_cls) command_cls.register_arguments(sub_parser) def dispatch(self): args = self.parser.parse_args() command = args.command_cls(self.parser, args) command.invoke(args) def main(): LaunchControlDispatcher().dispatch()
Add accounts page to admin v1
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module("eappApp").controller("UserAccountsController", function($scope, eapp) { $scope.type = "company"; $scope.query = { filter: '', limit: '100', order: 'name', page: 1 }; $scope.$watch("query.page", function(newValue, oldValue) { window.scrollTo(0, 0); }); $scope.getAccounts = function() { $scope.promise = eapp.getCompanyAccounts($scope.query); $scope.promise.then(function(response) { var data = response.data.accounts; $scope.count = response.data.count; $scope.accounts = Object.keys(data).map(i => data[i]); if($scope.accounts.length > 0) { $scope.headers = Object.keys($scope.accounts[0]); } }); }; angular.element(document).ready(function() { $scope.getAccounts(); }); });
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module("eappApp").controller("UserAccountsController", function($scope, eapp) { $scope.query = { filter: '', limit: '100', order: 'name', page: 1 }; $scope.$watch("query.page", function(newValue, oldValue) { window.scrollTo(0, 0); }); $scope.getAccounts = function(type) { $scope.type = type || $scope.type || "company"; $scope.promise = eapp.getCompanyAccounts($scope.query); $scope.promise.then(function(response) { var data = response.data.accounts; $scope.count = response.data.count; $scope.accounts = Object.keys(data).map(i => data[i]); if($scope.accounts.length > 0) { $scope.headers = Object.keys($scope.accounts[0]); } }); }; angular.element(document).ready(function() { $scope.getAccounts("company"); }); });
Fix section label issue in settings
package com.omralcorut.guardiannews; import android.content.SharedPreferences; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); } public static class NewsPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings_main); Preference section = findPreference(getString(R.string.settings_section_key)); bindPreferenceSummaryToValue(section); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String stringValue = newValue.toString(); preference.setSummary(getLabelGivenValue(stringValue)); return true; } private void bindPreferenceSummaryToValue(Preference preference) { preference.setOnPreferenceChangeListener(this); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext()); String preferenceString = preferences.getString(preference.getKey(), ""); onPreferenceChange(preference, preferenceString); } private String getLabelGivenValue(String value) { String result = "All Sections"; String values[] = getResources().getStringArray(R.array.settings_section_values); for (int i = 0; i < values.length; i++) { if (value.equals(values[i])) { result = getResources().getStringArray(R.array.settings_section_labels)[i]; } } return result; } } }
package com.omralcorut.guardiannews; import android.content.SharedPreferences; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); } public static class NewsPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings_main); Preference section = findPreference(getString(R.string.settings_section_key)); bindPreferenceSummaryToValue(section); } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String stringValue = newValue.toString(); preference.setSummary(stringValue); return true; } private void bindPreferenceSummaryToValue(Preference preference) { preference.setOnPreferenceChangeListener(this); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext()); String preferenceString = preferences.getString(preference.getKey(), ""); onPreferenceChange(preference, preferenceString); } } }
Fix issue with cascading loads
$(document).on('ajaxComplete ready', function () { // Initialize date pickers $('input[data-provides="anomaly.field_type.datetime"][name$="[date]"]:not([data-initialized])').each(function () { var input = $(this); input.prev('.icon').click(function () { input.focus(); }); input .attr('data-initialized', '') .datepicker({ dateFormat: $(this).data('date-format'), yearRange: $(this).data('year-range'), minDate: $(this).data('min'), maxDate: $(this).data('max'), selectOtherMonths: true, showOtherMonths: true, changeMonth: true, changeYear: true }); }); // Initialize time pickers $('input[data-provides="anomaly.field_type.datetime"][name$="[time]"]:not([data-initialized])').each(function () { var input = $(this); input.prev('.icon').click(function () { input.focus(); }); input .attr('data-initialized', '') .timepicker({ timeFormat: $(this).data('time-format'), step: $(this).data('step'), scrollDefault: 'now' }); }); });
$(function () { // Initialize date pickers $('input[data-provides="anomaly.field_type.datetime"][name$="[date]"]:not([data-initialized])').each(function () { var input = $(this); input.prev('.icon').click(function () { input.focus(); }); input .attr('data-initialized', '') .datepicker({ dateFormat: $(this).data('date-format'), yearRange: $(this).data('year-range'), minDate: $(this).data('min'), maxDate: $(this).data('max'), selectOtherMonths: true, showOtherMonths: true, changeMonth: true, changeYear: true }); }); // Initialize time pickers $('input[data-provides="anomaly.field_type.datetime"][name$="[time]"]:not([data-initialized])').each(function () { var input = $(this); input.prev('.icon').click(function () { input.focus(); }); input .attr('data-initialized', '') .timepicker({ timeFormat: $(this).data('time-format'), step: $(this).data('step'), scrollDefault: 'now' }); }); });
Fix constructor shared between components
import pluck from './pluck'; import { noop, mixin, observable, insertCss, emptyTemplate, computedAll, pureComputedAll } from '../util/'; const modulePolyfill = { defaults: {}, template: emptyTemplate }; // Transform transiton component module to native component module // // @param {Object} module Transiton component module // @return {Object} Native component module function transform(module) { const { name, constructor, defaults, props, mixins, methods, computed, pureComputed, style, template } = Object.assign({ constructor: function() {} }, modulePolyfill, module); insertCss(module.style); Object.assign(constructor.prototype, methods); return { viewModel: { createViewModel(params, componentInfo) { componentInfo.name = name; const opts = Object.assign( {}, defaults, ko.toJS(params), pluck(componentInfo.element) ); const vm = new constructor(opts, componentInfo); props && Object.assign(vm, observable(opts, props)); mixins && mixin(vm, opts, mixins); computed && computedAll(vm, computed); pureComputed && pureComputedAll(vm, pureComputed); vm.$opts = opts; vm.$defaults = defaults; vm.$info = vm.componentInfo = componentInfo; delete vm.$opts['$raw']; delete vm.$defaults['$raw']; return vm; } }, synchronous: true, template }; } export default transform;
import pluck from './pluck'; import { noop, mixin, observable, insertCss, emptyTemplate, computedAll, pureComputedAll } from '../util/'; const modulePolyfill = { constructor: noop, defaults: {}, template: emptyTemplate }; // Transform transiton component module to native component module // // @param {Object} module Transiton component module // @return {Object} Native component module function transform(module) { const { name, constructor, defaults, props, mixins, methods, computed, pureComputed, style, template } = Object.assign({}, modulePolyfill, module); insertCss(module.style); Object.assign(constructor.prototype, methods); return { viewModel: { createViewModel(params, componentInfo) { componentInfo.name = name; const opts = Object.assign( {}, defaults, ko.toJS(params), pluck(componentInfo.element) ); const vm = new constructor(opts, componentInfo); props && Object.assign(vm, observable(opts, props)); mixins && mixin(vm, opts, mixins); computed && computedAll(vm, computed); pureComputed && pureComputedAll(vm, pureComputed); vm.$opts = opts; vm.$defaults = defaults; vm.$info = vm.componentInfo = componentInfo; delete vm.$opts['$raw']; delete vm.$defaults['$raw']; return vm; } }, synchronous: true, template }; } export default transform;
fix: Fix Python3 error when decoding the response.
try: from urllib.request import urlopen, Request from urllib.error import HTTPError except ImportError: from urllib2 import urlopen, Request, HTTPError import json class PasteryUploader(): def __init__(self, api_key): """ Initialize an Uploader instance with the given API key. """ self.api_key = api_key def upload(self, body, title="", language=None, duration=None, max_views=0): """ Upload the given body with the specified language type. """ url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key if title: url += "&title=%s" % title if language: url += "&language=%s" % language if duration: url += "&duration=%s" % duration if max_views: url += "&max_views=%s" % max_views body = bytes(body.encode("utf8")) req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'}) try: response = urlopen(req) except HTTPError as e: response = json.loads(e.read().decode("utf8")) raise RuntimeError(response["error_msg"]) response = json.loads(response.read().decode("utf8")) return response["url"]
try: from urllib.request import urlopen, Request, HTTPError except ImportError: from urllib2 import urlopen, Request, HTTPError import json class PasteryUploader(): def __init__(self, api_key): """ Initialize an Uploader instance with the given API key. """ self.api_key = api_key def upload(self, body, title="", language=None, duration=None, max_views=0): """ Upload the given body with the specified language type. """ url = "https://www.pastery.net/api/paste/?api_key=%s" % self.api_key if title: url += "&title=%s" % title if language: url += "&language=%s" % language if duration: url += "&duration=%s" % duration if max_views: url += "&max_views=%s" % max_views body = bytes(body.encode("utf8")) req = Request(url, data=body, headers={'User-Agent': u'Mozilla/5.0 (Python) bakeit library'}) try: response = urlopen(req) except HTTPError as e: response = json.loads(e.read()) raise RuntimeError(response["error_msg"]) response = json.loads(response.read().decode("utf8")) return response["url"]
Update permission names when syncing
from django.contrib.auth.models import Permission from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Create admin permissions" def handle(self, *args, **options): if args: # pragma: no cover raise CommandError("Command doesn't accept any arguments") return self.handle_noargs(**options) def handle_noargs(self, *args, **options): from bananas import admin from django.contrib import admin as django_admin from django.contrib.contenttypes.models import ContentType django_admin.autodiscover() for model, _ in admin.site._registry.items(): if issubclass(getattr(model, "View", object), admin.AdminView): meta = model._meta ct, created = ContentType.objects.get_or_create( app_label=meta.app_label, model=meta.object_name.lower() ) if created: print("Found new admin view: {} [{}]".format(ct.name, ct.app_label)) for codename, name in model._meta.permissions: p, created = Permission.objects.update_or_create( codename=codename, content_type=ct, defaults=dict(name=name) ) if created: print("Created permission: {}".format(name))
from django.contrib.auth.models import Permission from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Create admin permissions" def handle(self, *args, **options): if args: # pragma: no cover raise CommandError("Command doesn't accept any arguments") return self.handle_noargs(**options) def handle_noargs(self, *args, **options): from bananas import admin from django.contrib import admin as django_admin from django.contrib.contenttypes.models import ContentType django_admin.autodiscover() for model, _ in admin.site._registry.items(): if issubclass(getattr(model, "View", object), admin.AdminView): meta = model._meta ct, created = ContentType.objects.get_or_create( app_label=meta.app_label, model=meta.object_name.lower() ) if created: print("Found new admin view: {} [{}]".format(ct.name, ct.app_label)) for codename, name in model._meta.permissions: p, created = Permission.objects.get_or_create( codename=codename, name=name, content_type=ct ) if created: print("Created permission: {}".format(name))
Use the new reset-password endpoint
'use strict'; const AccountManager = require('../account-manager'); const {handleResponseData, parseSetCookies, findCookie} = require('../utils'); const BaseStep = require('./base-step'); module.exports = class Login extends BaseStep { start({account: {email}} = {}, install) { this.install = install; return new Promise((resolve, reject) => { this.subscriptions.add(install.on('did-submit-credentials', () => resolve(this.onSubmit()))); this.subscriptions.add(install.on('did-forgot-password', () => { AccountManager.resetPassword({email}).then(resp => { if (resp.statusCode === 200) { atom.notifications.addSuccess( `Instructions on how to reset your password should have been sent to ${email}`); } return; }); })); }); } onSubmit() { const data = this.view.data; this.install.updateState({error: null}); return AccountManager.login(data) .then(resp => Promise.all([ Promise.resolve(resp.statusCode), handleResponseData(resp), Promise.resolve(parseSetCookies(resp.headers['set-cookie'])), ])) .then(([status, raw, cookies]) => { switch (status) { case 200: return { account: { sessionId: findCookie(cookies, 'kite-session').Value, }, }; case 500: throw new Error('Server error during log in'); default: throw new Error(`Unable to login: ${JSON.parse(raw).message}`); } }); } };
'use strict'; const opn = require('opn'); const AccountManager = require('../account-manager'); const {handleResponseData, parseSetCookies, findCookie} = require('../utils'); const BaseStep = require('./base-step'); module.exports = class Login extends BaseStep { start({account: {email}} = {}, install) { this.install = install; return new Promise((resolve, reject) => { this.subscriptions.add(install.on('did-submit-credentials', () => resolve(this.onSubmit()))); this.subscriptions.add(install.on('did-forgot-password', () => { opn(`https://alpha.kite.com/account/resetPassword/request?email=${email}`); })); }); } onSubmit() { const data = this.view.data; this.install.updateState({error: null}); return AccountManager.login(data) .then(resp => Promise.all([ Promise.resolve(resp.statusCode), handleResponseData(resp), Promise.resolve(parseSetCookies(resp.headers['set-cookie'])), ])) .then(([status, raw, cookies]) => { switch (status) { case 200: return { account: { sessionId: findCookie(cookies, 'kite-session').Value, }, }; case 500: throw new Error('Server error during log in'); default: throw new Error(`Unable to login: ${JSON.parse(raw).message}`); } }); } };
Use pgpkeys.mit.edu as our keyserver; seems to work.
import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key @celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: check_output2(( 'gpg', '--homedir', homedir, '--keyserver', 'pgpkeys.mit.edu', '--recv-keys', uid, )) except subprocess.CalledProcessError as exc: print "E: {}: {}".format(exc, exc.output) return None, False data = check_output2(( 'gpg', '--homedir', homedir, '--with-colons', '--fixed-list-mode', '--fingerprint', uid, )) for line in data.splitlines(): if line.startswith('uid:'): name = line.split(':')[9] break else: raise ValueError("Could not parse name from key: {}".format(data)) return Key.objects.update_or_create(uid=uid, defaults={ 'name': name, }) @celery.task() def refresh_all(): for x in Key.objects.all(): update_or_create_key.delay(x.uid)
import celery import subprocess from bidb.utils.tempfile import TemporaryDirectory from bidb.utils.subprocess import check_output2 from .models import Key @celery.task(soft_time_limit=60) def update_or_create_key(uid): with TemporaryDirectory() as homedir: try: check_output2(( 'gpg', '--homedir', homedir, '--keyserver', 'http://p80.pool.sks-keyservers.net/', '--recv-keys', uid, )) except subprocess.CalledProcessError as exc: print "E: {}: {}".format(exc, exc.output) return None, False data = check_output2(( 'gpg', '--homedir', homedir, '--with-colons', '--fixed-list-mode', '--fingerprint', uid, )) for line in data.splitlines(): if line.startswith('uid:'): name = line.split(':')[9] break else: raise ValueError("Could not parse name from key: {}".format(data)) return Key.objects.update_or_create(uid=uid, defaults={ 'name': name, }) @celery.task() def refresh_all(): for x in Key.objects.all(): update_or_create_key.delay(x.uid)
Update the description of the task.
/* * grunt-autoprefixer * * * Copyright (c) 2013 Dmitry Nikitenko * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { var autoprefixer = require('autoprefixer'); grunt.registerMultiTask('autoprefixer', 'Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website.', function () { var options = this.options(), compiler = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function (f) { // Concat specified files. var src = f.src.filter(function (filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function (filepath) { // Read file source. return grunt.file.read(filepath); } ).join(''); // Write the destination file. grunt.file.write(f.dest, compiler.compile(src)); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
/* * grunt-autoprefixer * * * Copyright (c) 2013 Dmitry Nikitenko * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { var autoprefixer = require('autoprefixer'); grunt.registerMultiTask('autoprefixer', 'Parse CSS and add prefixed properties and values by Can I Use database for actual browsers.', function () { var options = this.options(), compiler = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function (f) { // Concat specified files. var src = f.src.filter(function (filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function (filepath) { // Read file source. return grunt.file.read(filepath); } ).join(''); // Write the destination file. grunt.file.write(f.dest, compiler.compile(src)); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
Include Webpack path info in unminified build
var gulp = require('gulp'); var rename = require('gulp-rename'); var webpack = require('webpack'); var webpackStream = require('webpack-stream'); var uglify = require('gulp-uglify'); gulp.task('default', ['build']); gulp.task('build', function() { return gulp.src('src/index.js') .pipe(webpackStream({ module: { loaders: [ { exclude: /node_modules/, test: /\.js$/, loader: 'babel', query: { presets: ['es2015', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ] }, node: { // Mock Node.js modules that Babel require()s but that we don't // particularly care about. fs: 'empty', module: 'empty', net: 'empty' }, output: { filename: 'babel.js', library: 'Babel', libraryTarget: 'umd', pathinfo: true, }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.DedupePlugin() ] })) // Output unminified version .pipe(gulp.dest('.')) // Output minified version .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest('.')); });
var gulp = require('gulp'); var rename = require('gulp-rename'); var webpack = require('webpack'); var webpackStream = require('webpack-stream'); var uglify = require('gulp-uglify'); gulp.task('default', ['build']); gulp.task('build', function() { return gulp.src('src/index.js') .pipe(webpackStream({ module: { loaders: [ { exclude: /node_modules/, test: /\.js$/, loader: 'babel', query: { presets: ['es2015', 'stage-0'] } }, { test: /\.json$/, loader: 'json' } ] }, node: { // Mock Node.js modules that Babel require()s but that we don't // particularly care about. fs: 'empty', module: 'empty', net: 'empty' }, output: { filename: 'babel.js', library: 'Babel', libraryTarget: 'umd', }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': '"production"' }), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.DedupePlugin() ] })) // Output unminified version .pipe(gulp.dest('.')) // Output minified version .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(gulp.dest('.')); });
Update CSP report to try and capture offending page
<?php try { // Send `204 No Content` status code http_response_code(204); // Get the raw POST data $data = file_get_contents('php://input'); // Only continue if it’s valid JSON that is not just `null`, `0`, `false` or an empty string, i.e. if it could be a CSP violation report. if (json_decode($data)) { require_once('./global_functions.php'); require_once('./connections/parameters.php'); $db = new dbWrapper($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true); if ($db) { $headers = json_encode(getallheaders()); $remoteIP = empty($_SERVER['REMOTE_ADDR']) ? NULL : $_SERVER['REMOTE_ADDR']; $reportURI = empty($_SERVER["REQUEST_URI"]) ? NULL : htmlentities($_SERVER["REQUEST_URI"]); $db->q( "INSERT INTO `reports_csp`(`reportContent`, `reportHeaders`, `reportIP`, `reportURI`) VALUES (?, ?, ?, ?);", 'ssss', $data, $headers, $remoteIP, $reportURI ); } else { echo 'No DB!'; } } } catch (Exception $e) { echo $e->getMessage(); }
<?php try { // Send `204 No Content` status code http_response_code(204); // Get the raw POST data $data = file_get_contents('php://input'); // Only continue if it’s valid JSON that is not just `null`, `0`, `false` or an empty string, i.e. if it could be a CSP violation report. if (json_decode($data)) { require_once('./global_functions.php'); require_once('./connections/parameters.php'); $db = new dbWrapper($hostname_gds_site, $username_gds_site, $password_gds_site, $database_gds_site, true); if ($db) { $headers = json_encode(getallheaders()); $remoteIP = empty($_SERVER['REMOTE_ADDR']) ? NULL : $_SERVER['REMOTE_ADDR']; $db->q( "INSERT INTO `reports_csp`(`reportContent`, `reportHeaders`, `reportIP`) VALUES (?, ?, ?);", 'sss', $data, $headers, $remoteIP ); } else { echo 'No DB!'; } } } catch (Exception $e) { echo $e->getMessage(); }
Allow 3D input to MLP
import tensorflow as tf from neuralmonkey.nn.projection import linear, multilayer_projection class MultilayerPerceptron(object): """ General implementation of the multilayer perceptron. """ # pylint: disable=too-many-arguments def __init__(self, mlp_input, layer_configuration, dropout_plc, output_size, name: str = 'multilayer_perceptron', activation_fn=tf.nn.relu) -> None: with tf.variable_scope(name): last_layer_size = mlp_input.get_shape()[-1].value last_layer = multilayer_projection(mlp_input, layer_configuration, activation=activation_fn, dropout_plc=dropout_plc, scope="deep_output_mlp") self.n_params = 0 for size in layer_configuration: self.n_params += last_layer_size * size last_layer_size = size with tf.variable_scope("classification_layer"): self.n_params += last_layer_size * output_size self.logits = linear(last_layer, output_size) @property def softmax(self): with tf.variable_scope("classification_layer"): return tf.nn.softmax(self.logits, name="decision_softmax") @property def classification(self): with tf.variable_scope("classification_layer"): return tf.argmax(self.logits, 1)
import tensorflow as tf from neuralmonkey.nn.projection import linear, multilayer_projection class MultilayerPerceptron(object): """ General implementation of the multilayer perceptron. """ # pylint: disable=too-many-arguments def __init__(self, mlp_input, layer_configuration, dropout_plc, output_size, name: str = 'multilayer_perceptron', activation_fn=tf.nn.relu) -> None: with tf.variable_scope(name): last_layer_size = mlp_input.get_shape()[1].value last_layer = multilayer_projection(mlp_input, layer_configuration, activation=activation_fn, dropout_plc=dropout_plc, scope="deep_output_mlp") self.n_params = 0 for size in layer_configuration: self.n_params += last_layer_size * size last_layer_size = size with tf.variable_scope("classification_layer"): self.n_params += last_layer_size * output_size self.logits = linear(last_layer, output_size) @property def softmax(self): with tf.variable_scope("classification_layer"): return tf.nn.softmax(self.logits, name="decision_softmax") @property def classification(self): with tf.variable_scope("classification_layer"): return tf.argmax(self.logits, 1)
Use custom sugar build for deleting items
const timetrack = require('./timetrack'); require('../libs/sugar-custom.min'); const calculateDuration = require('./calculateDuration'); module.exports = (pluginContext) => { return (query, env = {}) => { return new Promise((resolve, reject) => { // first trim all spaces query = query.trim(); // load the data from the json file timetrack.loadData(); // Filter the items by day let historyItems = timetrack.getHistory() .slice(-10) .map(entry => { // get the duration of the entry let duration = 'Running'; if ('stop' in entry) { // We use beginningOfDay to support different timezones duration = calculateDuration(entry.start, entry.stop); } // get the project name const project = entry.project || 'No project'; // when did we start? const startDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%F %H:%M:%S'); // we use the start ts as unique id because it's unique return { icon: 'assets/history.svg', title: `[${duration}] ${project}`, subtitle: `Started on ${startDate}, click to delete`, value: entry.start } }); // no items found: send message to the app if (!historyItems.length) { return resolve([ { icon: 'assets/history.svg', title: `No entries found to delete`, value: false } ]); } resolve(historyItems); }); } }
const timetrack = require('./timetrack'); const Sugar = require('sugar-date'); const calculateDuration = require('./calculateDuration'); module.exports = (pluginContext) => { return (query, env = {}) => { return new Promise((resolve, reject) => { // first trim all spaces query = query.trim(); // load the data from the json file timetrack.loadData(); // Filter the items by day let historyItems = timetrack.getHistory() .slice(-10) .map(entry => { // get the duration of the entry let duration = 'Running'; if ('stop' in entry) { // We use beginningOfDay to support different timezones duration = calculateDuration(entry.start, entry.stop); } // get the project name const project = entry.project || 'No project'; // when did we start? const startDate = Sugar.Date.format(Sugar.Date.create(entry.start), '%F %H:%M:%S'); // we use the start ts as unique id because it's unique return { icon: 'assets/history.svg', title: `[${duration}] ${project}`, subtitle: `Started on ${startDate}, click to delete`, value: entry.start } }); // no items found: send message to the app if (!historyItems.length) { return resolve([ { icon: 'assets/history.svg', title: `No entries found to delete`, value: false } ]); } resolve(historyItems); }); } }
Use FQCN and automatically add BecklynRadBundle
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( // region Core bundles new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new \Symfony\Bundle\SecurityBundle\SecurityBundle(), new \Symfony\Bundle\TwigBundle\TwigBundle(), new \Symfony\Bundle\MonologBundle\MonologBundle(), new \Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new \Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), // endregion // region Extension bundles new \Becklyn\RadBundle\BecklynRadBundle(), // endregion // region Application bundles new \AppBundle\AppBundle(), // endregion ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new \Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new \Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new \Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new \Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } /** * @inheritdoc */ public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( // region Core bundles new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), // endregion // region Application bundles new AppBundle\AppBundle(), // endregion ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } /** * @inheritdoc */ public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml'); } }
Order content on profile by most recent.
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter( post__contributor__in=contributions ).order_by('-published') posts = Post.published_posts.filter( contributor__in=contributions ).exclude( id__in=comics.values_list('post') ).order_by('-published') context['posts'] = posts context['comics'] = comics return context
from django.shortcuts import render from django.contrib.auth.models import User from django.http import Http404 from django.views.generic import DetailView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import get_object_or_404 from comics.models import ( Comic, Post, Contributor ) class ProfileView(DetailView): template_name="profile.html" model = User def dispatch(self, *args, **kwargs): if kwargs.get('username'): self.user = get_object_or_404(User, username=kwargs.get('username')) elif self.request.user: self.user = self.request.user else: raise Http404() return super(ProfileView, self).dispatch(*args, **kwargs) def get_object(self): return self.user def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) contributions = Contributor.objects.filter(contributor=self.user) comics = Comic.published_comics.filter(post__contributor__in=contributions) posts = Post.published_posts.filter(contributor__in=contributions).exclude(id__in=comics.values_list('post')) context['posts'] = posts context['comics'] = comics return context
Set response code as 403
<?php namespace TypiCMS\Modules\Users\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Spatie\QueryBuilder\AllowedFilter; use Spatie\QueryBuilder\QueryBuilder; use TypiCMS\Modules\Core\Filters\FilterOr; use TypiCMS\Modules\Core\Http\Controllers\BaseApiController; class ApiController extends BaseApiController { public function index(Request $request): LengthAwarePaginator { $data = QueryBuilder::for(config('auth.providers.users.model')) ->allowedSorts(['first_name', 'last_name', 'email', 'superuser']) ->allowedFilters([ AllowedFilter::custom('first_name,last_name,email', new FilterOr()), ]) ->paginate($request->input('per_page')); return $data; } public function updatePreferences(Request $request): void { $user = $request->user(); $user->preferences = array_merge((array) $user->preferences, request()->all()); $user->save(); } public function destroy($userId): JsonResponse { $user = app(config('auth.providers.users.model'))->findOrFail($userId); if (method_exists($user, 'mollieCustomerFields')) { if ($user->hasRunningSubscription()) { return response()->json([ 'error' => true, 'message' => __('User can not be deleted because he has a running subscription.') ], 403); } } $deleted = $user->delete(); return response()->json([ 'error' => !$deleted, ]); } }
<?php namespace TypiCMS\Modules\Users\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Spatie\QueryBuilder\AllowedFilter; use Spatie\QueryBuilder\QueryBuilder; use TypiCMS\Modules\Core\Filters\FilterOr; use TypiCMS\Modules\Core\Http\Controllers\BaseApiController; class ApiController extends BaseApiController { public function index(Request $request): LengthAwarePaginator { $data = QueryBuilder::for(config('auth.providers.users.model')) ->allowedSorts(['first_name', 'last_name', 'email', 'superuser']) ->allowedFilters([ AllowedFilter::custom('first_name,last_name,email', new FilterOr()), ]) ->paginate($request->input('per_page')); return $data; } public function updatePreferences(Request $request): void { $user = $request->user(); $user->preferences = array_merge((array) $user->preferences, request()->all()); $user->save(); } public function destroy($userId): JsonResponse { $user = app(config('auth.providers.users.model'))->findOrFail($userId); if (method_exists($user, 'mollieCustomerFields')) { if ($user->hasRunningSubscription()) { return response()->json([ 'error' => true, 'message' => __('User can not be deleted because he has a running subscription.') ]); } } $deleted = $user->delete(); return response()->json([ 'error' => !$deleted, ]); } }
Add check for running on Mac OS X
try: import pync pync_available = True except ImportError: pync_available = False import platform from .alerter import Alerter class NotificationCenterAlerter(Alerter): """Send alerts to the Mac OS X Notification Center.""" def __init__(self, config_options): Alerter.__init__(self, config_options) if not pync_available: self.alerter_logger.critical("Pync package is not available, which is necessary to use NotificationCenterAlerter.") self.alerter_logger.critical("Try: pip install -r requirements.txt") return if platform.system() != "Darwin": self.alerter_logger.critical("This alerter (currently) only works on Mac OS X!") return def send_alert(self, name, monitor): """Send the message.""" alert_type = self.should_alert(monitor) message = "" if alert_type == "": return elif alert_type == "failure": message = "Monitor {} failed!".format(name) elif alert_type == "success": message = "Monitor {} succeeded.".format(name) else: self.alerter_logger.error("Unknown alert type: {}".format(alert_type)) return if not self.dry_run: pync.notify(message=message, title="SimpleMonitor") else: self.alerter_logger.info("dry_run: would send message: {}".format(message))
try: import pync pync_available = True except ImportError: pync_available = False from .alerter import Alerter class NotificationCenterAlerter(Alerter): """Send alerts to the Mac OS X Notification Center.""" def __init__(self, config_options): Alerter.__init__(self, config_options) if not pync_available: self.alerter_logger.critical("Pync package is not available, cannot use NotificationCenterAlerter.") self.alerter_logger.critical("Try: pip install -r requirements.txt") return def send_alert(self, name, monitor): """Send the message.""" alert_type = self.should_alert(monitor) message = "" if alert_type == "": return elif alert_type == "failure": message = "Monitor {} failed!".format(name) elif alert_type == "success": message = "Monitor {} succeeded.".format(name) else: self.alerter_logger.error("Unknown alert type: {}".format(alert_type)) return if not self.dry_run: pync.notify(message=message, title="SimpleMonitor") else: self.alerter_logger.info("dry_run: would send message: {}".format(message))
Add support for suplementary authentication
<?php namespace Auth; class Authenticator { const SUCCESS = 0; const ALREADY_PRESENT = 1; const LOGIN_FAILED = 2; public $current = false; public $pending = false; public $supplement = false; public function __construct($params) { $this->current = $params['current']; $this->pending = $params['pending']; $this->supplement = $params['supplement']; } public function login($username, $password) { return false; } public function is_logged_in($data) { return false; } public function get_user($data) { return null; } public function get_group_by_name($name) { return null; } public function get_user_by_name($name) { return null; } public function get_groups_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false) { return false; } public function get_users_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false) { return false; } public function get_active_user_count() { $users = $this->get_users_by_filter(false); if($users === false) { return 0; } return count($users); } public function get_pending_user_count() { return 0; } public function get_group_count() { $groups = $this->get_groups_by_filter(false); if($groups === false) { return 0; } return count($groups); } public function get_supplement_link() { return false; } } ?>
<?php namespace Auth; class Authenticator { public function login($username, $password) { return false; } public function is_logged_in($data) { return false; } public function get_user($data) { return null; } public function get_group_by_name($name) { return null; } public function get_user_by_name($name) { return null; } public function get_groups_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false) { return false; } public function get_users_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false) { return false; } public function get_active_user_count() { $users = $this->get_users_by_filter(false); if($users === false) { return 0; } return count($users); } public function get_pending_user_count() { return 0; } public function get_group_count() { $groups = $this->get_groups_by_filter(false); if($groups === false) { return 0; } return count($groups); } } ?>
Handle errors in external command
<?php namespace Kibo\Phast\Filters\Image; use Kibo\Phast\Filters\Image\ImageImplementations\DummyImage; abstract class ExternalAppImageFilter implements ImageFilter { /** * @var array */ protected $config; /** * @param Image $image * @return bool */ abstract protected function shouldApply(Image $image); /** * @return string */ abstract protected function getCommand(); /** * PNGCompressionImageFilter constructor. * * @param array $config */ public function __construct(array $config) { $this->config = $config; } public function transformImage(Image $image) { if (!$this->shouldApply($image)) { return $image; } $command = $this->getCommand(); $proc = proc_open($this->getCommand(), [['pipe', 'r'], ['pipe', 'w']], $pipes); if (!is_resource($proc)) { return $image; } fwrite($pipes[0], $image->getAsString()); fclose($pipes[0]); $compressed = stream_get_contents($pipes[1]); fclose($pipes[1]); $status = proc_close($proc); if ($status != 0) { throw new RuntimeException("External image processing command failed with status {$status}: {$command}"); } if ($compressed == '') { throw new RuntimeException("External image processing command did not output anything: {$command}"); } $newImage = new DummyImage(); $newImage->setImageString($compressed); $newImage->setType(Image::TYPE_PNG); return $newImage; } }
<?php namespace Kibo\Phast\Filters\Image; use Kibo\Phast\Filters\Image\ImageImplementations\DummyImage; abstract class ExternalAppImageFilter implements ImageFilter { /** * @var array */ protected $config; /** * @param Image $image * @return bool */ abstract protected function shouldApply(Image $image); /** * @return string */ abstract protected function getCommand(); /** * PNGCompressionImageFilter constructor. * * @param array $config */ public function __construct(array $config) { $this->config = $config; } public function transformImage(Image $image) { if (!$this->shouldApply($image)) { return $image; } $proc = proc_open($this->getCommand(), [['pipe', 'r'], ['pipe', 'w']], $pipes); if (!is_resource($proc)) { return $image; } fwrite($pipes[0], $image->getAsString()); fclose($pipes[0]); $compressed = stream_get_contents($pipes[1]); fclose($pipes[1]); proc_close($proc); $newImage = new DummyImage(); $newImage->setImageString($compressed); $newImage->setType(Image::TYPE_PNG); return $newImage; } }
Fix down migration for gtDirGUID
<?php declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddMetadataFieldsToUsers extends Migration { /** * Run the migrations. */ public function up(): void { DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping( 'enum', 'string' ); Schema::table('users', static function (Blueprint $table): void { $table->string('create_reason', 255)->default('cas_login'); $table->boolean('has_ever_logged_in')->default(true); $table->boolean('is_service_account')->default(false); $table->string('primary_affiliation')->nullable(); $table->timestamp('last_login')->nullable(); $table->string('gtDirGUID')->nullable(); }); Schema::table('users', static function (Blueprint $table): void { $table->string('create_reason', 255)->default(null)->change(); $table->boolean('has_ever_logged_in')->default(null)->change(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('users', static function (Blueprint $table): void { $table->dropColumn('create_reason'); $table->dropColumn('has_ever_logged_in'); $table->dropColumn('is_service_account'); $table->dropColumn('primary_affiliation'); $table->dropColumn('last_login'); $table->dropColumn('gtDirGUID'); }); } }
<?php declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddMetadataFieldsToUsers extends Migration { /** * Run the migrations. */ public function up(): void { DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping( 'enum', 'string' ); Schema::table('users', static function (Blueprint $table): void { $table->string('create_reason', 255)->default('cas_login'); $table->boolean('has_ever_logged_in')->default(true); $table->boolean('is_service_account')->default(false); $table->string('primary_affiliation')->nullable(); $table->timestamp('last_login')->nullable(); $table->string('gtDirGUID')->nullable(); }); Schema::table('users', static function (Blueprint $table): void { $table->string('create_reason', 255)->default(null)->change(); $table->boolean('has_ever_logged_in')->default(null)->change(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('users', static function (Blueprint $table): void { $table->dropColumn('create_reason'); $table->dropColumn('has_ever_logged_in'); $table->dropColumn('is_service_account'); $table->dropColumn('primary_affiliation'); $table->dropColumn('last_login'); }); } }
Use methods instead of property
<?php if (!function_exists('is_field_translatable')) { /** * Check if a Field is translatable. * * @param Illuminate\Database\Eloquent\Model $model * @param Illuminate\Database\Eloquent\Collection $row */ function is_field_translatable($model, $row) { if (!is_bread_translatable($model)) { return; } return $model->translatable() && in_array($row->field, $model->getTranslatableAttributes()); } } if (!function_exists('get_field_translations')) { /** * Return all field translations. * * @param Illuminate\Database\Eloquent\Model $model * @param string $field * @param string $rowType * @param bool $stripHtmlTags */ function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false) { $_out = $model->getTranslationsOf($field); if ($stripHtmlTags && $rowType == 'rich_text_box') { foreach ($_out as $language => $value) { $_out[$language] = strip_tags($_out[$language]); } } return json_encode($_out); } } if (!function_exists('is_bread_translatable')) { /** * Check if BREAD is translatable. * * @param Illuminate\Database\Eloquent\Model $model */ function is_bread_translatable($model) { return config('voyager.multilingual.enabled') && isset($model) && $model->translatable(); } }
<?php if (!function_exists('is_field_translatable')) { /** * Check if a Field is translatable. * * @param Illuminate\Database\Eloquent\Model $model * @param Illuminate\Database\Eloquent\Collection $row */ function is_field_translatable($model, $row) { if (!is_bread_translatable($model)) { return; } return isset($model['translatable']) && in_array($row->field, $model['translatable']); } } if (!function_exists('get_field_translations')) { /** * Return all field translations. * * @param Illuminate\Database\Eloquent\Model $model * @param string $field * @param string $rowType * @param bool $stripHtmlTags */ function get_field_translations($model, $field, $rowType = '', $stripHtmlTags = false) { $_out = $model->getTranslationsOf($field); if ($stripHtmlTags && $rowType == 'rich_text_box') { foreach ($_out as $language => $value) { $_out[$language] = strip_tags($_out[$language]); } } return json_encode($_out); } } if (!function_exists('is_bread_translatable')) { /** * Check if BREAD is translatable. * * @param Illuminate\Database\Eloquent\Model $model */ function is_bread_translatable($model) { return config('voyager.multilingual.enabled') && isset($model, $model['translatable']); } }
Remove cacheing of the json
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; // Don't cache the json :) $.ajaxSetup({ cache:false }); $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
$(document).ready(function() { var options = { chart: { renderTo: 'chart', type: 'spline', }, title: { text: 'Recent Water Values' }, xAxis: { type: 'datetime', title: { text: 'Date' } }, yAxis: { labels: { formatter: function() { return this.value == 1 ? 'Wet' : 'Dry'; } }, min: 0, max: 1, tickInterval: 1, title: { text: null } }, legend: { enabled: false }, series: [{}] }; $.getJSON('data.json', function(data) { var series = []; // Store some stats while parsing through var lastStatus; var lastWet; var lastDry; $.each(data, function(key, value) { series.push([Date.parse(key), value]); lastStatus = value; if (value == 1) { lastWet = key; } if (value == 0) { lastDry = key; } }); $('#current').text(lastStatus ? 'Wet' : 'Dry'); $('#lastWet').text(lastWet); $('#lastDry').text(lastDry); options.series[0].data = series; options.series[0].color = '#449944'; options.series[0].name = 'Water Value'; var chart = new Highcharts.Chart(options); }); });
(Migrations): Change user_agent column to text
<?php use Phinx\Migration\AbstractMigration; class SetUpAuthenticationHistory extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class * * The following commands can be used in this method and Phinx will * automatically reverse them when rolling back: * * createTable * renameTable * addColumn * renameColumn * addIndex * addForeignKey * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. */ public function change() { $this->table('user_login_history') ->addColumn('user_id', 'integer', ['length' => 11]) ->addColumn('login_status', 'string', ['length' => 100]) ->addColumn('ip_address', 'string', ['length' => 100, 'null' => true]) ->addColumn('user_agent', 'text') ->addColumn('date_logged', 'datetime', ['null' => false]) ->addForeignKey('user_id', 'user_credentials', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE']) ->create(); } }
<?php use Phinx\Migration\AbstractMigration; class SetUpAuthenticationHistory extends AbstractMigration { /** * Change Method. * * Write your reversible migrations using this method. * * More information on writing migrations is available here: * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class * * The following commands can be used in this method and Phinx will * automatically reverse them when rolling back: * * createTable * renameTable * addColumn * renameColumn * addIndex * addForeignKey * * Remember to call "create()" or "update()" and NOT "save()" when working * with the Table class. */ public function change() { $this->table('user_login_history') ->addColumn('user_id', 'integer', ['length' => 11]) ->addColumn('login_status', 'string', ['length' => 100]) ->addColumn('ip_address', 'string', ['length' => 100, 'null' => true]) ->addColumn('user_agent', 'string', ['length' => 100, 'null' => true]) ->addColumn('date_logged', 'datetime', ['null' => false]) ->addForeignKey('user_id', 'user_credentials', ['id'], ['delete' => 'CASCADE', 'update' => 'CASCADE']) ->create(); } }
Refactor method to have an explicit list of special words
define([ 'extensions/views/table/table' ], function (Table) { var HelpUsageTable = Table.extend({ capitalizeFirstWord: function(string) { return string.replace(/(?:^|\s)\S/, function(letter) { return letter.toUpperCase(); }); }, capitalizeSpecialWords: function(string) { var specialWords = ["LPA", "BACS", "I"]; return _.reduce(specialWords, function (newString, word) { var lowerCaseExpression = new RegExp("(\\s|^)" + word.toLowerCase() + "(\\s|$)", "g"), upperCaseReplacement = " " + word + " "; return newString.replace(lowerCaseExpression, upperCaseReplacement); }, string); }, sanitizeDescription: function (rawDescription) { var spaceSeparatedDescription = rawDescription.replace(/-/g, " "), lowercaseDescription = this.capitalizeSpecialWords(spaceSeparatedDescription); return this.capitalizeFirstWord(lowercaseDescription); }, columns: [ { id: 'description', title: 'Description', sortable: true, getValue: function (model) { return this.sanitizeDescription(model.get('description')); } }, { id: 'count', className: 'count numeric', title: 'Usage last week', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatNumericLabel(model.get('count')); } } ], defaultSortColumn: 1 }); return HelpUsageTable; });
define([ 'extensions/views/table/table' ], function (Table) { var HelpUsageTable = Table.extend({ capitalizeFirstWord: function(string) { return string.replace(/(?:^|\s)\S/, function(letter) { return letter.toUpperCase(); }); }, capitalizeSpecialWords: function(string) { return string.replace(/(\s|^)lpa(\s|$)/g, " LPA ") .replace(/(\s|^)bacs(\s|$)/g, " BACS ") .replace(/(\s|^)i(\s|$)/g, " I "); }, sanitizeDescription: function (rawDescription) { var spaceSeparatedDescription = rawDescription.replace(/-/g, " "), lowercaseDescription = this.capitalizeSpecialWords(spaceSeparatedDescription); return this.capitalizeFirstWord(lowercaseDescription); }, columns: [ { id: 'description', title: 'Description', sortable: true, getValue: function (model) { return this.sanitizeDescription(model.get('description')); } }, { id: 'count', className: 'count numeric', title: 'Usage last week', sortable: true, defaultDescending: true, getValue: function (model) { return this.formatNumericLabel(model.get('count')); } } ], defaultSortColumn: 1 }); return HelpUsageTable; });
Drop uncritical dependencies to enable alt runtimes Node is still supported, and IoT.js can be ported. Related links: https://engineering.upside.com/you-dont-need-lodash-3323ca2cfb4c https://github.com/rzr/webthing-iotjs Change-Id: I58c8c5b728ea6cd457e6618c952c0b7c8a406315 Bug: https://github.com/miroRucka/bh1750/pull/15 Origin: https://github.com/tizenteam/bh1750/tree/iotjs/master Signed-off-by: Philippe Coval <[email protected]>
var console = require('console'); var i2c = require('i2c'); var BH1750 = function (opts) { this.options = opts || { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }; this.verbose = this.options.verbose || false; this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!cb) { throw new Error("Invalid param"); } self.wire.readBytes(self.options.command, self.options.length, function (err, res) { if (err) { if (self.verbose) console.error("error: I/O failure on BH1750 - command: ", self.options.command); return cb(err, null); } var hi = res[0]; var lo = res[1]; if (Buffer.isBuffer(res)) { hi = res.readUInt8(0); lo = res.readUInt8(1); } var lux = ((hi << 8) + lo)/1.2; if (self.options.command === 0x11) { lux = lux/2; } cb(null, lux); }); }; module.exports = BH1750;
var console = require('console'); var i2c = require('i2c'); var _ = require('lodash'); var utils = require('./utils'); var BH1750 = function (opts) { this.options = _.extend({}, { address: 0x23, device: '/dev/i2c-1', command: 0x10, length: 2 }, opts); this.verbose = this.options.verbose || false; this.wire = new i2c(this.options.address, {device: this.options.device}); }; BH1750.prototype.readLight = function (cb) { var self = this; if (!utils.exists(cb)) { throw new Error("Invalid param"); } self.wire.readBytes(self.options.command, self.options.length, function (err, res) { if (utils.exists(err)) { if (self.verbose) console.error("error: I/O failure on BH1750 - command: ", self.options.command); return cb(err, null); } var hi = res[0]; var lo = res[1]; if (Buffer.isBuffer(res)) { hi = res.readUInt8(0); lo = res.readUInt8(1); } var lux = ((hi << 8) + lo)/1.2; if (self.options.command === 0x11) { lux = lux/2; } cb(null, lux); }); }; module.exports = BH1750;
Add confirmation before running init command in existing project ugh, another useless commit Undo temp file
<?php namespace TightenCo\Jigsaw\Console; use Symfony\Component\Console\Input\InputArgument; use TightenCo\Jigsaw\File\Filesystem; class InitCommand extends Command { private $files; private $base; public function __construct(Filesystem $files) { $this->files = $files; $this->base = getcwd(); parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Scaffold a new Jigsaw project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base .= '/' . $base; } $this->ifAlreadyScaffoldedWarnBeforeDoingTheFollowing(function () { $this->scaffoldSite(); $this->scaffoldMix(); $this->info('Site initialized successfully!'); }); } private function ifAlreadyScaffoldedWarnBeforeDoingTheFollowing($callback) { if ($this->files->exists($this->base . '/config.php')) { $this->info('It looks like you\'ve already run "jigsaw init" on this project.'); $this->info('Running it again may overwrite important files.'); $this->info(''); if (! $this->confirm('Do you wish to continue?')) { return; } } $callback(); } private function scaffoldSite() { $this->files->copyDirectory(__DIR__ . '/../../stubs/site', $this->base); } private function scaffoldMix() { $this->files->copyDirectory(__DIR__ . '/../../stubs/mix', $this->base); } }
<?php namespace TightenCo\Jigsaw\Console; use Symfony\Component\Console\Input\InputArgument; use TightenCo\Jigsaw\File\Filesystem; class InitCommand extends Command { private $files; private $base; public function __construct(Filesystem $files) { $this->files = $files; $this->base = getcwd(); parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Scaffold a new Jigsaw project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base .= '/' . $base; } $this->scaffoldSite(); $this->scaffoldMix(); $this->info('Site initialized successfully!'); } private function scaffoldSite() { $this->files->copyDirectory(__DIR__ . '/../../stubs/site', $this->base); } private function scaffoldMix() { $this->files->copyDirectory(__DIR__ . '/../../stubs/mix', $this->base); } }
Check that the .node file actually exists
var fs = require('fs'), path = require('path'); // normalize node 0.6 and 0.8 fs.existsSync || (fs.existsSync = path.existsSync); var platforms = { win32: function(folder, file){ process.env.PATH += ';' + folder; } }; // derive a distributable path from the node version, platform, and arch function distribPath(){ return [ '..', 'compiled', process.version.slice(1, 4), process.platform, process.arch, 'bindings'].join('/'); } // resolve a path relative the directory this .js file is in function absolutelyRelative(pathname){ return path.resolve(__dirname, pathname); } // find the binary file for a given name function requireBindings(lib){ var folder = [ '../build/Release', // self-compiled release '../build/Debug', // self-compiled debug distribPath() // system-relative pre-compiled ].map(absolutelyRelative) .filter(fs.existsSync)[0]; if (!folder) { throw new Error("Unable to locate bindings for " + lib); } var libPath = folder + '/' + lib + '.node'; if (!fs.existsSync(libPath)) { throw new Error("Binaries for " + lib + " not found in '" + folder + "'"); } if (process.platform in platforms) { platforms[process.platform](folder, libPath); } return require(libPath); } module.exports = requireBindings('appjs');
var fs = require('fs'), path = require('path'); // normalize node 0.6 and 0.8 fs.existsSync || (fs.existsSync = path.existsSync); var platforms = { win32: function(folder){ process.env.PATH += ';' + folder; } }; // derive a distributable path from the node version, platform, and arch function distribPath(){ return [ '..', 'compiled', process.version.slice(1, 4), process.platform, process.arch, 'bindings/'].join('/'); } // resolve a path relative the directory this .js file is in function absolutelyRelative(pathname){ return path.resolve(__dirname, pathname); } // find the binary file for a given name function requireBindings(lib){ var folder = [ '../build/Release/', // self-compiled release '../build/Debug/', // self-compiled debug distribPath() // system-relative pre-compiled ].map(absolutelyRelative) .filter(fs.existsSync)[0]; if (!folder) { throw new Error('Unable to locate binaries for '+lib); } if (process.platform in platforms) { platforms[process.platform](folder); } return require(folder + '/' + lib); } module.exports = requireBindings('appjs');
Allow `css_class` to have blank value. Currently the default value for the `css_class` field (name `Normal`) has the value of a blank string. To allow the value to be used `blank=True` must be set.
# -*- coding: utf-8 -*- __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(blank=True, max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
# -*- coding: utf-8 -*- __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL'), null=True, blank=True) css_class = models.CharField(max_length=20, verbose_name=_('CSS Class'), choices=CSS_CLASS_CHOICES) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), null=True, blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
Add pragma: nocover to non-implemented methods
#!/usr/bin/env python # coding: utf-8 import sys import os # import argparse class Infect(object): class Codes: symlink = { 'success': 0, 'target_not_found': 1, 'destination_already_linked': 2, 'destination_exists': 3, } def __init__(self): pass def install(self): # pragma: nocover pass def upload(self): # pragma: nocover pass def symlink(self, target, dest): """ Symlink a file and its destination Will return a return code from `Infect.Codes.symlink`. """ if not os.path.isfile(target): return self.Codes.symlink['target_not_found'] if os.path.islink(dest): return self.Codes.symlink['destination_already_linked'] if os.path.isfile(dest) or os.path.isdir(dest): return self.Codes.symlink['destination_exists'] os.symlink(target, dest) return self.Codes.symlink['success'] def uninstall(self): # pragma: nocover pass def main(): # pragma: nocover print('Running infect main()') return 0 if __name__ == "__main__": # pragma: nocover sys.exit(main())
#!/usr/bin/env python # coding: utf-8 import sys import os # import argparse class Infect(object): class Codes: symlink = { 'success': 0, 'target_not_found': 1, 'destination_already_linked': 2, 'destination_exists': 3, } def __init__(self): pass def install(self): pass def upload(self): pass def symlink(self, target, dest): """ Symlink a file and its destination Will return a return code from `Infect.Codes.symlink`. """ if not os.path.isfile(target): return self.Codes.symlink['target_not_found'] if os.path.islink(dest): return self.Codes.symlink['destination_already_linked'] if os.path.isfile(dest) or os.path.isdir(dest): return self.Codes.symlink['destination_exists'] os.symlink(target, dest) return self.Codes.symlink['success'] def uninstall(self): pass def main(): print('Running infect main()') return 0 if __name__ == "__main__": sys.exit(main())
Correct 'message status' nav label
def features_nav(): return [ { "name": "Features", "link": "main.features", }, { "name": "Emails", "link": "main.features_email", }, { "name": "Text messages", "link": "main.features_sms", }, { "name": "Letters", "link": "main.features_letters", }, { "name": "Roadmap", "link": "main.roadmap", }, { "name": "Trial mode", "link": "main.trial_mode_new", }, { "name": "Message status", "link": "main.message_status", }, { "name": "Security", "link": "main.security", }, { "name": "Terms of use", "link": "main.terms", }, { "name": "Using Notify", "link": "main.using_notify", }, ]
def features_nav(): return [ { "name": "Features", "link": "main.features", }, { "name": "Emails", "link": "main.features_email", }, { "name": "Text messages", "link": "main.features_sms", }, { "name": "Letters", "link": "main.features_letters", }, { "name": "Roadmap", "link": "main.roadmap", }, { "name": "Trial mode", "link": "main.trial_mode_new", }, { "name": "Message statuses", "link": "main.message_status", }, { "name": "Security", "link": "main.security", }, { "name": "Terms of use", "link": "main.terms", }, { "name": "Using Notify", "link": "main.using_notify", }, ]
Use uniqid rather than plain ol timestamp.
<?php namespace DoSomething\Gateway; trait ForwardsTransactionIds { /** * Run custom tasks before making a request. * * @see RestApiClient@raw */ public function runForwardsTransactionIdsTasks($method, &$path, &$options, &$withAuthorization) { $transactionId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : null; // If there is no 'X-Request-ID' in the header, create one. if (! $transactionId) { $newHeader = ['X-Request-ID' => uniqid() . '-0']; } else { // Otherwise, if there is a 'X-Request-ID' header, keep the // current transaction ID and increment the step by one. list($requestId, $step) = explode('-', $transactionId, 2); $newHeader = ['X-Request-ID' => $requestId. '-' . ($step + 1)]; } // Add incremented header to downstream API requests. $options['headers'] = array_merge($options['headers'], $newHeader); // If we have a logger, write details to the log. if (! empty($this->logger)) { $this->logger->info('Request made.', [ 'method' => $method, 'uri' => $this->getBaseUri() . $path, 'transaction_id' => $options['headers']['X-Request-ID'], ]); } } }
<?php namespace DoSomething\Gateway; trait ForwardsTransactionIds { /** * Run custom tasks before making a request. * * @see RestApiClient@raw */ public function runForwardsTransactionIdsTasks($method, &$path, &$options, &$withAuthorization) { $transactionId = isset($_SERVER['HTTP_X_REQUEST_ID']) ? $_SERVER['HTTP_X_REQUEST_ID'] : null; // If there is no 'X-Request-ID' in the header, create one. if (! $transactionId) { $newHeader = ['X-Request-ID' => microtime(true) . '-0']; } else { // Otherwise, if there is a 'X-Request-ID' header, keep the // current transaction ID and increment the step by one. list($requestId, $step) = explode('-', $transactionId, 2); $newHeader = ['X-Request-ID' => $requestId. '-' . ($step + 1)]; } // Add incremented header to downstream API requests. $options['headers'] = array_merge($options['headers'], $newHeader); // If we have a logger, write details to the log. if (! empty($this->logger)) { $this->logger->info('Request made.', [ 'method' => $method, 'uri' => $this->getBaseUri() . $path, 'transaction_id' => $options['headers']['X-Request-ID'], ]); } } }
Use surface.transaction() in TagEntityPanel to trigger selection update. Fixes substance/archivist#134.
var SelectEntityMixin = require("../select_entity_mixin"); var _ = require("substance/helpers"); var TagEntityPanelMixin = _.extend({}, SelectEntityMixin, { // Called with entityId when an entity has been clicked handleSelection: function(entityId) { var app = this.context.app; var doc = app.doc; var entityReferenceId = this.props.entityReferenceId; var surface = app.surfaceManager.getFocusedSurface(); if (entityReferenceId) { surface.transaction(function(tx) { tx.set([entityReferenceId, "target"], entityId); }); app.replaceState({ contextId: "showEntityReference", entityReferenceId: entityReferenceId }); } else { var path = this.props.path; var startOffset = this.props.startOffset; var endOffset = this.props.endOffset; var annotation = app.annotate({ type: "entity_reference", target: entityId, path: path, startOffset: startOffset, endOffset: endOffset }); // Switch state to highlight newly created reference app.replaceState({ contextId: "showEntityReference", entityReferenceId: annotation.id, noScroll: true }); } } }); var TagEntityPanel = React.createClass({ mixins: [TagEntityPanelMixin], displayName: "Tag Entity" }); // Panel configuration // ---------------- TagEntityPanel.contextId = "tagentity"; TagEntityPanel.icon = "fa-bullseye"; // No context switch toggle is shown TagEntityPanel.isDialog = true; module.exports = TagEntityPanel;
var SelectEntityMixin = require("../select_entity_mixin"); var _ = require("substance/helpers"); var TagEntityPanelMixin = _.extend({}, SelectEntityMixin, { // Called with entityId when an entity has been clicked handleSelection: function(entityId) { var app = this.context.app; var doc = app.doc; var entityReferenceId = this.props.entityReferenceId; if (entityReferenceId) { doc.transaction(function(tx) { tx.set([entityReferenceId, "target"], entityId); }); app.replaceState({ contextId: "showEntityReference", entityReferenceId: entityReferenceId }); } else { var path = this.props.path; var startOffset = this.props.startOffset; var endOffset = this.props.endOffset; var annotation = app.annotate({ type: "entity_reference", target: entityId, path: path, startOffset: startOffset, endOffset: endOffset }); // Switch state to highlight newly created reference app.replaceState({ contextId: "showEntityReference", entityReferenceId: annotation.id, noScroll: true }); } } }); var TagEntityPanel = React.createClass({ mixins: [TagEntityPanelMixin], displayName: "Tag Entity" }); // Panel configuration // ---------------- TagEntityPanel.contextId = "tagentity"; TagEntityPanel.icon = "fa-bullseye"; // No context switch toggle is shown TagEntityPanel.isDialog = true; module.exports = TagEntityPanel;
Add migration to boot method of service provider
<?php namespace Avanderbergh\Schoology; use OneLogin_Saml2_Auth; use URL; use Illuminate\Support\ServiceProvider; class Saml2ServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { /* * publish the saml_settings file to the config_path */ $this->publishes([ __DIR__.'/../../config/saml2_settings.php' => config_path('saml2_settings.php'), __DIR__.'/../../migrations/create_oauth_store_table.php' => database_path('migrations/create_oauth_store_table.php') ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('Avanderbegh\Schoology\Saml2Auth', function ($app) { $config = config('saml2_settings'); $config['sp']['entityId'] = URL::route('saml_metadata'); $config['sp']['assertionConsumerService']['url'] = URL::route('saml_acs'); $config['sp']['singleLogoutService']['url'] = URL::route('saml_sls'); $auth = new OneLogin_Saml2_Auth($config); return new Saml2Auth($auth); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
<?php namespace Avanderbergh\Schoology; use OneLogin_Saml2_Auth; use URL; use Illuminate\Support\ServiceProvider; class Saml2ServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { /* * publish the saml_settings file to the config_path */ $this->publishes([ __DIR__.'/../../config/saml2_settings.php' => config_path('saml2_settings.php'), ]); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('Avanderbegh\Schoology\Saml2Auth', function ($app) { $config = config('saml2_settings'); $config['sp']['entityId'] = URL::route('saml_metadata'); $config['sp']['assertionConsumerService']['url'] = URL::route('saml_acs'); $config['sp']['singleLogoutService']['url'] = URL::route('saml_sls'); $auth = new OneLogin_Saml2_Auth($config); return new Saml2Auth($auth); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } }
Make append argument easier to read
package servlets; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FormDataFileSaver extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = request.getServletContext(); final String OUTPUT_FILE_PATH = context.getRealPath("/") + "output.txt"; // Read data from submitted form String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String age = request.getParameter("age"); String egnNumber = request.getParameter("egnNumber"); // Save data to a file try { boolean appendToFile = true; PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH, appendToFile))); out.println(firstName + " " + lastName + ", " + age + " years old, EGN: " + egnNumber); out.close(); PrintWriter output = response.getWriter(); output.println("Info successfully saved to " + OUTPUT_FILE_PATH); } catch (IOException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
package servlets; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FormDataFileSaver extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = request.getServletContext(); final String OUTPUT_FILE_PATH = context.getRealPath("/") + "output.txt"; // Read data from submitted form String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); String age = request.getParameter("age"); String egnNumber = request.getParameter("egnNumber"); // Save data to a file try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(OUTPUT_FILE_PATH, true))); out.println(firstName + " " + lastName + ", " + age + " years old, EGN: " + egnNumber); out.close(); PrintWriter output = response.getWriter(); output.println("Info successfully saved to " + OUTPUT_FILE_PATH); } catch (IOException e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
Add support for proper aliasing
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Elasticsearch; use App\Console\Helpers\Indexer; class UninstallSearch extends Command { use Indexer; protected $signature = 'search:uninstall {index? : The group of indexes to delete} {--y|yes : Answer "yes" to all prompts confirming to delete index}'; protected $description = 'Tear down the Search Service indexes'; /** * The prefix of the indexes to delete. * * @var string */ protected $index; public function __construct() { parent::__construct(); $this->index = env('ELASTICSEARCH_INDEX', 'test_'); } public function handle() { if ($this->argument('index')) { $this->index = $this->argument('index'); } if (!$this->option('yes') && !$this->confirm("This will delete all indexes that are a part of the " .$this->index ." alias. Do you wish to continue?")) { return false; } foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model) { $endpoint = endpointFor($model); $index = $this->index .'-' .$endpoint; $this->info('Deleting ' .$index .' index...'); $params = [ 'index' => $index, ]; if (Elasticsearch::indices()->exists($params)) { $return = Elasticsearch::indices()->delete($params); $this->info($this->done($return)); } else { $this->info("Index " .$index . " does not exist."); } } } }
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Elasticsearch; use App\Console\Helpers\Indexer; class UninstallSearch extends Command { use Indexer; protected $signature = 'search:uninstall {prefix? : The prefixes of the indexes to delete} {--y|yes : Answer "yes" to all prompts confirming to delete index}'; protected $description = 'Tear down the Search Service indexes'; /** * The prefix of the indexes to delete. * * @var string */ protected $prefix; public function __construct() { parent::__construct(); $this->prefix = env('ELASTICSEARCH_INDEX_PREFIX', 'test_'); } public function handle() { if ($this->argument('prefix')) { $this->prefix = $this->argument('prefix'); } if (!$this->option('yes') && !$this->confirm("This will delete all indexes that begin with the prefix " .$this->prefix .". Do you wish to continue?")) { return false; } foreach (allModelsThatUse(\App\Models\ElasticSearchable::class) as $model) { $endpoint = endpointFor($model); $index = $this->prefix .$endpoint; $params = [ 'index' => $index, ]; if (Elasticsearch::indices()->exists($params)) { $return = Elasticsearch::indices()->delete($params); $this->info($this->done($return)); } else { $this->info("Index " .$index . " does not exist."); } } } }
Handle a Werkzeug ClosingIterator (as exposed by the tests)
# -*- encoding: utf-8 import json from flask import Response, jsonify from werkzeug.wsgi import ClosingIterator class ContextResponse(Response): """ This class adds the "@context" parameter to JSON responses before they're sent to the user. For an explanation of how this works/is used, read https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class """ context_url = "https://api.wellcomecollection.org/storage/v1/context.json" def __init__(self, response, *args, **kwargs): """ Unmarshal the response as provided by Flask-RESTPlus, add the @context parameter, then repack it. """ if isinstance(response, ClosingIterator): response = b''.join([char for char in response]) rv = json.loads(response) # The @context may already be provided if we've been through the # force_type method below. if "@context" in rv: return super(ContextResponse, self).__init__(response, **kwargs) else: rv["@context"] = self.context_url json_string = json.dumps(rv) return super(ContextResponse, self).__init__(json_string, **kwargs) @classmethod def force_type(cls, rv, environ=None): # All of our endpoints should be returning a dictionary to be # serialised as JSON. assert isinstance(rv, dict) assert "@context" not in rv, rv rv["@context"] = cls.context_url return super(ContextResponse, cls).force_type(jsonify(rv), environ)
# -*- encoding: utf-8 import json from flask import Response, jsonify class ContextResponse(Response): """ This class adds the "@context" parameter to JSON responses before they're sent to the user. For an explanation of how this works/is used, read https://blog.miguelgrinberg.com/post/customizing-the-flask-response-class """ context_url = "https://api.wellcomecollection.org/storage/v1/context.json" def __init__(self, response, **kwargs): # Here we unmarshal the response as provided by Flask-RESTPlus, add # the @context parameter, then repack it. rv = json.loads(response) # The @context may already be provided if we've been through the # force_type method below. if "@context" in rv: return super(ContextResponse, self).__init__(response, **kwargs) else: rv["@context"] = self.context_url return super(ContextResponse, self).__init__(json.dumps(rv), **kwargs) @classmethod def force_type(cls, rv, environ=None): # All of our endpoints should be returning a dictionary to be # serialised as JSON. assert isinstance(rv, dict) assert "@context" not in rv, rv rv["@context"] = cls.context_url return super(ContextResponse, cls).force_type(jsonify(rv), environ)
Add cppcheck issue id as code field
from SublimeLinter.lint import Linter, util class Cppcheck(Linter): cmd = ( 'cppcheck', '--template={file}:{line}:{column}:{severity}:{id}:{message}', '--inline-suppr', '--quiet', '${args}', '${file}' ) regex = ( r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)' r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):' r'(?P<code>\w+):(?P<message>.+)' ) error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout on_stderr = None # handle stderr via split_match tempfile_suffix = '-' defaults = { 'selector': 'source.c, source.c++', '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } def split_match(self, match): """ Return the components of the match. We override this because included header files can cause linter errors, and we only want errors from the linted file. """ if match: if match.group('file') != self.filename: return None return super().split_match(match)
from SublimeLinter.lint import Linter, util class Cppcheck(Linter): cmd = ( 'cppcheck', '--template={file}:{line}: {severity}: {message}', '--inline-suppr', '--quiet', '${args}', '${file}' ) regex = ( r'^(?P<file>(:\\|[^:])+):(?P<line>\d+):((?P<col>\d+):)?\s+' r'((?P<error>error)|(?P<warning>warning|style|performance|portability|information)):\s+' r'(?P<message>.+)' ) error_stream = util.STREAM_BOTH # linting errors are on stderr, exceptions like "file not found" on stdout on_stderr = None # handle stderr via split_match tempfile_suffix = '-' defaults = { 'selector': 'source.c, source.c++', '--std=,+': [], # example ['c99', 'c89'] '--enable=,': 'style', } def split_match(self, match): """ Return the components of the match. We override this because included header files can cause linter errors, and we only want errors from the linted file. """ if match: if match.group('file') != self.filename: return None return super().split_match(match)
Remove Tower reference from email backend
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import json from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend from django.utils.translation import ugettext_lazy as _ class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host", "type": "string"}, "port": {"label": "Port", "type": "int"}, "username": {"label": "Username", "type": "string"}, "password": {"label": "Password", "type": "password"}, "use_tls": {"label": "Use TLS", "type": "bool"}, "use_ssl": {"label": "Use SSL", "type": "bool"}, "sender": {"label": "Sender Email", "type": "string"}, "recipients": {"label": "Recipient List", "type": "list"}} recipient_parameter = "recipients" sender_parameter = "sender" def format_body(self, body): if "body" in body: body_actual = body['body'] else: body_actual = smart_text(_("{} #{} had status {}, view details at {}\n\n").format( body['friendly_name'], body['id'], body['status'], body['url']) ) body_actual += json.dumps(body, indent=4) return body_actual
# Copyright (c) 2016 Ansible, Inc. # All Rights Reserved. import json from django.utils.encoding import smart_text from django.core.mail.backends.smtp import EmailBackend from django.utils.translation import ugettext_lazy as _ class CustomEmailBackend(EmailBackend): init_parameters = {"host": {"label": "Host", "type": "string"}, "port": {"label": "Port", "type": "int"}, "username": {"label": "Username", "type": "string"}, "password": {"label": "Password", "type": "password"}, "use_tls": {"label": "Use TLS", "type": "bool"}, "use_ssl": {"label": "Use SSL", "type": "bool"}, "sender": {"label": "Sender Email", "type": "string"}, "recipients": {"label": "Recipient List", "type": "list"}} recipient_parameter = "recipients" sender_parameter = "sender" def format_body(self, body): if "body" in body: body_actual = body['body'] else: body_actual = smart_text(_("{} #{} had status {} on Ansible Tower, view details at {}\n\n").format( body['friendly_name'], body['id'], body['status'], body['url']) ) body_actual += json.dumps(body, indent=4) return body_actual