text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix compilation issue because of latest Forge RB
package org.cyclops.commoncapabilities.core; import net.minecraftforge.fml.relauncher.ReflectionHelper; import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Helper methods. * @author rubensworks */ public class Helpers { public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) { if (method != null) { try { return (R) method.invoke(instance, arguments); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return null; } public static <R> R getFieldValue(Object instance, @Nullable Field field) { if (field != null) { try { return (R) field.get(instance); } catch (IllegalAccessException e) { e.printStackTrace(); } } return null; } public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) { try { return ReflectionHelper.findMethod(clazz, method, null, methodTypes); } catch (ReflectionHelper.UnableToFindMethodException e) { e.printStackTrace(); return null; } } public static Field getField(Class<?> clazz, String field) { try { return ReflectionHelper.findField(clazz, field); } catch (ReflectionHelper.UnableToFindFieldException e) { e.printStackTrace(); return null; } } }
package org.cyclops.commoncapabilities.core; import net.minecraftforge.fml.relauncher.ReflectionHelper; import javax.annotation.Nullable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Helper methods. * @author rubensworks */ public class Helpers { public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) { if (method != null) { try { return (R) method.invoke(instance, arguments); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } return null; } public static <R> R getFieldValue(Object instance, @Nullable Field field) { if (field != null) { try { return (R) field.get(instance); } catch (IllegalAccessException e) { e.printStackTrace(); } } return null; } public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) { try { return ReflectionHelper.findMethod(clazz, null, new String[]{method}, methodTypes); } catch (ReflectionHelper.UnableToFindMethodException e) { e.printStackTrace(); return null; } } public static Field getField(Class<?> clazz, String field) { try { return ReflectionHelper.findField(clazz, field); } catch (ReflectionHelper.UnableToFindFieldException e) { e.printStackTrace(); return null; } } }
Work on trailing whitespace in code blocks.
<?php namespace FluxBB\Markdown\Node; use FluxBB\Markdown\Common\Collection; use FluxBB\Markdown\Common\Text; class CodeBlock extends Block implements NodeInterface, NodeAcceptorInterface { /** * @var Collection */ protected $lines; public function __construct(Text $text) { $this->lines = new Collection([$text->replace('/^[ ]{4}/', '')]); } public function getType() { return 'code_block'; } public function canContain(Node $other) { return true; } public function proposeTo(NodeAcceptorInterface $block) { return $block->acceptCodeBlock($this); } public function acceptBlankLine(BlankLine $blankLine) { $this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', '')); return $this; } public function acceptCodeBlock(CodeBlock $codeBlock) { $codeBlock->lines->each(function (Text $line) { $this->lines->add($line); }); return $this; } public function getContent() { $content = new Text($this->lines->join("\n")); // Just in case we added blank lines at the end, we remove them, and finally add back the trailing newline. $content->replace('/(\n[ ]*)*$/', '')->append("\n"); return $content; } public function visit(NodeVisitorInterface $visitor) { $visitor->visitCodeBlock($this); } }
<?php namespace FluxBB\Markdown\Node; use FluxBB\Markdown\Common\Collection; use FluxBB\Markdown\Common\Text; class CodeBlock extends Block implements NodeInterface, NodeAcceptorInterface { /** * @var Collection */ protected $lines; public function __construct(Text $text) { $this->lines = new Collection([$text->replace('/^[ ]{4}/', '')]); } public function getType() { return 'code_block'; } public function canContain(Node $other) { return true; } public function proposeTo(NodeAcceptorInterface $block) { return $block->acceptCodeBlock($this); } public function acceptBlankLine(BlankLine $blankLine) { $this->lines->add($blankLine->getContent()->replace('/^[ ]{0,4}/', '')); return $this; } public function acceptCodeBlock(CodeBlock $codeBlock) { $codeBlock->lines->each(function (Text $line) { $this->lines->add($line); }); return $this; } public function getContent() { return (new Text($this->lines->join("\n")))->rtrim()->append("\n"); } public function visit(NodeVisitorInterface $visitor) { $visitor->visitCodeBlock($this); } }
Add @deprecated annotation for getRows()
<?php namespace PeachySQL; /** * Contains rows, affected count, and the query string for a completed SQL query */ class SQLResult { /** * An array of rows selected in the query * @var array */ private $rows; /** * The number of rows affected by the query * @var int */ private $affected; /** * The SQL query * @var string */ private $query; /** * @param array $rows * @param int $affected * @param string $query */ public function __construct(array $rows, $affected, $query) { $this->rows = $rows; $this->affected = $affected; $this->query = $query; } /** * Returns all rows selected by the query * @return array */ public function getAll() { return $this->rows; } /** * Deprecated alias of getAll() * @deprecated since version 2.1.0 */ public function getRows() { return $this->getAll(); } /** * Returns the first selected row, or null if zero rows were returned * @return array */ public function getFirst() { return empty($this->rows) ? null : $this->rows[0]; } /** * Returns the number of rows affected by the query * @return int */ public function getAffected() { return $this->affected; } /** * Returns the SQL query * @return string */ public function getQuery() { return $this->query; } }
<?php namespace PeachySQL; /** * Contains rows, affected count, and the query string for a completed SQL query */ class SQLResult { /** * An array of rows selected in the query * @var array */ private $rows; /** * The number of rows affected by the query * @var int */ private $affected; /** * The SQL query * @var string */ private $query; /** * @param array $rows * @param int $affected * @param string $query */ public function __construct(array $rows, $affected, $query) { $this->rows = $rows; $this->affected = $affected; $this->query = $query; } /** * Returns all rows selected by the query * @return array */ public function getAll() { return $this->rows; } /** * Deprecated alias of getAll() */ public function getRows() { return $this->getAll(); } /** * Returns the first selected row, or null if zero rows were returned * @return array */ public function getFirst() { return empty($this->rows) ? null : $this->rows[0]; } /** * Returns the number of rows affected by the query * @return int */ public function getAffected() { return $this->affected; } /** * Returns the SQL query * @return string */ public function getQuery() { return $this->query; } }
[IDS] Fix IDs selector count result
<?php /* * This file was delivered to you as part of the Yucca package. * * (c) Rémi JANOT <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Yucca\Component\Selector; class Ids implements SelectorInterface { /** * @var array */ protected $ids; protected $keyName; /** * @param array $ids * @param string $keyName */ public function __construct(array $ids, $keyName = null) { $this->ids = $ids; $this->keyName = $keyName ; } /** * @return mixed */ public function current() { if(isset($this->keyName)) { return array($this->keyName => current($this->ids)); } else { return current($this->ids); } } /** * */ public function next() { next($this->ids); } /** * */ public function key() { return key($this->ids); } /** * */ public function valid() { return ( false !== current($this->ids) ); } /** * */ public function rewind() { reset($this->ids); } /** * */ public function count() { return count($this->ids); } /** * @return null */ public function currentShardingKey() { return null; } }
<?php /* * This file was delivered to you as part of the Yucca package. * * (c) Rémi JANOT <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Yucca\Component\Selector; class Ids implements SelectorInterface { /** * @var array */ protected $ids; protected $keyName; /** * @param array $ids * @param string $keyName */ public function __construct(array $ids, $keyName = null) { $this->ids = $ids; $this->keyName = $keyName ; } /** * @return mixed */ public function current() { if(isset($this->keyName)) { return array($this->keyName => current($this->ids)); } else { return current($this->ids); } } /** * */ public function next() { next($this->ids); } /** * */ public function key() { return key($this->ids); } /** * */ public function valid() { return ( false !== current($this->ids) ); } /** * */ public function rewind() { reset($this->ids); } /** * */ public function count() { count($this->ids); } /** * @return null */ public function currentShardingKey() { return null; } }
Fix syntax error, call authorized function
var app = require('http').createServer(handler), io = require('socket.io')(app), socketAuth = require('../lib/socket-handshake-authorization'), APP_PORT = 8000; function handler(req, res) { res.end('Hello World'); }; io.on('connection', function(socket) { console.log('A new Socket Connected'); console.log('SocketID [%s]', socket.id); var authorize = function(data) { return (data.user == 'felipe' && data.pass == 'abc123') ? true : false; }; socketAuth.auth({ socket: socket, authorize: authorize, method: 'auth' }).listen(AuthScope); socket.on('disconnect', function() { console.log('SockedID [%s] is disconnected', socket.id); }); }); function AuthScope(socket, authorized) { socket.on('message', function(value) { if (!authorized.status) { console.log('Unauthorized!'); return; } console.log('receveid', value); }); var interval = setInterval(function() { if( !authorized.status ) { clearInterval(interval); return; } socket.emit('message', 'Ola mundo'); }, 5000); }; app.listen(APP_PORT); console.log('APP run in [%s] port', APP_PORT);
var app = require('http').createServer(handler), io = require('socket.io')(app), socketAuth = require('../lib/socket-handshake-authorization'), APP_PORT = 8000; function handler(req, res) { res.end('Hello World'); }; io.on('connection', function(socket) { console.log('A new Socket Connected'); console.log('SocketID [%s]', socket.id); var AuthorizeOne = function(data) { return (data.user == 'felipe' && data.pass == 'abc123') ? true : false; }; socketAuth.auth({ socket: socket, authorize: auth, method: 'auth' }).listen(AuthScope); socket.on('disconnect', function() { console.log('SockedID [%s] is disconnected', socket.id); }); }); function AuthScope(socket, authorized) { socket.on('message', function(value) { if (!authorized.status) { console.log('Unauthorized!'); return; } console.log('receveid', value); }); var interval = setInterval(function() { if( !authorized.status ) { clearInterval(interval); return; } socket.emit('message', 'Ola mundo'); }, 5000); }; app.listen(APP_PORT); console.log('APP run in [%s] port', APP_PORT);
Fix when locale is invalid after first guess
<?php namespace Kunstmaan\LanguageChooserBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LanguageChooserController extends Controller { /** * Handles the language chooser * * @return Response the request response */ public function indexAction() { $enableAutodetect = $this->container->getParameter('autodetectlanguage'); $enableSplashpage = $this->container->getParameter('showlanguagechooser'); $defaultLocale = $this->container->getParameter('defaultlocale'); if ($enableAutodetect) { $localeGuesserManager = $this->get('lunetics_locale.guesser_manager'); $request = $this->getRequest(); $locale = $localeGuesserManager->runLocaleGuessing($request); if ($locale) { //locale returned will in the form of en_US, we need en $locale = locale_get_primary_language($locale); } // locale has been found, redirect if ($locale) { return $this->redirect($this->generateUrl('_slug', array('_locale' => $locale)), 302); } else { // no locale could be guessed, if splashpage is not enabled fallback to default and redirect if (!$enableSplashpage) { return $this->redirect($this->generateUrl('_slug', array('_locale' => $defaultLocale)), 302); } } } if ($enableSplashpage) { $viewPath = $this->container->getParameter('languagechoosertemplate'); return $this->render($viewPath); } } }
<?php namespace Kunstmaan\LanguageChooserBundle\Controller; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LanguageChooserController extends Controller { /** * Handles the language chooser * * @return Response the request response */ public function indexAction() { $enableAutodetect = $this->container->getParameter('autodetectlanguage'); $enableSplashpage = $this->container->getParameter('showlanguagechooser'); $defaultLocale = $this->container->getParameter('defaultlocale'); if ($enableAutodetect) { $localeGuesserManager = $this->get('lunetics_locale.guesser_manager'); $request = $this->getRequest(); $locale = $localeGuesserManager->runLocaleGuessing($request); //locale returned will in the form of en_US, we need en $locale = locale_get_primary_language($locale); // locale has been found, redirect if ($locale) { return $this->redirect($this->generateUrl('_slug', array('_locale' => $locale)), 302); } else { // no locale could be guessed, if splashpage is not enabled fallback to default and redirect if (!$enableSplashpage) { return $this->redirect($this->generateUrl('_slug', array('_locale' => $defaultLocale)), 302); } } } if ($enableSplashpage) { $viewPath = $this->container->getParameter('languagechoosertemplate'); return $this->render($viewPath); } } }
Update reviews model for new added field in 5.5
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() ip_address = models.CharField(max_length=255, default='0.0.0.0') editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
import itertools from django.db import models import amo from translations.fields import TranslatedField from translations.models import Translation class Review(amo.ModelBase): version = models.ForeignKey('versions.Version') user = models.ForeignKey('users.UserProfile') reply_to = models.ForeignKey('self', null=True, unique=True, db_column='reply_to') rating = models.PositiveSmallIntegerField(null=True) title = TranslatedField() body = TranslatedField() editorreview = models.BooleanField(default=False) flag = models.BooleanField(default=False) sandbox = models.BooleanField(default=False) class Meta: db_table = 'reviews' def fetch_translations(self, ids, lang): if not ids: return [] rv = {} ts = Translation.objects.filter(id__in=ids) # If a translation exists for the current language, use it. Otherwise, # make do with whatever is available. (Reviewers only write reviews in # their language). for id, translations in itertools.groupby(ts, lambda t: t.id): locales = dict((t.locale, t) for t in translations) if lang in locales: rv[id] = locales[lang] else: rv[id] = locales.itervalues().next() return rv.values()
Allow meta value to be NULL
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account meta table. * * @author Gawain Lynch <[email protected]> */ class AccountMeta extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('id', 'integer', ['autoincrement' => true]); $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('meta', 'string', ['length' => 64]); $this->table->addColumn('value', 'text', ['notnull' => false, 'default' => null]); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addIndex(['guid']); $this->table->addIndex(['meta']); $this->table->addUniqueIndex(['guid', 'meta']); // Temporary until done upstream $this->addForeignKeyConstraint(); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['id']); } /** * @inheritDoc */ protected function addForeignKeyConstraint() { $this->table->addForeignKeyConstraint('bolt_members_account', ['guid'], ['guid'], [], 'guid'); } }
<?php namespace Bolt\Extension\Bolt\Members\Storage\Schema\Table; use Bolt\Storage\Database\Schema\Table\BaseTable; /** * Account meta table. * * @author Gawain Lynch <[email protected]> */ class AccountMeta extends BaseTable { /** * @inheritDoc */ protected function addColumns() { $this->table->addColumn('id', 'integer', ['autoincrement' => true]); $this->table->addColumn('guid', 'guid', []); $this->table->addColumn('meta', 'string', ['length' => 64]); $this->table->addColumn('value', 'text'); } /** * @inheritDoc */ protected function addIndexes() { $this->table->addIndex(['guid']); $this->table->addIndex(['meta']); $this->table->addUniqueIndex(['guid', 'meta']); // Temporary until done upstream $this->addForeignKeyConstraint(); } /** * @inheritDoc */ protected function setPrimaryKey() { $this->table->setPrimaryKey(['id']); } /** * @inheritDoc */ protected function addForeignKeyConstraint() { $this->table->addForeignKeyConstraint('bolt_members_account', ['guid'], ['guid'], [], 'guid'); } }
Allow embedding groups in groups
import { Immutable } from 'nuclear-js'; import { getters as entityGetters } from '../entity'; const DEFAULT_VIEW_ENTITY_ID = 'group.default_view'; export const currentView = [ 'currentView', ]; export const views = [ entityGetters.entityMap, entities => entities.filter(entity => entity.domain === 'group' && entity.attributes.view && entity.entityId !== DEFAULT_VIEW_ENTITY_ID), ]; function addToMap(map, entities, groupEntity, recurse = true) { groupEntity.attributes.entity_id.forEach(entityId => { if (map.has(entityId)) return; const entity = entities.get(entityId); if (!entity || entity.attributes.hidden) return; map.set(entityId, entity); if (entity.domain === 'group' && recurse) { addToMap(map, entities, entity, false); } }); } export const currentViewEntities = [ entityGetters.entityMap, currentView, (entities, view) => { let viewEntity; if (view) { viewEntity = entities.get(view); } else { // will be undefined if entity does not exist viewEntity = entities.get(DEFAULT_VIEW_ENTITY_ID); } if (!viewEntity) { return entities.filter(entity => !entity.attributes.hidden); } return (new Immutable.Map()).withMutations(map => { addToMap(map, entities, viewEntity); }); }, ];
import { Immutable } from 'nuclear-js'; import { getters as entityGetters } from '../entity'; const DEFAULT_VIEW_ENTITY_ID = 'group.default_view'; export const currentView = [ 'currentView', ]; export const views = [ entityGetters.entityMap, entities => entities.filter(entity => entity.domain === 'group' && entity.attributes.view && entity.entityId !== DEFAULT_VIEW_ENTITY_ID), ]; function addToMap(map, entities, groupEntity) { groupEntity.attributes.entity_id.forEach(entityId => { if (map.has(entityId)) return; const entity = entities.get(entityId); if (!entity || entity.attributes.hidden) return; map.set(entityId, entity); if (entity.domain === 'group') { addToMap(map, entities, entity); } }); } export const currentViewEntities = [ entityGetters.entityMap, currentView, (entities, view) => { let viewEntity; if (view) { viewEntity = entities.get(view); } else { // will be undefined if entity does not exist viewEntity = entities.get(DEFAULT_VIEW_ENTITY_ID); } if (!viewEntity) { return entities.filter(entity => !entity.attributes.hidden); } return (new Immutable.Map()).withMutations(map => { addToMap(map, entities, viewEntity); }); }, ];
Fix problem with Python 2 to 3
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import gettext import eventlet import os from stand.socketio_events import StandSocketIO locales_path = os.path.join(os.path.dirname(__file__), '..', 'i18n', 'locales') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, help="Config file", required=True) parser.add_argument("--lang", help="Minion messages language (i18n)", required=False, default="en_US") args = parser.parse_args() eventlet.monkey_patch(all=True) from stand.factory import create_app, create_babel_i18n, \ create_redis_store t = gettext.translation('messages', locales_path, [args.lang], fallback=True) t.install() app = create_app(config_file=args.config) babel = create_babel_i18n(app) # socketio, socketio_app = create_socket_io_app(app) stand_socket_io = StandSocketIO(app) redis_store = create_redis_store(app) port = int(app.config['STAND_CONFIG'].get('port', 5000)) if app.debug: app.run(debug=True, port=port) else: # noinspection PyUnresolvedReferences eventlet.wsgi.server(eventlet.listen(('', port)), stand_socket_io.socket_app)
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import gettext import eventlet import os from stand.socketio_events import StandSocketIO locales_path = os.path.join(os.path.dirname(__file__), '..', 'i18n', 'locales') if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, help="Config file", required=True) parser.add_argument("--lang", help="Minion messages language (i18n)", required=False, default="en_US") args = parser.parse_args() eventlet.monkey_patch(all=True) from stand.factory import create_app, create_babel_i18n, \ create_redis_store t = gettext.translation('messages', locales_path, [args.lang], fallback=True) t.install(str=True) app = create_app(config_file=args.config) babel = create_babel_i18n(app) # socketio, socketio_app = create_socket_io_app(app) stand_socket_io = StandSocketIO(app) redis_store = create_redis_store(app) if app.debug: app.run(debug=True) else: port = int(app.config['STAND_CONFIG'].get('port', 5000)) # noinspection PyUnresolvedReferences eventlet.wsgi.server(eventlet.listen(('', port)), stand_socket_io.socket_app)
Add icalendar stragegy to service manager
<?php /** * * Spork Zend Framework 2 Library * * @author Chris Schreiber <[email protected]> */ return array( 'service_manager' => array( 'abstract_factories' => array(), 'aliases' => array(), 'factories' => array( 'cssLess' => 'Spork\CSS\Less', 'cssSass' => 'Spork\CSS\Sass', 'cssStylus' => 'Spork\CSS\Stylus', ), 'invokables' => array( 'IcalendarViewStrategy' => 'Spork\View\Strategy\Icalendar', ), ), 'view_helpers' => array( 'invokables' => array( 'date' => 'Spork\View\Helper\Date', 'headScript' => 'Spork\View\Helper\HeadScript', 'inlineScript' => 'Spork\View\Helper\InlineScript', 'cssLess' => 'Spork\View\Helper\CSS\Less', 'cssSass' => 'Spork\View\Helper\CSS\Sass', 'cssStylus' => 'Spork\View\Helper\CSS\Stylus', 'tagTrim' => 'Spork\View\Helper\TagTrim', 'timeElapsed' => 'Spork\View\Helper\TimeElapsed', ), 'factories' => array( 'dojo' => 'Spork\View\Helper\Dojo', 'googleAnalytic' => 'Spork\View\Helper\GoogleAnalytic', ) ) );
<?php /** * * Spork Zend Framework 2 Library * * @author Chris Schreiber <[email protected]> */ return array( 'service_manager' => array( 'abstract_factories' => array(), 'aliases' => array(), 'factories' => array( 'cssLess' => 'Spork\CSS\Less', 'cssSass' => 'Spork\CSS\Sass', 'cssStylus' => 'Spork\CSS\Stylus', ), 'invokables' => array(), ), 'view_helpers' => array( 'invokables' => array( 'date' => 'Spork\View\Helper\Date', 'headScript' => 'Spork\View\Helper\HeadScript', 'inlineScript' => 'Spork\View\Helper\InlineScript', 'cssLess' => 'Spork\View\Helper\CSS\Less', 'cssSass' => 'Spork\View\Helper\CSS\Sass', 'cssStylus' => 'Spork\View\Helper\CSS\Stylus', 'tagTrim' => 'Spork\View\Helper\TagTrim', 'timeElapsed' => 'Spork\View\Helper\TimeElapsed', ), 'factories' => array( 'dojo' => 'Spork\View\Helper\Dojo', 'googleAnalytic' => 'Spork\View\Helper\GoogleAnalytic', ) ) );
Check element before get an innerHTML
/*! Copyright (C) 2017 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function(can) { can.extend(can.Control.prototype, { // Returns a function which will be halted unless `this.element` exists // - useful for callbacks which depend on the controller's presence in // the DOM _ifNotRemoved: function(fn) { var that = this; return function() { if (!that.element) { return; } return fn.apply(this, arguments); }; }, //make buttons non-clickable when saving bindXHRToButton : function(xhr, el, newtext, disable) { // binding of an ajax to a click is something we do manually var $el = $(el); var oldtext = $el[0] ? $el[0].innerHTML : ''; if(newtext) { $el[0].innerHTML = newtext; } $el.addClass("disabled pending-ajax"); if (disable !== false) { $el.attr("disabled", true); } xhr.always(function() { // If .text(str) is used instead of innerHTML, the click event may not fire depending on timing if ($el.length) { $el.removeAttr("disabled").removeClass("disabled pending-ajax")[0].innerHTML = oldtext; } }); } }); })(this.can);
/*! Copyright (C) 2017 Google Inc. Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> */ (function(can) { can.extend(can.Control.prototype, { // Returns a function which will be halted unless `this.element` exists // - useful for callbacks which depend on the controller's presence in // the DOM _ifNotRemoved: function(fn) { var that = this; return function() { if (!that.element) { return; } return fn.apply(this, arguments); }; }, //make buttons non-clickable when saving bindXHRToButton : function(xhr, el, newtext, disable) { // binding of an ajax to a click is something we do manually var $el = $(el); var oldtext = $el[0].innerHTML; if(newtext) { $el[0].innerHTML = newtext; } $el.addClass("disabled pending-ajax"); if (disable !== false) { $el.attr("disabled", true); } xhr.always(function() { // If .text(str) is used instead of innerHTML, the click event may not fire depending on timing if ($el.length) { $el.removeAttr("disabled").removeClass("disabled pending-ajax")[0].innerHTML = oldtext; } }); } }); })(this.can);
Edit view pre-populates with data from user object
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404, HttpResponseRedirect from django.core.urlresolvers import reverse def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) return render_to_response('people/profile.html', {"commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user form = EditUserForm(request.POST or None, user=request.user) if form.is_valid(): for key in form.cleaned_data: setattr(user, key, form.cleaned_data.get(key)) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username':request.user.username}) ) if user == None: raise Http404("User not found") return render_to_response(template_name, {'form':form}, RequestContext(request))
from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template.context import RequestContext #from google.appengine.ext import db from july.people.models import Commit from gae_django.auth.models import User from django.http import Http404, HttpResponseRedirect from django.core.urlresolvers import reverse def user_profile(request, username): user = User.all().filter("username", username).get() if user == None: raise Http404("User not found") commits = Commit.all().ancestor(request.user.key()) return render_to_response('people/profile.html', {"commits":commits}, RequestContext(request)) @login_required def edit_profile(request, username, template_name='people/edit.html'): from forms import EditUserForm user = request.user #CONSIDER FILES with no POST? Can that happen? form = EditUserForm(request.POST or None, request.FILES or None) if form.is_valid(): for key in form.cleaned_data: setattr(user,key,form.cleaned_data.get(key)) user.put() return HttpResponseRedirect( reverse('member-profile', kwargs={'username': request.user.username}) ) if user == None: raise Http404("User not found") return render_to_response(template_name, {'form':form,}, RequestContext(request))
Fix lecturer lecture page being accessible to everyone
(function() { 'use strict'; angular .module('lecturer') .config(config); /* ngInject */ function config($routeProvider, $httpProvider) { console.log('Ready (Providers)'); $routeProvider .when('/', { templateUrl: 'app/login/login.html', controller: 'LoginCtrl', controllerAs: 'vm', loginRequired: false }) .when('/register', { templateUrl: 'app/register/register.html', controller: 'RegisterCtrl', controllerAs: 'vm', loginRequired: false }) .when('/courses', { templateUrl: 'app/courses/courses.html', controller: 'CoursesCtrl', controllerAs: 'vm', loginRequired: true }) .when('/lectures', { templateUrl: 'app/lectures/lectures.html', controller: 'LecturesCtrl', controllerAs: 'vm', loginRequired: true }) .when('/lectures/:lectureId', { templateUrl: 'app/lecture/lecture.html', controller: 'LectureCtrl', controllerAs: 'vm', loginRequired: true }) .otherwise({ redirectTo: '/' }); $httpProvider.interceptors.push('apiInterceptor'); } })();
(function() { 'use strict'; angular .module('lecturer') .config(config); /* ngInject */ function config($routeProvider, $httpProvider) { console.log('Ready (Providers)'); $routeProvider .when('/', { templateUrl: 'app/login/login.html', controller: 'LoginCtrl', controllerAs: 'vm', loginRequired: false }) .when('/register', { templateUrl: 'app/register/register.html', controller: 'RegisterCtrl', controllerAs: 'vm', loginRequired: false }) .when('/courses', { templateUrl: 'app/courses/courses.html', controller: 'CoursesCtrl', controllerAs: 'vm', loginRequired: true }) .when('/lectures', { templateUrl: 'app/lectures/lectures.html', controller: 'LecturesCtrl', controllerAs: 'vm', loginRequired: true }) .when('/lectures/:lectureId', { templateUrl: 'app/lecture/lecture.html', controller: 'LectureCtrl', controllerAs: 'vm' }) .otherwise({ redirectTo: '/' }); $httpProvider.interceptors.push('apiInterceptor'); } })();
Allow custom theme lib directories using .libcfg
<?php namespace CupOfTea\WordPress\Foundation\Bootstrap; use Illuminate\Support\Str; use Illuminate\Contracts\Container\Container; class RegisterThemeAutoloader { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Container $app) { if (! $app->bound('composer')) { $composer = new \Composer\Autoload\ClassLoader(); $composer->register(true); $app->instance('composer', $composer); } $composer = $app->make('composer'); $themeDir = get_template_directory(); $namespace = Str::studly(wp_get_theme()->Name) . '\\'; $path = []; foreach (['lib', 'library'] as $directory) { $fullPath = $themeDir . '/' . $directory; if (file_exists($fullPath) && is_dir($fullPath)) { $path[] = $fullPath; } } $libcfg = $themeDir . '/.libcfg'; if (file_exists($libcfg) && is_file($libcfg)) { $libcfg = array_filter(array_map('trim', explode(PHP_EOL, $cfg))); $path = array_merge($path, $libcfg); } $composer->addPsr4($namespace, $path); } }
<?php namespace CupOfTea\WordPress\Foundation\Bootstrap; use Illuminate\Support\Str; use Illuminate\Contracts\Container\Container; class RegisterThemeAutoloader { /** * Bootstrap the given application. * * @param \Illuminate\Contracts\Foundation\Application $app * @return void */ public function bootstrap(Container $app) { if (! $app->bound('composer')) { $composer = new \Composer\Autoload\ClassLoader(); $composer->register(true); $app->instance('composer', $composer); } $composer = $app->make('composer'); $themeDir = get_template_directory(); $namespace = Str::studly(wp_get_theme()->Name) . '\\'; $path = []; foreach (['lib', 'library'] as $directory) { $fullPath = $themeDir . '/' . $directory; if (file_exists($fullPath) && is_dir($fullPath)) { $path[] = $fullPath; } } $composer->addPsr4($namespace, $path); } }
Fix where from query builder
<?php namespace App\Validators; use Valitron\Validator; use Illuminate\Database\Capsule\Manager as DB; abstract class AbstractValidator { protected $validator; public function __construct(Validator $validator) { $this->addCustomRules(); $this->validator = $validator; } abstract public function rules(); public function errors() { return $this->validator->errors(); } public function validate() { foreach ($this->rules() as $rule) { $args = array_splice($rule, 0, count($rule), true); call_user_func_array([$this->validator, 'rule'], $args); } return $this->validator->validate(); } private function addCustomRules() { Validator::addRule('unique', function ($field, $value, array $params, $fields) { foreach ($params[0] as $table => $column) { if ($result = DB::table($table)->where($column, '=', $value)->get()) { return false; } } return true; }, 'must be unique in our database'); Validator::addRule('exists', function ($field, $value, array $params, $fields) { foreach ($params[0] as $table => $column) { if (! $result = DB::table($table)->where($column, '=', $value)->get()) { return false; } } return true; }, 'must exists in our database'); } }
<?php namespace App\Validators; use Valitron\Validator; use Illuminate\Database\Capsule\Manager as DB; abstract class AbstractValidator { protected $validator; public function __construct(Validator $validator) { $this->addCustomRules(); $this->validator = $validator; } abstract public function rules(); public function errors() { return $this->validator->errors(); } public function validate() { foreach ($this->rules() as $rule) { $args = array_splice($rule, 0, count($rule), true); call_user_func_array([$this->validator, 'rule'], $args); } return $this->validator->validate(); } private function addCustomRules() { Validator::addRule('unique', function ($field, $value, array $params, $fields) { foreach ($params[0] as $table => $column) { if ($result = DB::table($table)->where($column, $value)->get()->toArray()) { return false; } } return true; }, 'must be unique in our database'); Validator::addRule('exists', function ($field, $value, array $params, $fields) { foreach ($params[0] as $table => $column) { if (! $result = DB::table($table)->where($column, $value)->get()->toArray()) { return false; } } return true; }, 'must exists in our database'); } }
Allow "Magic Home" to be hidden Summary: Ref T12174. Fallback behavior on this already appears to be sensible. Test Plan: - Hid "Magic Home". - Viewed homepage with no dashboards on the menu. - Saw "Magic Home" content, with no item in the menu selected, which seems reasonable. {F2557022} Reviewers: chad Reviewed By: chad Maniphest Tasks: T12174 Differential Revision: https://secure.phabricator.com/D17289
<?php final class PhabricatorHomeProfileMenuItem extends PhabricatorProfileMenuItem { const MENUITEMKEY = 'home.dashboard'; public function getMenuItemTypeName() { return pht('Home'); } private function getDefaultName() { return pht('Home'); } public function canMakeDefault( PhabricatorProfileMenuItemConfiguration $config) { return true; } public function getDisplayName( PhabricatorProfileMenuItemConfiguration $config) { $name = $config->getMenuItemProperty('name'); if (strlen($name)) { return $name; } return $this->getDefaultName(); } public function newPageContent() { $viewer = $this->getViewer(); return id(new PHUIHomeView()) ->setViewer($viewer); } public function buildEditEngineFields( PhabricatorProfileMenuItemConfiguration $config) { return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setPlaceholder($this->getDefaultName()) ->setValue($config->getMenuItemProperty('name')), ); } protected function newNavigationMenuItems( PhabricatorProfileMenuItemConfiguration $config) { $viewer = $this->getViewer(); $name = $this->getDisplayName($config); $icon = 'fa-home'; $href = $this->getItemViewURI($config); $item = $this->newItem() ->setHref($href) ->setName($name) ->setIcon($icon); return array( $item, ); } }
<?php final class PhabricatorHomeProfileMenuItem extends PhabricatorProfileMenuItem { const MENUITEMKEY = 'home.dashboard'; public function getMenuItemTypeName() { return pht('Home'); } private function getDefaultName() { return pht('Home'); } public function canHideMenuItem( PhabricatorProfileMenuItemConfiguration $config) { return false; } public function canMakeDefault( PhabricatorProfileMenuItemConfiguration $config) { return true; } public function getDisplayName( PhabricatorProfileMenuItemConfiguration $config) { $name = $config->getMenuItemProperty('name'); if (strlen($name)) { return $name; } return $this->getDefaultName(); } public function newPageContent() { $viewer = $this->getViewer(); return id(new PHUIHomeView()) ->setViewer($viewer); } public function buildEditEngineFields( PhabricatorProfileMenuItemConfiguration $config) { return array( id(new PhabricatorTextEditField()) ->setKey('name') ->setLabel(pht('Name')) ->setPlaceholder($this->getDefaultName()) ->setValue($config->getMenuItemProperty('name')), ); } protected function newNavigationMenuItems( PhabricatorProfileMenuItemConfiguration $config) { $viewer = $this->getViewer(); $name = $this->getDisplayName($config); $icon = 'fa-home'; $href = $this->getItemViewURI($config); $item = $this->newItem() ->setHref($href) ->setName($name) ->setIcon($icon); return array( $item, ); } }
Simplify client, remove unneeded init method
<?php namespace React\Whois; use React\Async\Util as Async; use React\Curry\Util as Curry; use React\Dns\Resolver\Resolver; class Client { private $resolver; private $connFactory; public function __construct(Resolver $resolver, $connFactory) { $this->resolver = $resolver; $this->connFactory = $connFactory; } public function query($domain, $callback) { Async::waterfall( array( Curry::bind(array($this, 'resolveWhoisServer'), $domain), Curry::bind(array($this, 'queryWhoisServer'), $domain), ), $callback ); } public function resolveWhoisServer($domain, $callback) { $tld = substr(strrchr($domain, '.'), 1); $target = $tld.'.whois-servers.net'; $this->resolver->resolve($target, $callback); } public function queryWhoisServer($domain, $ip, $callback) { $result = ''; $conn = call_user_func($this->connFactory, $ip); $conn->write("$domain\r\n"); $conn->on('data', function ($data) use (&$result) { $result .= $data; }); $conn->on('close', function () use (&$result, $callback) { $result = str_replace("\r\n", "\n", $result); $callback($result); }); } }
<?php namespace React\Whois; use React\Async\Util as Async; use React\Curry\Util as Curry; use React\Dns\Resolver\Resolver; class Client { private $resolver; private $connFactory; public function __construct(Resolver $resolver, $connFactory) { $this->resolver = $resolver; $this->connFactory = $connFactory; } public function query($domain, $callback) { Async::waterfall( array( Curry::bind(array($this, 'init'), $domain), array($this, 'resolveWhoisServer'), Curry::bind(array($this, 'queryWhoisServer'), $domain), ), $callback ); } public function init($domain, $callback) { $callback($domain); } public function resolveWhoisServer($domain, $callback) { $tld = substr(strrchr($domain, '.'), 1); $target = $tld.'.whois-servers.net'; $this->resolver->resolve($target, $callback); } public function queryWhoisServer($domain, $ip, $callback) { $result = ''; $conn = call_user_func($this->connFactory, $ip); $conn->write("$domain\r\n"); $conn->on('data', function ($data) use (&$result) { $result .= $data; }); $conn->on('close', function () use (&$result, $callback) { $result = str_replace("\r\n", "\n", $result); $callback($result); }); } }
Add flow to PlayerSelect and clean up
/* @flow */ import React, { Component } from 'react'; import { Text, View, ScrollView, Image, Alert } from 'react-native'; import MyButton from '../../../MyButton'; import Input from '../../../Input'; import List from '../../../List'; export class PlayerSelect extends Component { static navigationOptions = { title: "New Game", }; state = { players: ['Hannah', 'Markus', 'Tobi', 'Lo', 'Moritz'], }; onAddPlayer = (text: string) => { const {players} = this.state if(players.indexOf(text) > -1){ Alert.alert( 'Info', `Player ${text} already exists`, [ {text: 'OK', onPress: () => {}} ], { cancelable: true } ) } else { this.setState({ players: [text, ...players], }) } } onRemovePlayer = (index: number) => { const {players} = this.state this.setState({ players: players.filter((player, i) => i !== index), }) } render() { const {players} = this.state const { navigate } = this.props.navigation return ( <ScrollView> <Input onSubmitEditing={this.onAddPlayer} placeholder='Add players... Remove by tapping on them.' /> <List list={players} onPressItem={this.onRemovePlayer} /> <MyButton text="Select Teams" onPress={()=>navigate('Team', {players: players})} /> </ScrollView> ); } };
import React, { Component } from 'react'; import { StyleSheet, Text, View, ScrollView, Image, Alert } from 'react-native'; import MyButton from '../../../MyButton'; import Input from '../../../Input'; import List from '../../../List'; export class PlayerSelect extends Component { static navigationOptions = { title: "New Game", }; state = { players: ['Hannah', 'Markus', 'Tobi', 'Lo', 'Moritz'], }; onAddPlayer = (text) => { const {players} = this.state if(players.indexOf(text) > -1){ Alert.alert( 'Info', `Player ${text} already exists`, [ {text: 'OK', onPress: () => {}} ], { cancelable: true } ) } else { this.setState({ players: [text, ...players], }) } } onRemovePlayer = (index) => { const {players} = this.state this.setState({ players: players.filter((player, i) => i !== index), }) } render() { const {players} = this.state const { navigate } = this.props.navigation return ( <ScrollView> <Input onSubmitEditing={this.onAddPlayer} style={styles.input} placeholder='Add players... Remove by tapping on them.' /> <List list={players} onPressItem={this.onRemovePlayer} /> <MyButton text="Select Teams" onPress={()=>navigate('Team', {players: players})} /> </ScrollView> ); } }; const styles = StyleSheet.create({ });
Fix for test (add mock for CommCareUser)
from datetime import date from unittest import TestCase from mock import patch from corehq.apps.users.models import CommCareUser from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows @patch.object(CommCareUser, 'by_domain', return_value=[]) def test_basic_CMR(self, user_mock): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
from datetime import date from unittest import TestCase from couchforms.models import XFormInstance from ..constants import * from ..reports import get_report, BeneficiaryPaymentReport, MetReport from .case_reports import Report, OPMCase, MockCaseRow, MockDataProvider class TestGetReportUtil(TestCase): def get_report_class(self, report_class): obj_dict = { 'get_rows': lambda slf, datespan: [ OPMCase( forms=[], edd=date(2014, 11, 10), ), OPMCase( forms=[], dod=date(2014, 1, 12), ), OPMCase( forms=[], dod=date(2014, 3, 12), ), ], 'data_provider': MockDataProvider(), } return type(report_class.__name__, (Report, report_class), obj_dict) def test_basic_BPR(self): report_class = self.get_report_class(BeneficiaryPaymentReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows def test_basic_CMR(self): report_class = self.get_report_class(MetReport) report = get_report(report_class, month=6, year=2014, block="Atri") report.rows
Use constants for model configuration
<?php /** * This class manages content in the "nails_comment" table. * * @package Nails * @subpackage module-comment * @category Model * @author Nails Dev Team * @link https://docs.nailsapp.co.uk/modules/other/comment */ namespace Nails\Comment\Model; use Nails\Comment\Constants; use Nails\Common\Exception\ModelException; use Nails\Common\Model\Base; /** * Class Comment * * @package Nails\Comment\Model */ class Comment extends Base { /** * The table this model represents * * @var string */ const TABLE = NAILS_DB_PREFIX . 'comment'; /** * The name of the resource to use (as passed to \Nails\Factory::resource()) * * @var string */ const RESOURCE_NAME = 'Comment'; /** * The provider of the resource to use (as passed to \Nails\Factory::resource()) * * @var string */ const RESOURCE_PROVIDER = Constants::MODULE_SLUG; /** * The default column to sort on * * @var string|null */ const DEFAULT_SORT_COLUMN = 'created'; // -------------------------------------------------------------------------- /** * Comment constructor. * * @throws ModelException */ public function __construct() { parent::__construct(); $this ->hasMany('flags', 'CommentFlag', 'comment_id', Constants::MODULE_SLUG) ->hasMany('votes', 'CommentVote', 'comment_id', Constants::MODULE_SLUG); } }
<?php /** * This class manages content in the "nails_comment" table. * * @package Nails * @subpackage module-comment * @category Model * @author Nails Dev Team * @link https://docs.nailsapp.co.uk/modules/other/comment */ namespace Nails\Comment\Model; use Nails\Comment\Constants; use Nails\Common\Exception\ModelException; use Nails\Common\Model\Base; /** * Class Comment * * @package Nails\Comment\Model */ class Comment extends Base { /** * The table this model represents * * @var string */ const TABLE = NAILS_DB_PREFIX . 'comment'; /** * The name of the resource to use (as passed to \Nails\Factory::resource()) * * @var string */ const RESOURCE_NAME = 'Comment'; /** * The provider of the resource to use (as passed to \Nails\Factory::resource()) * * @var string */ const RESOURCE_PROVIDER = Constants::MODULE_SLUG; // -------------------------------------------------------------------------- /** * Comment constructor. * * @throws ModelException */ public function __construct() { parent::__construct(); $this->defaultSortColumn = $this->getColumn('created'); $this ->hasMany('flags', 'CommentFlag', 'comment_id', Constants::MODULE_SLUG) ->hasMany('votes', 'CommentVote', 'comment_id', Constants::MODULE_SLUG); } }
Remove route inclusion from service provider
<?php namespace Sztyup\Authsch; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Support\ServiceProvider; class AuthschServiceProvider extends ServiceProvider { public function register() { $this->mergeConfigFrom( __DIR__.'/../config/config.php', 'authsch' ); $this->loadMigrationsFrom( __DIR__ . '/../migrations' ); } public function boot() { $this->publishes([ __DIR__ . '/../config/config.php' => config_path('authsch.php') ], 'config'); $socialite = $this->app->make('Laravel\Socialite\Contracts\Factory'); $socialite->extend( 'authsch', function (Container $app) { return new SchProvider( $app->make('request'), $app->make(UrlGenerator::class), $app->make('config')->get('authsch') ); } ); $socialite->extend( 'authsch-bme', function (Container $app) { return new BmeProvider( $app->make('request'), $app->make(UrlGenerator::class), $app->make('config')->get('authsch') ); } ); } }
<?php namespace Sztyup\Authsch; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Support\ServiceProvider; class AuthschServiceProvider extends ServiceProvider { public function register() { $this->loadRoutesFrom(__DIR__ . '/../routes/routes.php'); $this->mergeConfigFrom( __DIR__.'/../config/config.php', 'authsch' ); $this->loadMigrationsFrom( __DIR__ . '/../migrations' ); } public function boot() { $this->publishes([ __DIR__ . '/../config/config.php' => config_path('authsch.php') ], 'config'); $socialite = $this->app->make('Laravel\Socialite\Contracts\Factory'); $socialite->extend( 'authsch', function (Container $app) { return new SchProvider( $app->make('request'), $app->make(UrlGenerator::class), $app->make('config')->get('authsch') ); } ); $socialite->extend( 'authsch-bme', function (Container $app) { return new BmeProvider( $app->make('request'), $app->make(UrlGenerator::class), $app->make('config')->get('authsch') ); } ); } }
:bug: Fix Sass syntax final newline rule bug
'use strict'; var helpers = require('../helpers'), os = require('os'); module.exports = { 'name': 'final-newline', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = [], last = ast.content[ast.content.length - 1], error = { 'ruleId': parser.rule.name, 'severity': parser.severity }; if (ast.syntax === 'sass') { if (typeof last.last('block') === 'object') { var lastBlock = last.last('block'); if (lastBlock.content.length > 0) { if (lastBlock.content[lastBlock.length - 1]) { last = lastBlock.content[lastBlock.length - 1]; } } } } if (last.type !== 'space') { if (parser.options.include) { error.line = last.end.line; error.column = last.end.column; error.message = 'Files must end with a new line'; result = helpers.addUnique(result, error); } } else { if (last.content !== os.EOL && parser.options.include) { error.line = last.start.line; error.column = last.start.column; error.message = 'Files must end with a new line'; result = helpers.addUnique(result, error); } else if (last.content === os.EOL && !parser.options.include) { error.line = last.start.line; error.column = last.start.column; error.message = 'Files must not end with a new line'; result = helpers.addUnique(result, error); } } return result; } };
'use strict'; var helpers = require('../helpers'), os = require('os'); module.exports = { 'name': 'final-newline', 'defaults': { 'include': true }, 'detect': function (ast, parser) { var result = [], last = ast.content[ast.content.length - 1], error = { 'ruleId': parser.rule.name, 'severity': parser.severity }; if (last.type !== 'space') { if (parser.options.include) { error.line = last.end.line; error.column = last.end.column; error.message = 'Files must end with a new line'; result = helpers.addUnique(result, error); } } else { if (last.content !== os.EOL && parser.options.include) { error.line = last.start.line; error.column = last.start.column; error.message = 'Files must end with a new line'; result = helpers.addUnique(result, error); } else if (last.content === os.EOL && !parser.options.include) { error.line = last.start.line; error.column = last.start.column; error.message = 'Files must not end with a new line'; result = helpers.addUnique(result, error); } } return result; } };
Add mock to test extras
from setuptools import setup, find_packages # Parse the version from the mapbox module. with open('mapboxcli/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue setup(name='mapboxcli', version=version, description="Command line interface to Mapbox Web Services", classifiers=[], keywords='', author="Sean Gillies", author_email='[email protected]', url='https://github.com/mapbox/mapbox-cli-py', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click', 'click-plugins', 'cligj>=0.4', 'mapbox>=0.11', 'six'], extras_require={ 'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses', 'mock']}, entry_points=""" [console_scripts] mapbox=mapboxcli.scripts.cli:main_group """)
from setuptools import setup, find_packages # Parse the version from the mapbox module. with open('mapboxcli/__init__.py') as f: for line in f: if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"') version = version.strip("'") continue setup(name='mapboxcli', version=version, description="Command line interface to Mapbox Web Services", classifiers=[], keywords='', author="Sean Gillies", author_email='[email protected]', url='https://github.com/mapbox/mapbox-cli-py', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ 'click', 'click-plugins', 'cligj>=0.4', 'mapbox>=0.11', 'six'], extras_require={ 'test': ['coveralls', 'pytest>=2.8', 'pytest-cov', 'responses'], }, entry_points=""" [console_scripts] mapbox=mapboxcli.scripts.cli:main_group """)
Put classes into config file
<?php /** * Config for the connections for the test */ return [ 'mysql' => [ 'type' => 'mysql', 'host' => 'localhost', 'database' => 'sample_database', 'user' => 'sample_user', 'password' => 'sample_password', 'charset' => 'utf8', 'options' => [ PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", ], 'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing ], 'pgsql' => [ 'type' => 'pgsql', 'host' => 'localhost', 'database' => 'sample_database', 'user' => 'sample_user', 'password' => 'sample_password', 'options' => [ PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", ], 'class' => \OlajosCs\QueryBuilder\PostgreSQL\Connection::class // Needed only for testing ] ];
<?php /** * Config for the connections for the test */ return [ 'mysql' => [ 'type' => 'mysql', 'host' => 'localhost', 'database' => 'sample_database', 'user' => 'sample_user', 'password' => 'sample_password', 'charset' => 'utf8', 'options' => [ PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", ], 'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing ], 'pgsql' => [ 'type' => 'pgsql', 'host' => 'localhost', 'database' => 'sample_database', 'user' => 'sample_user', 'password' => 'sample_password', 'options' => [ PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8", ], 'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing ] ];
FIX matplotlib backend problem in cli tests
"""Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <[email protected]> # # License: BSD (3-clause) import matplotlib # noqa matplotlib.use('Agg') # noqa; for testing don't use X server import os import os.path as op from ephypype.commands import neuropycon from click.testing import CliRunner def test_input_linear(): """Test input node with Linear plugin (serial workflow execution)""" runner = CliRunner() wf_name = 'test_input_linear' with runner.isolated_filesystem(): with open('temp.fif', 'w') as f: f.write('temp') result = runner.invoke(neuropycon.cli, ['-s', os.getcwd(), '-w', wf_name, 'input', 'temp.fif']) assert result.exit_code == 0 assert os.path.exists(op.join(os.getcwd(), wf_name)) def test_input_multiproc(): """Test input node with MultiProc plugin (parallel workflow execution)""" runner = CliRunner() wf_name = 'test_input_multiproc' with runner.isolated_filesystem(): with open('temp.fif', 'w') as f: f.write('temp') result = runner.invoke(neuropycon.cli, ['-s', os.getcwd(), '-w', wf_name, '-p', 'MultiProc', 'input', 'temp.fif']) assert result.exit_code == 0 assert os.path.exists(op.join(os.getcwd(), wf_name))
"""Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <[email protected]> # # License: BSD (3-clause) import os import os.path as op from ephypype.commands import neuropycon from click.testing import CliRunner def test_input_linear(): """Test input node with Linear plugin (serial workflow execution)""" runner = CliRunner() wf_name = 'test_input_linear' with runner.isolated_filesystem(): with open('temp.fif', 'w') as f: f.write('temp') result = runner.invoke(neuropycon.cli, ['-s', os.getcwd(), '-w', wf_name, 'input', 'temp.fif']) assert result.exit_code == 0 assert os.path.exists(op.join(os.getcwd(), wf_name)) def test_input_multiproc(): """Test input node with MultiProc plugin (parallel workflow execution)""" runner = CliRunner() wf_name = 'test_input_multiproc' with runner.isolated_filesystem(): with open('temp.fif', 'w') as f: f.write('temp') result = runner.invoke(neuropycon.cli, ['-s', os.getcwd(), '-w', wf_name, '-p', 'MultiProc', 'input', 'temp.fif']) assert result.exit_code == 0 assert os.path.exists(op.join(os.getcwd(), wf_name))
Add source map support to CSS
const path = require("path"); const merge = require("webpack-merge"); const webpack = require("webpack"); const common = require("./webpack.common.js"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer") ]; module.exports = merge(common, { entry: [ "webpack-dev-server/client?http://localhost:3000/", "webpack/hot/only-dev-server" ], mode: "development", devtool: "eval-source-map", watch: true, devServer: { headers: { "Access-Control-Allow-Origin": "*" }, hot: true, port: 3000, disableHostCheck: true, overlay: true, contentBase: path.join(__dirname, "../src") }, plugins: [new webpack.HotModuleReplacementPlugin()], module: { rules: [ { test: /\.css$/, use: [ "style-loader", { loader: "css-loader", options: { url: false, sourceMap: true } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins, sourceMap: true } } ] } ] } });
const path = require("path"); const merge = require("webpack-merge"); const webpack = require("webpack"); const common = require("./webpack.common.js"); const postCSSPlugins = [ require("postcss-easy-import")({ prefix: "_" }), require("postcss-mixins"), require("postcss-simple-vars"), require("postcss-nested"), require("postcss-color-function"), require("postcss-hexrgba"), require("autoprefixer") ]; module.exports = merge(common, { entry: [ "webpack-dev-server/client?http://localhost:3000/", "webpack/hot/only-dev-server" ], mode: "development", devtool: "eval-source-map", watch: true, devServer: { headers: { "Access-Control-Allow-Origin": "*" }, hot: true, port: 3000, disableHostCheck: true, overlay: true, contentBase: path.join(__dirname, "../src") }, plugins: [new webpack.HotModuleReplacementPlugin()], module: { rules: [ { test: /\.css$/, use: [ "style-loader", { loader: "css-loader", options: { url: false } }, { loader: "postcss-loader", options: { plugins: postCSSPlugins } } ] } ] } });
Deal with optional methods too
import {VueComponentFactory} from "./vueComponentFactory"; class VueFrameworkComponentWrapper { constructor(parent) { this._parent = parent; } wrap(component, methodList, optionalMethods) { let componentType = VueComponentFactory.getComponentType(this._parent, component); if (!componentType) { return; } class DynamicComponent { init(params) { this.component = VueComponentFactory.createAndMountComponent(params, componentType); } getGui() { return this.component.$el; } destroy() { this.component.$destroy(); } getFrameworkComponentInstance() { return this.component; } } let wrapper = new DynamicComponent(); methodList.forEach((methodName => { wrapper[methodName] = function () { if (wrapper.getFrameworkComponentInstance()[methodName]) { const componentRef = this.getFrameworkComponentInstance(); return wrapper.getFrameworkComponentInstance()[methodName].apply(componentRef, arguments) } else { console.warn('ag-Grid: Vue component is missing the method ' + methodName + '()'); return null; } } })); optionalMethods.forEach((methodName => { wrapper[methodName] = function () { if (wrapper.getFrameworkComponentInstance()[methodName]) { const componentRef = this.getFrameworkComponentInstance(); return wrapper.getFrameworkComponentInstance()[methodName].apply(componentRef, arguments) } } })); return wrapper; } } VueFrameworkComponentWrapper.prototype.__agBeanMetaData = { beanName: "frameworkComponentWrapper" }; export {VueFrameworkComponentWrapper as VueFrameworkComponentWrapper};
import {VueComponentFactory} from "./vueComponentFactory"; class VueFrameworkComponentWrapper { constructor(parent) { this._parent = parent; } wrap(component, methodList) { let componentType = VueComponentFactory.getComponentType(this._parent, component); if (!componentType) { return; } class DynamicComponent { init(params) { this.component = VueComponentFactory.createAndMountComponent(params, componentType); } getGui() { return this.component.$el; } destroy() { this.component.$destroy(); } getFrameworkComponentInstance() { return this.component; } } let wrapper = new DynamicComponent(); methodList.forEach((methodName => { wrapper[methodName] = function () { if (wrapper.getFrameworkComponentInstance()[methodName]) { const componentRef = this.getFrameworkComponentInstance(); return wrapper.getFrameworkComponentInstance()[methodName].apply(componentRef, arguments) } else { console.warn('ag-Grid: Vue component is missing the method ' + methodName + '()'); return null; } } })); return wrapper; } } VueFrameworkComponentWrapper.prototype.__agBeanMetaData = { beanName: "frameworkComponentWrapper" }; export { VueFrameworkComponentWrapper as VueFrameworkComponentWrapper };
Add test for list display
var $ = require("jquery"); var List = require("../"); describe('List', function() { describe('count', function() { it('should return correct count (without filter)', function() { var l = new List(); l.collection.reset([ { 'test': 1 }, { 'test': 2 }, { 'test': 3 } ]); expect(l.count()).to.equal(3); }); it('should return correct count (with filter)', function() { var l = new List({ filter: function(model) { return model.get("test") >= 2; } }); l.collection.reset([ { 'test': 1 }, { 'test': 2 }, { 'test': 3 } ]); expect(l.count()).to.equal(2); }); it('should correcly be rendered', function() { var Item = List.Item.extend({ render: function() { this.html("test "+this.model.get('test')); return this.ready(); } }); var TestList = List.extend({ Item: Item }); var l = new TestList({ }); l.collection.reset([ { 'test': 1 }, { 'test': 2 }, { 'test': 3 } ]); var $container = $("<div>", { 'class': "test"}); $container.appendTo($("body")); l.appendTo($container); expect($(".test").html()).to.equal("<ul><li>test 1</li><li>test 2</li><li>test 3</li></ul>"); }); }); });
var List = require("../"); describe('List', function() { describe('count', function() { it('should return correct count (without filter)', function() { var l = new List(); l.collection.reset([ { 'test': 1 }, { 'test': 2 }, { 'test': 3 } ]); expect(l.count()).to.equal(3); }); it('should return correct count (with filter)', function() { var l = new List({ filter: function(model) { return model.get("test") >= 2; } }); l.collection.reset([ { 'test': 1 }, { 'test': 2 }, { 'test': 3 } ]); expect(l.count()).to.equal(2); }); }); });
Update benchmarks to Pyton 3.
import re import urllib.parse import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.parse.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
import re import urllib import random import unittest from funkload.FunkLoadTestCase import FunkLoadTestCase class Benchmark(FunkLoadTestCase): """This test uses a configuration file Benchmark.conf.""" def setUp(self): self.server_url = self.conf_get('main', 'url') def test_simple(self): server_url = self.server_url if not re.match('https?://', server_url): raise Exception("The `server_url` setting doesn't have a scheme.") username = self.conf_get('test_benchmark', 'username', None) password = self.conf_get('test_benchmark', 'password', None) if username and password: self.post(self.server_url + "/api/user/login", params=[['username', username], ['password', password]], description="Login as %s" % username) nb_times = self.conf_getInt('test_benchmark', 'nb_times') names = self.conf_get('test_benchmark', 'page_names').split(';') for i in range(nb_times): r = random.randint(0, len(names) - 1) url = server_url + '/api/read/' + urllib.quote(names[r]) self.get(url, description='Getting %s' % names[r]) if __name__ in ('main', '__main__'): unittest.main()
Fix spelling error with shutdown
import React from 'react'; export let IntercomAPI = window.Intercom || function() { console.warn('Intercome not initialized yet') }; export default class Intercom extends React.Component { static propTypes = { appID: React.PropTypes.string.isRequired } static displayName = 'Intercom' constructor(props) { super(props); if (typeof window.Intercom === "function" || !props.appID) { return; } (function(w, d, id, s, x) { function i() { i.c(arguments); } i.q = []; i.c = function(args) { i.q.push(args); }; w.Intercom = i; s = d.createElement('script'); s.onload = function() { IntercomAPI = window.Intercom }; s.async = 1; s.src = 'https://widget.intercom.io/widget/' + id; x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(window, document, props.appID); window.intercomSettings = props; if (typeof window.Intercom === 'function') { window.Intercom('boot', props); } } componentWillReceiveProps(nextProps) { window.intercomSettings = nextProps; window.Intercom('update'); } shouldComponentUpdate() { return false; } componentWillUnmount() { window.Intercom('shutdown'); } render() { return false; } }
import React from 'react'; export let IntercomAPI = window.Intercom || function() { console.warn('Intercome not initialized yet') }; export default class Intercom extends React.Component { static propTypes = { appID: React.PropTypes.string.isRequired } static displayName = 'Intercom' constructor(props) { super(props); if (typeof window.Intercom === "function" || !props.appID) { return; } (function(w, d, id, s, x) { function i() { i.c(arguments); } i.q = []; i.c = function(args) { i.q.push(args); }; w.Intercom = i; s = d.createElement('script'); s.onload = function() { IntercomAPI = window.Intercom }; s.async = 1; s.src = 'https://widget.intercom.io/widget/' + id; x = d.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })(window, document, props.appID); window.intercomSettings = props; if (typeof window.Intercom === 'function') { window.Intercom('boot', props); } } componentWillReceiveProps(nextProps) { window.intercomSettings = nextProps; window.Intercom('update'); } shouldComponentUpdate() { return false; } componentWillUnmount() { window.Intercom('shudown'); } render() { return false; } }
Use LIMIT_CHARA_LENGTH instead of Magic number
import React, {Component} from 'react' import {keyStringDetector} from '../registories/registory' import Tweet from '../../domain/models/Tweet' export default class Editor extends Component { constructor(props) { super(props); this.state = this.initialState(); } initialState() { return {text: ''}; } getRestTextLength() { return Tweet.LIMIT_CHARA_LENGTH - this.state.text.length; } onTextareaChanged(event) { this.setState({text: event.target.value}); } onTextareaKeyDown(event) { if (keyStringDetector.detect(event) === 'Return') { event.preventDefault(); this.onTweetSubmitted(); } } onTweetSubmitted() { const {onTweetSubmitted} = this.props; onTweetSubmitted(this.state.text); this.setState(this.initialState()); //TODO: tweetが成功したらテキストを初期化する } //TODO: 140字を超えたらviewを変更して伝える render() { return ( <div className="editor"> <textarea name="name" rows="2" cols="40" className="editor-textarea" onChange={this.onTextareaChanged.bind(this)} onKeyDown={this.onTextareaKeyDown.bind(this)} placeholder="What's happening?" value={this.state.text}> </textarea> <div className="editor-counter"> {this.getRestTextLength()} </div> </div> ); } }
import React, {Component} from 'react' import {keyStringDetector} from '../registories/registory' export default class Editor extends Component { constructor(props) { super(props); this.state = this.initialState(); } initialState() { return {text: ''}; } getRestTextLength() { return 140 - this.state.text.length; } onTextareaChanged(event) { this.setState({text: event.target.value}); } onTextareaKeyDown(event) { if (keyStringDetector.detect(event) === 'Return') { event.preventDefault(); this.onTweetSubmitted(); } } onTweetSubmitted() { const {onTweetSubmitted} = this.props; onTweetSubmitted(this.state.text); this.setState(this.initialState()); //TODO: tweetが成功したらテキストを初期化する } //TODO: 140字を超えたらviewを変更して伝える render() { return ( <div className="editor"> <textarea name="name" rows="2" cols="40" className="editor-textarea" onChange={this.onTextareaChanged.bind(this)} onKeyDown={this.onTextareaKeyDown.bind(this)} placeholder="What's happening?" value={this.state.text}> </textarea> <div className="editor-counter"> {this.getRestTextLength()} </div> </div> ); } }
Allow a controller to accept non-json data by setting route attribute
<?php /* * This file is part of Contao Manager. * * (c) Contao Association * * @license LGPL-3.0-or-later */ namespace Contao\ManagerApi\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\KernelEvent; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException; class JsonRequestListener implements EventSubscriberInterface { /** * Disallow everything except JSON and convert data to request content. * * @param KernelEvent $event * * @throws UnsupportedMediaTypeHttpException * @throws BadRequestHttpException */ public function onKernelRequest(KernelEvent $event) { $request = $event->getRequest(); $content = $content = $request->getContent(); if ($content === '' && $request->attributes->get('form-data')) { return; } $data = []; if ($content !== '') { if ('json' !== $request->getContentType()) { throw new UnsupportedMediaTypeHttpException('Only JSON requests are supported.'); } $data = json_decode($content, true); if (!is_array($data)) { throw new BadRequestHttpException('Invalid JSON data received.'); } } $request->request->replace($data); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { // Priority must be lower than the router (defaults to 32) return ['kernel.request' => ['onKernelRequest', 20]]; } }
<?php /* * This file is part of Contao Manager. * * (c) Contao Association * * @license LGPL-3.0-or-later */ namespace Contao\ManagerApi\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\KernelEvent; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException; class JsonRequestListener implements EventSubscriberInterface { /** * Disallow everything except JSON and convert data to request content. * * @param KernelEvent $event * * @throws UnsupportedMediaTypeHttpException * @throws BadRequestHttpException */ public function onKernelRequest(KernelEvent $event) { $request = $event->getRequest(); $data = []; if (($content = $request->getContent()) !== '') { if ('json' !== $request->getContentType()) { throw new UnsupportedMediaTypeHttpException('Only JSON requests are supported.'); } $data = json_decode($content, true); if (!is_array($data)) { throw new BadRequestHttpException('Invalid JSON data received.'); } } $request->request->replace($data); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return ['kernel.request' => ['onKernelRequest', 100]]; } }
RESOLVE an error with undefined index
<?php namespace rrsoacis\component\setting\cluster; use rrsoacis\manager\ClusterManager; use ZipArchive; use rrsoacis\component\common\AbstractController; use rrsoacis\manager\MapManager; use rrsoacis\system\Config; class SettingsClusterUpdateController extends AbstractController { public function post() { $name = null; if (isset($_POST['name']) && $_POST['name'] !== '') { $name = $_POST['name']; } $a_host = $_POST['a_host']; $f_host = $_POST['f_host']; $p_host = $_POST['p_host']; $s_host = $_POST['s_host']; $archiver = $_POST['archiver']; $hosts_pass = $_POST['hosts_pass']; if ($a_host !== '' && $s_host !== '' && $f_host !== '' && $p_host !== '' && $archiver !== "" && $hosts_pass !== "") { ClusterManager::updateCluster($name, $a_host, $f_host, $p_host, $s_host, $archiver, $hosts_pass); } if ($name == null) { header('location: '.Config::$TOP_PATH.'settings-clusters'); } else { header('location: '.Config::$TOP_PATH.'settings-cluster/'.$name); } } } ?>
<?php namespace rrsoacis\component\setting\cluster; use rrsoacis\manager\ClusterManager; use ZipArchive; use rrsoacis\component\common\AbstractController; use rrsoacis\manager\MapManager; use rrsoacis\system\Config; class SettingsClusterUpdateController extends AbstractController { public function post() { $name = $_POST['name']; if ($name === '') { $name = null; } $a_host = $_POST['a_host']; $f_host = $_POST['f_host']; $p_host = $_POST['p_host']; $s_host = $_POST['s_host']; $archiver = $_POST['archiver']; $hosts_pass = $_POST['hosts_pass']; if ($a_host !== '' && $s_host !== '' && $f_host !== '' && $p_host !== '' && $archiver !== "" && $hosts_pass !== "") { ClusterManager::updateCluster($name, $a_host, $f_host, $p_host, $s_host, $archiver, $hosts_pass); } if ($name == null) { header('location: '.Config::$TOP_PATH.'settings-clusters'); } else { header('location: '.Config::$TOP_PATH.'settings-cluster/'.$name); } } } ?>
Fix rolling over history and write unit test to prevent future bugs
package com.github.games647.lagmonitor; public class RollingOverHistory { private final float[] samples; private float total; private int currentPosition = 0; private int currentSize = 1; public RollingOverHistory(int size, float firstValue) { this.samples = new float[size]; samples[0] = firstValue; total = firstValue; } public void add(float sample) { currentPosition++; if (currentPosition >= samples.length) { //we reached the end - go back to the beginning currentPosition = 0; } if (currentSize < samples.length) { //array is not full yet currentSize++; } else { //delete the latest sample which wil be overridden total -= samples[currentPosition]; } total += sample; samples[currentPosition] = sample; } public float getAverage() { return total / currentSize; } public int getCurrentPosition() { return currentPosition; } public int getCurrentSize() { return currentSize; } public float getLastSample() { int lastPos = currentPosition; if (lastPos < 0) { lastPos = samples.length - 1; } return samples[lastPos]; } public float[] getSamples() { return samples; } }
package com.github.games647.lagmonitor; public class RollingOverHistory { private final float[] samples; private float total; private int currentPosition = 1; private int currentSize = 1; public RollingOverHistory(int size, float firstValue) { this.samples = new float[size]; samples[0] = firstValue; } public void add(float sample) { currentPosition++; if (currentPosition >= samples.length) { //we reached the end - go back to the beginning currentPosition = 0; } if (currentSize < samples.length) { //array is not full yet currentSize++; } else { //delete the latest sample which wil be overridden total -= samples[currentPosition]; } total += sample; samples[currentPosition] = sample; } public float getAverage() { return total / currentSize; } public int getCurrentPosition() { return currentPosition; } public int getCurrentSize() { return currentSize; } public float getLastSample() { int lastPos = currentPosition - 1; if (lastPos < 0) { lastPos = samples.length - 1; } return samples[lastPos]; } public float[] getSamples() { return samples; } }
Add clearTitleSegments method to seo helper
<?php namespace Concrete\Core\Html\Service; class Seo { private $siteName = ''; private $titleSegments = array(); private $titleSegmentSeparator = ' :: '; private $titleFormat = '%1$s :: %2$s'; private $hasCustomTitle = false; public function setSiteName($name) { $this->siteName = $name; } public function hasCustomTitle() { return $this->hasCustomTitle; } public function setCustomTitle($title) { $this->hasCustomTitle = true; $this->clearTitleSegments(); $this->addTitleSegmentBefore($title); return $this; } public function addTitleSegment($segment) { array_push($this->titleSegments, $segment); return $this; } public function addTitleSegmentBefore($segment) { array_unshift($this->titleSegments, $segment); return $this; } public function clearTitleSegments() { $this->titleSegments = array(); } public function setTitleFormat($format) { $this->titleFormat = $format; return $this; } public function setTitleSegmentSeparator($separator) { $this->titleSegmentSeparator = $separator; return $this; } public function getTitle() { $segments = ''; if (count($this->titleSegments) > 0) { $segments = implode($this->titleSegmentSeparator, $this->titleSegments); } return sprintf($this->titleFormat, $this->siteName, $segments); } }
<?php namespace Concrete\Core\Html\Service; class Seo { private $siteName = ''; private $titleSegments = array(); private $titleSegmentSeparator = ' :: '; private $titleFormat = '%1$s :: %2$s'; private $hasCustomTitle = false; public function setSiteName($name) { $this->siteName = $name; } public function hasCustomTitle() { return $this->hasCustomTitle; } public function setCustomTitle($title) { $this->hasCustomTitle = true; $this->titleSegments = array(); $this->addTitleSegmentBefore($title); return $this; } public function addTitleSegment($segment) { array_push($this->titleSegments, $segment); return $this; } public function addTitleSegmentBefore($segment) { array_unshift($this->titleSegments, $segment); return $this; } public function setTitleFormat($format) { $this->titleFormat = $format; return $this; } public function setTitleSegmentSeparator($separator) { $this->titleSegmentSeparator = $separator; return $this; } public function getTitle() { $segments = ''; if (count($this->titleSegments) > 0) { $segments = implode($this->titleSegmentSeparator, $this->titleSegments); } return sprintf($this->titleFormat, $this->siteName, $segments); } }
Send the latest logs by ordering logs descending
<?php namespace A3020\Centry\Log; use A3020\Centry\Payload\PayloadAbstract; use Concrete\Core\Config\Repository\Repository; use Concrete\Core\Database\Connection\Connection; final class Payload extends PayloadAbstract { /** @var Connection */ private $db; /** @var Repository */ private $config; public function __construct(Connection $db, Repository $config) { $this->db = $db; $this->config = $config; } public function jsonSerialize() { return $this->getLogs(); } private function getLogs() { $logs = $this->db->fetchAll(' SELECT * FROM Logs ORDER BY logID DESC LIMIT ' . $this->getMaxNumberOfLogs() ); return array_map(function($log) { return [ 'log_id' => (int) $log['logID'], 'log_channel' => $log['channel'], 'log_time' => (int) $log['time'], 'log_message' => $log['message'], 'log_level' => (int) $log['level'], 'log_user_id' => $log['uID'] ? (int) $log['uID'] : null, ]; }, $logs); } private function getMaxNumberOfLogs() { return (int) $this->config->get('centry.api.logs.max', 300); } }
<?php namespace A3020\Centry\Log; use A3020\Centry\Payload\PayloadAbstract; use Concrete\Core\Config\Repository\Repository; use Concrete\Core\Database\Connection\Connection; final class Payload extends PayloadAbstract { /** @var Connection */ private $db; /** @var Repository */ private $config; public function __construct(Connection $db, Repository $config) { $this->db = $db; $this->config = $config; } public function jsonSerialize() { return $this->getLogs(); } private function getLogs() { $logs = $this->db->fetchAll(' SELECT * FROM Logs LIMIT ' . $this->getMaxNumberOfLogs() ); return array_map(function($log) { return [ 'log_id' => (int) $log['logID'], 'log_channel' => $log['channel'], 'log_time' => (int) $log['time'], 'log_message' => $log['message'], 'log_level' => (int) $log['level'], 'log_user_id' => $log['uID'] ? (int) $log['uID'] : null, ]; }, $logs); } private function getMaxNumberOfLogs() { return (int) $this->config->get('centry.api.logs.max', 300); } }
Fix migration file for Python 3.2 (and PEP8)
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('from_email', models.TextField(verbose_name='from e-mail')), ('recipients', models.TextField(verbose_name='recipients')), ('subject', models.TextField(verbose_name='subject')), ('body', models.TextField(verbose_name='body')), ('ok', models.BooleanField(default=False, db_index=True, verbose_name='ok')), ('date_sent', models.DateTimeField(auto_now_add=True, verbose_name='date sent', db_index=True)), ], options={ 'ordering': ('-date_sent',), 'verbose_name': 'e-mail', 'verbose_name_plural': 'e-mails', }, bases=(models.Model,), ), ]
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Email', fields=[ (u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True)), ('from_email', models.TextField(verbose_name=u'from e-mail')), ('recipients', models.TextField(verbose_name=u'recipients')), ('subject', models.TextField(verbose_name=u'subject')), ('body', models.TextField(verbose_name=u'body')), ('ok', models.BooleanField(default=False, db_index=True, verbose_name=u'ok')), ('date_sent', models.DateTimeField(auto_now_add=True, verbose_name=u'date sent', db_index=True)), ], options={ u'ordering': (u'-date_sent',), u'verbose_name': u'e-mail', u'verbose_name_plural': u'e-mails', }, bases=(models.Model,), ), ]
Fix error in top navigation not being able to find about us section
(function() { 'use strict'; angular .module('app.layout') .directive('pvTopNav', pvTopNav); /* @ngInject */ function pvTopNav () { var directive = { bindToController: true, controller: TopNavController, controllerAs: 'vm', restrict: 'EA', scope: { 'inHeader': '=' }, templateUrl: 'app/layout/pv-top-nav.html' }; /* @ngInject */ function TopNavController($scope, $document, $state, $rootScope) { var vm = this; activate(); function activate() { checkWithinIntro(); $document.on('scroll', checkWithinIntro); $rootScope.$on('$viewContentLoaded', checkWithinIntro); } function checkWithinIntro() { if ($state.current.name !== 'home') { vm.inHeader = false; $scope.$applyAsync(); return; } var aboutTopPosition = $document.find('#about').offset().top, navbarHeight = $document.find('#pv-top-nav').height(), triggerHeight = aboutTopPosition - navbarHeight - 1; vm.inHeader = $document.scrollTop() <= triggerHeight; $scope.$applyAsync(); } } return directive; } })();
(function() { 'use strict'; angular .module('app.layout') .directive('pvTopNav', pvTopNav); /* @ngInject */ function pvTopNav () { var directive = { bindToController: true, controller: TopNavController, controllerAs: 'vm', restrict: 'EA', scope: { 'inHeader': '=' }, templateUrl: 'app/layout/pv-top-nav.html' }; /* @ngInject */ function TopNavController($scope, $document, $state, $rootScope) { var vm = this; activate(); function activate() { checkWithinIntro(); $document.on('scroll', checkWithinIntro); $rootScope.$on('$viewContentLoaded', checkWithinIntro); } function checkWithinIntro() { var aboutTopPosition = $document.find('#about').offset().top, navbarHeight = $document.find('#pv-top-nav').height(), triggerHeight = aboutTopPosition - navbarHeight - 1; vm.inHeader = $state.current.url === '/' && $document.scrollTop() <= triggerHeight; $scope.$applyAsync(); } } return directive; } })();
Make InstanceLaunchFooter functionally disabled instead of just visually
import React from 'react'; export default React.createClass({ propTypes: { backIsDisabled: React.PropTypes.bool.isRequired, launchIsDisabled: React.PropTypes.bool.isRequired, advancedIsDisabled: React.PropTypes.bool.isRequired, viewAdvanced: React.PropTypes.func, onSubmitLaunch: React.PropTypes.func, onCancel: React.PropTypes.func, onBack: React.PropTypes.func, }, renderBack: function() { if (this.props.backIsDisabled) { return } else { return ( <a className="btn btn-default pull-left" style={{marginRight:"10px"}} onClick={this.props.onBack} > <span className="glyphicon glyphicon-arrow-left"/> Back </a> ) } }, render: function() { return ( <div className="modal-footer"> {this.renderBack()} <a className="pull-left btn" disabled={this.props.advancedIsDisabled} onClick={this.props.viewAdvanced}> <i className="glyphicon glyphicon-cog"/> Advanced Options </a> <button disabled={this.props.launchIsDisabled} type="button" className="btn btn-primary pull-right" onClick={this.props.onSubmitLaunch} > Launch Instance </button> <button type="button" className="btn btn-default pull-right" style={{marginRight:"10px"}} onClick={this.props.onCancel} > Cancel </button> </div> ) } });
import React from 'react'; export default React.createClass({ propTypes: { backIsDisabled: React.PropTypes.bool.isRequired, launchIsDisabled: React.PropTypes.bool.isRequired, advancedIsDisabled: React.PropTypes.bool.isRequired, viewAdvanced: React.PropTypes.func, onSubmitLaunch: React.PropTypes.func, onCancel: React.PropTypes.func, onBack: React.PropTypes.func, }, renderBack: function() { if (this.props.backIsDisabled) { return } else { return ( <a className="btn btn-default pull-left" style={{marginRight:"10px"}} onClick={this.props.onBack} > <span className="glyphicon glyphicon-arrow-left"/> Back </a> ) } }, render: function() { let launchIsDisabled = this.props.launchIsDisabled ? "disabled" : ""; let advancedIsDisabled = this.props.advancedIsDisabled ? "disabled" : ""; return ( <div className="modal-footer"> {this.renderBack()} <a className={`pull-left btn ${advancedIsDisabled}`} onClick={this.props.viewAdvanced}> <i className="glyphicon glyphicon-cog"/> Advanced Options </a> <button disabled={this.props.launchIsDisabled} type="button" className={`btn btn-primary pull-right ${launchIsDisabled}`} onClick={this.props.onSubmitLaunch} > Launch Instance </button> <button type="button" className="btn btn-default pull-right" style={{marginRight:"10px"}} onClick={this.props.onCancel} > Cancel </button> </div> ) } });
Fix typo in upgrade script git-svn-id: f68c6b3b1dcd5d00a2560c384475aaef3bc99487@1647 af82e41b-90c4-0310-8c96-b1721e28e2e2
import os.path import shutil sql = """ -- Remove empty values from the milestone list DELETE FROM milestone WHERE COALESCE(name,'')=''; -- Add a description column to the version table, and remove unnamed versions CREATE TEMP TABLE version_old AS SELECT * FROM version; DROP TABLE version; CREATE TABLE version ( name text PRIMARY KEY, time integer, description text ); INSERT INTO version(name,time,description) SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>''; -- Add a description column to the component table, and remove unnamed components CREATE TEMP TABLE component_old AS SELECT * FROM component; DROP TABLE component; CREATE TABLE component ( name text PRIMARY KEY, owner text, description text ); INSERT INTO component(name,owner,description) SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>''; """ def do_upgrade(env, ver, cursor): cursor.execute(sql) # Copy the new default wiki macros over to the environment from trac.siteconfig import __default_macros_dir__ as macros_dir for f in os.listdir(macros_dir): if not f.endswith('.py'): continue src = os.path.join(macros_dir, f) dst = os.path.join(env.path, 'wiki-macros', f) if not os.path.isfile(dst): shutil.copy2(src, dst)
import os.path import shutil sql = """ -- Remove empty values from the milestone list DELETE FROM milestone WHERE COALESCE(name,'')=''; -- Add a description column to the version table, and remove unnamed versions CREATE TEMP TABLE version_old AS SELECT * FROM version; DROP TABLE version; CREATE TABLE version ( name text PRIMARY KEY, time integer, description text ); INSERT INTO version(name,time,description) SELECT name,time,'' FROM version_old WHERE COALESCE(name,'')<>''; -- Add a description column to the component table, and remove unnamed components CREATE TEMP TABLE component_old AS SELECT * FROM component; DROP TABLE component; CREATE TABLE component ( name text PRIMARY KEY, owner text, description text ); INSERT INTO component(name,owner,description) SELECT name,owner,'' FROM component_old WHERE COALESCE(name,'')<>''; """ def do_upgrade(env, ver, cursor): cursor.execute(sql) # Copy the new default wiki macros over to the environment from trac.siteconfig import __default_macro_dir__ as macro_dir for f in os.listdir(macro_dir): if not f.endswith('.py'): continue src = os.path.join(macro_dir, f) dst = os.path.join(env.path, 'wiki-macros', f) if not os.path.isfile(dst): shutil.copy2(src, dst)
Load table schema automatically instead of stubbing out
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table meta = MetaData() instances = Table('instances', meta, autoload=True) instances_vm_mode = Column('vm_mode', String(length=255, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), nullable=True) def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; # bind migrate_engine to your metadata meta.bind = migrate_engine instances.create_column(instances_vm_mode) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column('vm_mode')
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from sqlalchemy import Column, Integer, MetaData, String, Table meta = MetaData() instances = Table('instances', meta, Column('id', Integer(), primary_key=True, nullable=False), ) instances_vm_mode = Column('vm_mode', String(length=255, convert_unicode=False, assert_unicode=None, unicode_error=None, _warn_on_bytestring=False), nullable=True) def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; # bind migrate_engine to your metadata meta.bind = migrate_engine instances.create_column(instances_vm_mode) def downgrade(migrate_engine): meta.bind = migrate_engine instances.drop_column('vm_mode')
Add new line print to clearScreen()
import java.util.Scanner; public class Main { public static void main(String[] args) { printTitle(); titleWait(); System.out.println("You wake up on a beach."); } private static void printTitle() { String banner = "___________ .__ ___________ __ \n" + "\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" + " | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" + " | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" + "/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" + " \\/|__| \\/ \\/ \\/ "; System.out.println(banner); } private static void titleWait() { System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); clearScreen(); } private static void clearScreen() { System.out.println("\n\n\n\n\n\n\n\n\n\n"); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { printTitle(); titleWait(); System.out.println("You wake up on a beach."); } private static void printTitle() { String banner = "___________ .__ ___________ __ \n" + "\\_ _____/_____ |__| ___\\__ ___/___ ___ ____/ |_ \n" + " | __)_\\____ \\| |/ ___\\| |_/ __ \\\\ \\/ /\\ __\\\n" + " | \\ |_> > \\ \\___| |\\ ___/ > < | | \n" + "/_______ / __/|__|\\___ >____| \\___ >__/\\_ \\ |__| \n" + " \\/|__| \\/ \\/ \\/ "; System.out.println(banner); } private static void titleWait() { System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine(); clearScreen(); } private static void clearScreen() { } }
Refactor the repository generator so we can reuse its methods
<?php namespace ModuleGenerator\CLI\Console\Generate\Domain; use ModuleGenerator\CLI\Console\GenerateCommand; use ModuleGenerator\Domain\Repository\Repository as RepositoryClass; use ModuleGenerator\Domain\Repository\RepositoryType; use ModuleGenerator\Module\Backend\Resources\Config\Repositories\Repositories; use ModuleGenerator\PhpGenerator\ClassName\ClassName; use ModuleGenerator\PhpGenerator\ModuleName\ModuleName; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; final class Repository extends GenerateCommand { protected function configure() { parent::configure(); $this->setName('generate:domain:repository') ->setDescription('Generates the repository class for an entity'); } protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); $this->createRepository(ClassName::fromDataTransferObject($this->getFormData(RepositoryType::class))); } public function createRepository(ClassName $entityClassName): void { $repositoryClass = RepositoryClass::fromEntityClassName($entityClassName); $this->generateService->generateClass( $repositoryClass, $this->getTargetPhpVersion() ); $moduleName = $this->extractModuleName($repositoryClass->getClassName()->getNamespace()); if ($moduleName instanceof ModuleName) { $this->generateService->generateFile( new Repositories( $moduleName, [$repositoryClass->getClassName()->getForUseStatement()], true ), $this->getTargetPhpVersion() ); } } }
<?php namespace ModuleGenerator\CLI\Console\Generate\Domain; use ModuleGenerator\CLI\Console\GenerateCommand; use ModuleGenerator\Domain\Repository\Repository as RepositoryClass; use ModuleGenerator\Domain\Repository\RepositoryType; use ModuleGenerator\Module\Backend\Resources\Config\Repositories\Repositories; use ModuleGenerator\PhpGenerator\ClassName\ClassName; use ModuleGenerator\PhpGenerator\ModuleName\ModuleName; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; final class Repository extends GenerateCommand { protected function configure() { parent::configure(); $this->setName('generate:domain:repository') ->setDescription('Generates the repository class for an entity'); } protected function execute(InputInterface $input, OutputInterface $output) { parent::execute($input, $output); $entityClassName = ClassName::fromDataTransferObject($this->getFormData(RepositoryType::class)); $repositoryClass = RepositoryClass::fromEntityClassName($entityClassName); $this->generateService->generateClass( $repositoryClass, $this->getTargetPhpVersion() ); $moduleName = $this->extractModuleName($repositoryClass->getClassName()->getNamespace()); if ($moduleName instanceof ModuleName) { $this->generateService->generateFile( new Repositories( $moduleName, [$repositoryClass->getClassName()->getForUseStatement()], true ), $this->getTargetPhpVersion() ); } } }
Change 9gag collector longpost detector
import time import feedparser from bs4 import BeautifulSoup import boto3 from PIL import Image import requests import logging NINEGAG_RSS_URL = 'http://www.15minutesoffame.be/9gag/rss/9GAG_-_Trending.atom' def main(): feed = feedparser.parse(NINEGAG_RSS_URL)['items'] table = boto3.resource('dynamodb', 'eu-west-1').Table('LeonardBot9gagPosts') for item in feed: title, post_id, img = item['title'], item['link'].split('/')[4], BeautifulSoup( item['summary'], 'lxml' ).find('img') if not hasattr(img, 'src'): continue img = img['src'] response = requests.get(img, stream=True) width, height = Image.open(response.raw).size if height / width >= 2: continue table.put_item( Item={ 'postId': post_id, 'title': title, 'img': img, 'createdAt': int(time.time()), 'viewed': {-1}, 'file_id': False } ) if __name__ == '__main__': try: main() except Exception as e: logging.error(e)
import time import feedparser from bs4 import BeautifulSoup import boto3 from PIL import Image import requests import logging NINEGAG_RSS_URL = 'http://www.15minutesoffame.be/9gag/rss/9GAG_-_Trending.atom' def main(): feed = feedparser.parse(NINEGAG_RSS_URL)['items'] table = boto3.resource('dynamodb', 'eu-west-1').Table('LeonardBot9gagPosts') for item in feed: title, post_id, img = item['title'], item['link'].split('/')[4], BeautifulSoup( item['summary'], 'lxml' ).find('img') if not hasattr(img, 'src'): continue img = img['src'] response = requests.get(img, stream=True) width, height = Image.open(response.raw).size if height / width >= 3: continue table.put_item( Item={ 'postId': post_id, 'title': title, 'img': img, 'createdAt': int(time.time()), 'viewed': {-1}, 'file_id': False } ) if __name__ == '__main__': try: main() except Exception as e: logging.error(e)
Fix ‘TypeError: Object [object Object] has no method 'addError'’
/** * Type */ var typeConstructor = function typeConstructor() { /** * Types */ var types = { 'string': isString, 'number': isNumber, 'function': isFunction, 'boolean': isBoolean, 'object': isObject, 'array': isArray, 'integer': isInteger, 'int': isInteger, 'null': isNull, 'any': returnTrue }; // Export return function type(property, propertyValue, attributeValue, propertyAttributes, callback) { /** * { * type: ['string', 'number'] * } */ if (isArray(attributeValue)) { var noError = attributeValue.some(function(type) { if (!hasProperty(types, type)) { throw new Error('Type ‘' + attributeValue + '’ is not supported.'); } return types[type](propertyValue); }); if (!noError) { this.addError(); } return callback(); /** * { * type: 'string' * } */ } else { if (!hasProperty(types, attributeValue)) { throw new Error('Type ‘' + attributeValue + '’ is not supported.'); } if (!types[attributeValue](propertyValue)) { this.addError(); } return callback(); } }; }; // Export Validation.prototype.addAttributeConstructor('type', typeConstructor);
/** * Type */ var typeConstructor = function typeConstructor() { /** * Types */ var types = { 'string': isString, 'number': isNumber, 'function': isFunction, 'boolean': isBoolean, 'object': isObject, 'array': isArray, 'integer': isInteger, 'int': isInteger, 'null': isNull, 'any': returnTrue }; // Export return function type(property, propertyValue, attributeValue, propertyAttributes, callback) { /** * { * type: ['string', 'number'] * } */ if (isArray(attributeValue)) { var noError = attributeValue.some(function(type) { if (!hasProperty(types, type)) { throw new Error('Type ‘' + attributeValue + '’ is not supported.'); } return types[type](propertyValue); }); if (!noError) { this.errors.addError(); } return callback(); /** * { * type: 'string' * } */ } else { if (!hasProperty(types, attributeValue)) { throw new Error('Type ‘' + attributeValue + '’ is not supported.'); } if (!types[attributeValue](propertyValue)) { this.addError(); } return callback(); } }; }; // Export Validation.prototype.addAttributeConstructor('type', typeConstructor);
Rename F to Function and f() to apply()
package cells; import com.jme3.math.ColorRGBA; import geometry.Position; import inventory.InventoryItem; import world.World; /** * A cell whose state is known for any given tick */ public enum AnimatedCell implements InventoryItem, WorldCell { OSCILLATOR("Oscillator", (tick) -> { if (tick % 2 == 0) { return ColorRGBA.Magenta; } else { return ColorRGBA.Yellow; } }); private final String name; private final Function function; /** * A color function of tick and position */ private interface Function { ColorRGBA apply(int tick); } /** * Create an animated cell with given name and a color function * @param name name of the animated cell * @param function color generating function */ AnimatedCell(String name, Function function) { this.name = name; this.function = function; } /** * Produce the name of this animated cell * @return name of this animated cell */ @Override public String getName() { return name; } /** * Produce the color of this animated cell from the given tick and position * @param tick current tick * @return current color of this animated cell */ @Override public ColorRGBA getColor(int tick, Position position) { return function.apply(tick); } @Override public void use(Position placeCursor, Position removeCursor, Position player) { World.getInstance().add(placeCursor, this); } }
package cells; import com.jme3.math.ColorRGBA; import geometry.Position; import inventory.InventoryItem; import world.World; /** * A cell whose state is known for any given tick */ public enum AnimatedCell implements InventoryItem, WorldCell { OSCILLATOR("Oscillator", (tick) -> { if (tick % 2 == 0) { return ColorRGBA.Magenta; } else { return ColorRGBA.Yellow; } }); private final String name; private final F function; /** * A color function of tick and position */ interface F { ColorRGBA f(int tick); } /** * Create an animated cell with given name and a color function * @param name name of the animated cell * @param function color generating function */ AnimatedCell(String name, F function) { this.name = name; this.function = function; } /** * Produce the name of this animated cell * @return name of this animated cell */ @Override public String getName() { return name; } /** * Produce the color of this animated cell from the given tick and position * @param tick current tick * @return current color of this animated cell */ @Override public ColorRGBA getColor(int tick, Position position) { return function.f(tick); } @Override public void use(Position placeCursor, Position removeCursor, Position player) { World.getInstance().add(placeCursor, this); } }
Use narrower rows for table
<!-- resources/views/testequipment/show_cal_dates.blade.php --> @extends('layouts.app') @section('content') <h2>Recent Test Equipment Calibration Dates</h2> <table class="table table-striped table-hover table-sm"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Manufacturer</th> <th scope="col">Model</th> <th scope="col">SN</th> <th scope="col">Description</th> <th scope="col">Location</th> <th scope="col">Age</th> <th scope="col">Room</th> <th scope="col">Last calibration</th> </tr> </thead> <tbody> @foreach ($testequipment as $t) <tr> <th scope="row">{{ $t->id }}</th> <td>{{ $t->manufacturer->manufacturer }}</td> <td>{{ $t->model }}</td> <td>{{ $t->serial_number }}</td> <td>{{ $t->description }}</td> <td>{{ $t->location->location }}</td> <td>{{ $t->age }}</td> <td>{{ $t->room }}</td> @foreach ($t->testdate as $td) @if($loop->first) <td>{{ $td->test_date }}</td> @endif @endforeach </tr> @endforeach </tbody> </table> @endsection
<!-- resources/views/testequipment/show_cal_dates.blade.php --> @extends('layouts.app') @section('content') <h2>Recent Test Equipment Calibration Dates</h2> <table class="table table-striped table-hover"> <thead> <tr> <th>ID</th> <th>Manufacturer</th> <th>Model</th> <th>SN</th> <th>Description</th> <th>Location</th> <th>Age</th> <th>Room</th> <th>Last calibration</th> </tr> </thead> <tbody> @foreach ($testequipment as $t) <tr> <td>{{ $t->id }}</td> <td>{{ $t->manufacturer->manufacturer }}</td> <td>{{ $t->model }}</td> <td>{{ $t->serial_number }}</td> <td>{{ $t->description }}</td> <td>{{ $t->location->location }}</td> <td>{{ $t->age }}</td> <td>{{ $t->room }}</td> @foreach ($t->testdate as $td) @if($loop->first) <td>{{ $td->test_date }}</td> @endif @endforeach </tr> @endforeach </tbody> </table> @endsection
Change dict-comprehension for python 2.6 compatibility.
from celery.app import default_app from celery.app import defaults def clean_quoted_config(config, key): # ini doesn't allow quoting, but lets support it to fit with celery config[key] = config[key].replace('"', '') TYPES_TO_OBJ = { 'any': (object, None), 'bool': (bool, defaults.str_to_bool), 'dict': (dict, eval), 'float': (float, float), 'int': (int, int), 'list': (list, eval), 'tuple': (tuple, eval), 'string': (str, str), } OPTIONS = ( (key, TYPES_TO_OBJ[opt.type]) for key, opt in defaults.flatten(defaults.NAMESPACES) ) def convert_celery_options(config): """ Converts celery options to apropriate types """ for key, value in config.iteritems(): opt_type = OPTIONS.get(key) if opt_type: if opt_type[0] == str: clean_quoted_config(config, key) elif opt_type[0] is object: try: config[key] = eval(value) except: pass # any can be anything; even a string elif not isinstance(value, opt_type[0]): config[key] = opt_type[1](value) def includeme(config): convert_celery_options(config.registry.settings) default_app.config_from_object(config.registry.settings) default_app.config = config
from celery.app import default_app from celery.app import defaults def clean_quoted_config(config, key): # ini doesn't allow quoting, but lets support it to fit with celery config[key] = config[key].replace('"', '') TYPES_TO_OBJ = { 'any': (object, None), 'bool': (bool, defaults.str_to_bool), 'dict': (dict, eval), 'float': (float, float), 'int': (int, int), 'list': (list, eval), 'tuple': (tuple, eval), 'string': (str, str), } OPTIONS = { key: TYPES_TO_OBJ[opt.type] for key, opt in defaults.flatten(defaults.NAMESPACES) } def convert_celery_options(config): """ Converts celery options to apropriate types """ for key, value in config.iteritems(): opt_type = OPTIONS.get(key) if opt_type: if opt_type[0] == str: clean_quoted_config(config, key) elif opt_type[0] is object: try: config[key] = eval(value) except: pass # any can be anything; even a string elif not isinstance(value, opt_type[0]): config[key] = opt_type[1](value) def includeme(config): convert_celery_options(config.registry.settings) default_app.config_from_object(config.registry.settings) default_app.config = config
Handle 404 on local server
const rewrite = require('connect-modrewrite'); const serveIndex = require('serve-index'); const serveStatic = require('serve-static'); module.exports = function (grunt) { return { livereload: { options: { hostname : '127.0.0.1', port : 443, protocol : 'https', base : 'dist', open : 'https://localhost.localdomain', middleware: (connect, options) => { const middlewares = [ require('connect-livereload')(), ]; const rules = [ '^/binary-static/(.*)$ /$1', ]; middlewares.push(rewrite(rules)); if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach((base) => { middlewares.push(serveStatic(base)); }); const directory = options.directory || options.base[options.base.length - 1]; middlewares.push(serveIndex(directory)); middlewares.push((req, res) => { const path_404 = `${options.base[0]}/404.html`; if (grunt.file.exists(path_404)) { require('fs').createReadStream(path_404).pipe(res); return; } res.statusCode(404); // 404.html not found res.end(); }); return middlewares; } } }, }; };
const rewrite = require('connect-modrewrite'); const serveIndex = require('serve-index'); const serveStatic = require('serve-static'); module.exports = function (grunt) { return { livereload: { options: { hostname : '127.0.0.1', port : 443, protocol : 'https', base : 'dist', open : 'https://localhost.localdomain', middleware: (connect, options) => { const middlewares = [ require('connect-livereload')(), ]; const rules = [ '^/binary-static/(.*)$ /$1', ]; middlewares.push(rewrite(rules)); if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach((base) => { middlewares.push(serveStatic(base)); }); const directory = options.directory || options.base[options.base.length - 1]; middlewares.push(serveIndex(directory)); return middlewares; } } }, }; };
Fix stability option in config
<?php namespace Che\BuildGuild; use Che\BuildGuild\Installer\GuildInstaller; use Che\BuildGuild\Installer\ScriptRunner; use Che\BuildGuild\Util\Environment; use Composer\Config; use Composer\Downloader\DownloadManager; use Composer\Downloader; use Composer\Json\JsonFile; use Composer\Repository\ComposerRepository; use Composer\Repository\InstalledFilesystemRepository; /** * Class BuildFactory * * @author Kirill chEbba Chebunin <[email protected]> */ class GuildFactory { private $config; private $env; public function __construct(GuildConfig $config, Environment $env) { $this->config = $config; $this->env = $env; } public function build() { $remoteRepository = new ComposerRepository( ['url' => $this->config->getRepository()], $this->env->getIo(), $this->config->getComposer() ); $localRepository = new InstalledFilesystemRepository(new JsonFile($this->config->getLocalRepository())); $installer = new GuildInstaller( $this->config->getInstallDir(), $this->createDownloadManager(), $this->env->getProcess(), $this->env->getFilesystem() ); return new Guild($remoteRepository, $localRepository, $installer, $this->config->getStability()); } private function createDownloadManager() { $dm = new DownloadManager(false, $this->env->getFilesystem()); $dm->setDownloader('tar', new Downloader\TarDownloader($this->env->getIo(), $this->config->getComposer())); return $dm; } }
<?php namespace Che\BuildGuild; use Che\BuildGuild\Installer\GuildInstaller; use Che\BuildGuild\Installer\ScriptRunner; use Che\BuildGuild\Util\Environment; use Composer\Config; use Composer\Downloader\DownloadManager; use Composer\Downloader; use Composer\Json\JsonFile; use Composer\Repository\ComposerRepository; use Composer\Repository\InstalledFilesystemRepository; /** * Class BuildFactory * * @author Kirill chEbba Chebunin <[email protected]> */ class GuildFactory { private $config; private $env; public function __construct(GuildConfig $config, Environment $env) { $this->config = $config; $this->env = $env; } public function build() { $remoteRepository = new ComposerRepository( ['url' => $this->config->getRepository()], $this->env->getIo(), $this->config->getComposer() ); $localRepository = new InstalledFilesystemRepository(new JsonFile($this->config->getLocalRepository())); $installer = new GuildInstaller( $this->config->getInstallDir(), $this->createDownloadManager(), $this->env->getProcess(), $this->env->getFilesystem() ); return new Guild($remoteRepository, $localRepository, $installer); } private function createDownloadManager() { $dm = new DownloadManager(false, $this->env->getFilesystem()); $dm->setDownloader('tar', new Downloader\TarDownloader($this->env->getIo(), $this->config->getComposer())); return $dm; } }
fix: Correct text-anchor to textAnchor property
'use strict'; import React, { Component } from 'react'; const DPCLogo = () => ( <svg width="570px" height="275px" style={{ background: 'rgba(79, 152, 201, 0.75)', letterSpacing: '3px' }}> <text x="50%" y="52.5%" textAnchor="middle" style={{ font: 'bold 100px/110px Georgia, sans-serif', fill: '#FFF', textAlign: 'center' }}>DPC</text> <text x="50%" y="72.5%" textAnchor="middle" fill="White" style={{ font: 'small-caps lighter 35px/35px Georgia, sans-serif', stroke: 'none', textAlign: 'center' }}>Davie Poplar Capital</text> <line x1="135px" y1="60%" x2="435px" y2="60%" style={{ stroke: '#FFF', strokeWidth: '1' }} /> <line x1="135px" y1="77.5%" x2="435px" y2="77.5%" style={{ stroke: '#FFF', strokeWidth: '1' }} /> Oh no! Your browser does not support inline SVG elements. Maybe try Chrome. </svg> ); export default DPCLogo;
'use strict'; import React, { Component } from 'react'; const DPCLogo = () => ( <svg width="570px" height="275px" style={{ background: 'rgba(79, 152, 201, 0.75)', letterSpacing: '3px' }}> <text x="50%" y="52.5%" text-anchor="middle" style={{ font: 'bold 100px/110px Georgia, sans-serif', fill: '#FFF', textAlign: 'center' }}>DPC</text> <text x="50%" y="72.5%" text-anchor="middle" fill="White" style={{ font: 'small-caps lighter 35px/35px Georgia, sans-serif', stroke: 'none', textAlign: 'center' }}>Davie Poplar Capital</text> <line x1="135px" y1="60%" x2="435px" y2="60%" style={{ stroke: '#FFF', strokeWidth: '1' }} /> <line x1="135px" y1="77.5%" x2="435px" y2="77.5%" style={{ stroke: '#FFF', strokeWidth: '1' }} /> Oh no! Your browser does not support inline SVG elements. Maybe try Chrome. </svg> ); export default DPCLogo;
refactor: Use spread operator to copy notification
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const now = new Date(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = { ...notification, read_at: now.toISOString() }; context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
const notifications = { namespaced: true, state: { isFetching: false, isErrored: false, error: [], notifications: [] }, computed: {}, getters: {}, mutations: { setNotifications (state, notifications) { state.notifications = notifications; state.isFetching = false; state.isErrored = false; state.error = []; }, setRequestError (state, error) { state.isFetching = false; state.isErrored = true; state.error = error; state.notifications = []; }, setFetchingState (state) { state.isFetching = true; state.isErrored = false; state.error = []; state.notifications = []; } }, actions: { fetchNotifications (context, options) { context.commit('setFetchingState'); context.rootState.client.getConfig(function (err, _, data) { if (err) { context.commit('setRequestError', err); return; } context.commit('setNotifications', data.unfiltered_organization_notifications); context.dispatch('markNotificationsAsRead', options); }); }, markNotificationsAsRead (context, options) { const now = new Date(); context.state.notifications.forEach(notification => { const { userId, apiKey } = options; if (!notification.read_at) { const notificationCopy = Object.assign({}, notification); notificationCopy.read_at = now.toISOString(); context.rootState.client.updateNotification(userId, apiKey, notificationCopy); } }); } } }; export default notifications;
Remove the whitespace in the render method of the ProgressStep component
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import ProgressStep from './ProgressStep'; class ProgressTracker extends PureComponent { render() { const { color, children, currentStep, allStepsCompleted } = this.props; const classNames = cx(theme['tracker']); return ( <Box className={classNames}> {React.Children.map(children, (child, index) => { const activeStep = Math.max(0, currentStep); return ( <ProgressStep {...child.props} active={allStepsCompleted ? false : index === activeStep} completed={allStepsCompleted || index < activeStep} color={color} /> ); })} </Box> ); } } ProgressTracker.propTypes = { /** Whether or not all steps are completed */ allStepsCompleted: PropTypes.bool, /** The number of the step which is currently active */ currentStep: PropTypes.number.isRequired, /** The steps to display inside the progress tracker */ children: PropTypes.node, /** Color theme of the progress tracker. */ color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']), }; ProgressTracker.defaultProps = { currentStep: 0, color: 'neutral', }; ProgressTracker.ProgressStep = ProgressStep; export default ProgressTracker;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import ProgressStep from './ProgressStep'; class ProgressTracker extends PureComponent { render() { const { color, children, currentStep, allStepsCompleted } = this.props; const classNames = cx(theme['tracker']); return ( <Box className={classNames}> {React.Children.map(children, (child, index) => { const activeStep = Math.max(0, currentStep); return ( <ProgressStep { ...child.props} active={allStepsCompleted ? false : index === activeStep} completed={allStepsCompleted || index < activeStep} color={color} /> ); })} </Box> ); } } ProgressTracker.propTypes = { /** Whether or not all steps are completed */ allStepsCompleted: PropTypes.bool, /** The number of the step which is currently active */ currentStep: PropTypes.number.isRequired, /** The steps to display inside the progress tracker */ children: PropTypes.node, /** Color theme of the progress tracker. */ color: PropTypes.oneOf(['neutral', 'mint', 'aqua', 'violet', 'gold', 'ruby']), }; ProgressTracker.defaultProps = { currentStep: 0, color: 'neutral', }; ProgressTracker.ProgressStep = ProgressStep; export default ProgressTracker;
Fix the path for sort partition list file
package io.dongyue.at15.tree.indexer.mapreduce.sort; import io.dongyue.at15.tree.indexer.mapreduce.Config; /** * Created by at15 on 16-1-1. * * @TODO test */ public class SortConfig implements Config { private String input; private String output; private String partition; private String meta; public String[] toArray() { String[] args = {input, output, partition, meta}; return args; } public void fromArray(String[] args) { setInput(args[0]); setOutput(args[1]); setPartition(args[2]); setMeta(args[3]); } public void fromBasePath(String base) { setInput(base + "/pre-sort/out"); setOutput(base + "/sort/out"); setPartition(base + "/part.lst"); setMeta(base + "/sort/meta"); } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } public String getPartition() { return partition; } public void setPartition(String partition) { this.partition = partition; } public String getMeta() { return meta; } public void setMeta(String meta) { this.meta = meta; } }
package io.dongyue.at15.tree.indexer.mapreduce.sort; import io.dongyue.at15.tree.indexer.mapreduce.Config; /** * Created by at15 on 16-1-1. * * @TODO test */ public class SortConfig implements Config { private String input; private String output; private String partition; private String meta; public String[] toArray() { String[] args = {input, output, partition, meta}; return args; } public void fromArray(String[] args) { setInput(args[0]); setOutput(args[1]); setPartition(args[2]); setMeta(args[3]); } public void fromBasePath(String base) { setInput(base + "/pre-sort/out"); setOutput(base + "/sort/out"); setPartition(base + "part.lst"); setMeta(base + "/sort/meta"); } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } public String getPartition() { return partition; } public void setPartition(String partition) { this.partition = partition; } public String getMeta() { return meta; } public void setMeta(String meta) { this.meta = meta; } }
Set min value to text field.
import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import Card, { CardActions, CardContent } from 'material-ui/Card'; import Button from 'material-ui/Button'; import TaxCalculator from '../libs/TaxCalculator'; class TextFields extends Component { state = { income: 0, expenses: 0 }; calculate() { const { income, expenses } = this.state; const taxInfo = TaxCalculator.getTaxInfo(income, expenses); this.props.handleUpdate(taxInfo); } render() { return ( <Card> <CardContent> <div> <TextField label="Income" type="number" value={this.state.income} onChange={event => this.setState({ income: event.target.value })} inputProps={{ min: 0, step: 10000 }} margin="normal" style={{ width: '100%' }} /> </div> <div> <TextField label="Expenses" type="number" value={this.state.expenses} onChange={event => this.setState({ expenses: event.target.value })} inputProps={{ min: 0, step: 10000 }} margin="normal" style={{ width: '100%' }} /> </div> </CardContent> <CardActions> <Button onClick={() => this.calculate()}>Calculate</Button> </CardActions> </Card> ); } } export default TextFields;
import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import Card, { CardActions, CardContent } from 'material-ui/Card'; import Button from 'material-ui/Button'; import TaxCalculator from '../libs/TaxCalculator'; class TextFields extends Component { state = { income: 0, expenses: 0 }; calculate() { const { income, expenses } = this.state; const taxInfo = TaxCalculator.getTaxInfo(income, expenses); this.props.handleUpdate(taxInfo); } render() { return ( <Card> <CardContent> <div> <TextField label="Income" type="number" value={this.state.income} onChange={event => this.setState({ income: event.target.value })} inputProps={{ step: '10000' }} margin="normal" style={{ width: '100%' }} /> </div> <div> <TextField label="Expenses" type="number" value={this.state.expenses} onChange={event => this.setState({ expenses: event.target.value })} inputProps={{ step: '10000' }} margin="normal" style={{ width: '100%' }} /> </div> </CardContent> <CardActions> <Button onClick={() => this.calculate()}>Calculate</Button> </CardActions> </Card> ); } } export default TextFields;
Add redirect route from root to setup
import React, { Component } from 'react' import { Router, Route, Redirect, hashHistory } from 'react-router' import './App.css' import Setup from './Setup' import SetupWelcome from './SetupWelcome' import SetupWifiPassword from './SetupWifiPassword' import SetupWifiSelection from './SetupWifiSelection' import SetupNuimo from './SetupNuimo' import SetupDevices from './SetupDevices' import SetupCompletion from './SetupCompletion' import SetupTutorialVideo from './SetupTutorialVideo' class App extends Component { render() { //TODO: Use `browserHistory` instead of `hashHistory`, see also https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md#browserhistory return ( <div className="App"> <Router history={hashHistory}> <Redirect from="/" to="/setup/welcome" /> <Redirect from="/setup" to="/setup/welcome" /> <Route path='setup' component={Setup}> <Route path='welcome' component={SetupWelcome} /> <Route path='wifi' component={SetupWifiSelection} /> <Route path='wifi/:ssid' component={SetupWifiPassword} /> <Route path='nuimo' component={SetupNuimo} /> <Route path='devices' component={SetupDevices} /> <Route path='completed' component={SetupCompletion} /> <Route path='tutorial' component={SetupTutorialVideo} /> </Route> </Router> </div> ); } } export default App
import React, { Component } from 'react' import { Router, Route, hashHistory } from 'react-router' import './App.css' import Setup from './Setup' import SetupWelcome from './SetupWelcome' import SetupWifiPassword from './SetupWifiPassword' import SetupWifiSelection from './SetupWifiSelection' import SetupNuimo from './SetupNuimo' import SetupDevices from './SetupDevices' import SetupCompletion from './SetupCompletion' import SetupTutorialVideo from './SetupTutorialVideo' class App extends Component { render() { //TODO: Use `browserHistory` instead of `hashHistory`, see also https://github.com/ReactTraining/react-router/blob/master/docs/guides/Histories.md#browserhistory return ( <div className="App"> <Router history={hashHistory}> <Route path='setup' component={Setup}> <Route path='welcome' component={SetupWelcome} /> <Route path='wifi' component={SetupWifiSelection} /> <Route path='wifi/:ssid' component={SetupWifiPassword} /> <Route path='nuimo' component={SetupNuimo} /> <Route path='devices' component={SetupDevices} /> <Route path='completed' component={SetupCompletion} /> <Route path='tutorial' component={SetupTutorialVideo} /> </Route> </Router> </div> ); } } export default App
Fix mistake printing wrong HTTP proto
package pewpew import ( "net/http" "net/http/httputil" "time" ) func runRequest(req http.Request, client *http.Client) (response *http.Response, stat RequestStat) { reqStartTime := time.Now() response, responseErr := (*client).Do(&req) reqEndTime := time.Now() if responseErr != nil { stat = RequestStat{ Proto: req.Proto, URL: req.URL.String(), Method: req.Method, StartTime: reqStartTime, EndTime: reqEndTime, Duration: reqEndTime.Sub(reqStartTime), StatusCode: 0, Error: responseErr, DataTransferred: 0, } return } //get size of request reqDump, _ := httputil.DumpRequestOut(&req, true) respDump, _ := httputil.DumpResponse(response, true) totalSizeSentBytes := len(reqDump) totalSizeReceivedBytes := len(respDump) totalSizeBytes := totalSizeSentBytes + totalSizeReceivedBytes stat = RequestStat{ Proto: response.Proto, URL: req.URL.String(), Method: req.Method, StartTime: reqStartTime, EndTime: reqEndTime, Duration: reqEndTime.Sub(reqStartTime), StatusCode: response.StatusCode, Error: responseErr, DataTransferred: totalSizeBytes, } return }
package pewpew import ( "net/http" "net/http/httputil" "time" ) func runRequest(req http.Request, client *http.Client) (response *http.Response, stat RequestStat) { reqStartTime := time.Now() response, responseErr := (*client).Do(&req) reqEndTime := time.Now() if responseErr != nil { stat = RequestStat{ Proto: req.Proto, URL: req.URL.String(), Method: req.Method, StartTime: reqStartTime, EndTime: reqEndTime, Duration: reqEndTime.Sub(reqStartTime), StatusCode: 0, Error: responseErr, DataTransferred: 0, } return } //get size of request reqDump, _ := httputil.DumpRequestOut(&req, true) respDump, _ := httputil.DumpResponse(response, true) totalSizeSentBytes := len(reqDump) totalSizeReceivedBytes := len(respDump) totalSizeBytes := totalSizeSentBytes + totalSizeReceivedBytes stat = RequestStat{ Proto: req.Proto, URL: req.URL.String(), Method: req.Method, StartTime: reqStartTime, EndTime: reqEndTime, Duration: reqEndTime.Sub(reqStartTime), StatusCode: response.StatusCode, Error: responseErr, DataTransferred: totalSizeBytes, } return }
Remove `width` and `height` from image service import [WEB-1908]
<?php namespace App\Console\Commands\Import; use App\Models\Collections\Image; class ImportImages extends AbstractImportCommand { protected $signature = 'import:images {page? : Page to begin importing from}'; protected $description = 'Import all image data from data-service-images'; public function handle() { $this->api = env('IMAGES_DATA_SERVICE_URL'); $this->import('images', Image::class, 'images', $this->argument('page') ?: 1); } // TODO: Optionally, use an inbound transformer here? protected function save($datum, $model, $transformer) { $this->info("Importing #{$datum->id}: {$datum->title}"); // TODO: When we make inbound transformers, provide a toggle between find() & findOrNew() $resource = $model::find($datum->id); // For this one, we should ignore entities that don't exist here if (!$resource) { return; } // TODO: Move this to an inbound transformer $metadata = $resource->metadata ?? (object) []; $metadata->lqip = $datum->lqip; $metadata->color = $datum->color; $metadata->colorfulness = round((float) $datum->colorfulness, 4); $resource->metadata = $metadata; $resource->save(); return $resource; } }
<?php namespace App\Console\Commands\Import; use App\Models\Collections\Image; class ImportImages extends AbstractImportCommand { protected $signature = 'import:images {page? : Page to begin importing from}'; protected $description = 'Import all image data from data-service-images'; public function handle() { $this->api = env('IMAGES_DATA_SERVICE_URL'); $this->import('images', Image::class, 'images', $this->argument('page') ?: 1); } // TODO: Optionally, use an inbound transformer here? protected function save($datum, $model, $transformer) { $this->info("Importing #{$datum->id}: {$datum->title}"); // TODO: When we make inbound transformers, provide a toggle between find() & findOrNew() $resource = $model::find($datum->id); // For this one, we should ignore entities that don't exist here if (!$resource) { return; } // TODO: Move this to an inbound transformer $metadata = $resource->metadata ?? (object) []; $metadata->lqip = $datum->lqip; $metadata->color = $datum->color; $metadata->width = $datum->width; $metadata->height = $datum->height; $metadata->colorfulness = round((float) $datum->colorfulness, 4); $resource->metadata = $metadata; $resource->save(); return $resource; } }
Fix ordering bug in NGO edit Fix issue #126
class CmsNgosListController{ constructor(NgoService, $filter, $state, DialogService){ 'ngInject'; var vm = this; this.$filter = $filter; this.$state = $state; this.DialogService = DialogService; this.NgoService = NgoService; this.listOrderByColumn = '-organisation'; this.NgoService.fetchAll().then(function(ngos) { vm.ngos = vm.$filter('orderBy')(ngos, [vm.listOrderByColumn], true); }); this.listFilter = { search: '' }; this.listPagination = { limit: 10, page: 1 }; this.onOrderChange = (order) => { return vm.ngos = vm.$filter('orderBy')(vm.ngos, [order], true); }; } togglePublished(ngo) { this.NgoService.togglePublished(ngo); } add() { this.ngo = {}; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } edit(ngo) { this.ngo = ngo; this.ngo.editMode = true; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } $onInit(){ } } export const CmsNgosListComponent = { templateUrl: './views/app/components/cms-ngos-list/cms-ngos-list.component.html', controller: CmsNgosListController, controllerAs: 'vm', bindings: {} }
class CmsNgosListController{ constructor(NgoService, $filter, $state, DialogService){ 'ngInject'; var vm = this; this.$filter = $filter; this.$state = $state; this.DialogService = DialogService; this.NgoService = NgoService; this.NgoService.fetchAll().then(function(response) { vm.ngos = response; }); this.listFilter = { search: '' }; this.listPagination = { limit: 10, page: 1 }; this.listOrderByColumn = '-organisation'; this.onOrderChange = (order) => { return vm.ngos = this.$filter('orderBy')(vm.ngos, [order], true); }; } togglePublished(ngo) { this.NgoService.togglePublished(ngo); } add() { this.ngo = {}; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } edit(ngo) { this.ngo = ngo; this.ngo.editMode = true; this.DialogService.fromTemplate('ngo', { controller: () => this, controllerAs: 'vm' }); } $onInit(){ } } export const CmsNgosListComponent = { templateUrl: './views/app/components/cms-ngos-list/cms-ngos-list.component.html', controller: CmsNgosListController, controllerAs: 'vm', bindings: {} }
Use Array.from instead of Array.prototype
chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) { var pattern, case_insensitive, color, opacity; var re, flags; pattern = items.pattern; if (!pattern) { pattern = 'WIP'; } case_insensitive = !!items.case_insensitive; if (case_insensitive) { flags = 'i'; } else { flags = ''; } re = new RegExp(pattern, flags); color = items.color || 'lightgray'; opacity = items.opacity || 0.7; var unhighlighter = function(element, re, color, opacity) { var items = element.querySelectorAll('.Box-row-link'); Array.from(items).filter(function(item) { if (item.innerText.match(re)) { element.style.backgroundColor = color; element.style.opacity = opacity; } }); }; var walk = function(re, color, opacity) { var elements = document.querySelectorAll('.js-issue-row'); Array.from(elements).forEach(function(element) { unhighlighter(element, re, color, opacity); }); } var target = document.querySelector('body'); var config = { childList: true, subtree: true }; var observer = new MutationObserver(function(mutations, self) { mutations.forEach(function(mutation) { if (mutation.type === 'childList') { walk(re, color, opacity); } }); }); observer.observe(target, config); walk(re, color, opacity); });
chrome.storage.local.get(['pattern', 'case_insensitive', 'color', 'opacity'], function(items) { var pattern, case_insensitive, color, opacity; var re, flags; pattern = items.pattern; if (!pattern) { pattern = 'WIP'; } case_insensitive = !!items.case_insensitive; if (case_insensitive) { flags = 'i'; } else { flags = ''; } re = new RegExp(pattern, flags); color = items.color || 'lightgray'; opacity = items.opacity || 0.7; var unhighlighter = function(element, re, color, opacity) { var items = element.querySelectorAll('.Box-row-link'); Array.prototype.filter.call(items, function(item) { if (item.innerText.match(re)) { element.style.backgroundColor = color; element.style.opacity = opacity; } }) }; var walk = function(re, color, opacity) { var elements = document.querySelectorAll('.js-issue-row'); Array.prototype.forEach.call(elements, function(element) { unhighlighter(element, re, color, opacity); }); } var target = document.querySelector('body'); var config = { childList: true, subtree: true }; var observer = new MutationObserver(function(mutations, self) { mutations.forEach(function(mutation) { if (mutation.type === 'childList') { walk(re, color, opacity); } }); }); observer.observe(target, config); walk(re, color, opacity); });
Change behaviour of onShow / onHide for community video - set whole html as data
Kwf.onJElementReady('.kwcAdvancedCommunityVideo', function(el, config) { el.data('config', config); }, {priority: -1}); Kwf.onJElementWidthChange('.kwcAdvancedCommunityVideo', function(el, config) { var config = el.data('config'); var iframe = el.find('iframe'); if(config.fullWidth) { var size = {}; switch(config.ratio) { case "16x9": size = { width: $(el).width(), height: ($(el).width() / 16) * 9 }; break; case "4x3": size = { width: $(el).width(), height: ($(el).width() / 4) * 3 }; break; default: return false; } iframe.width(size.width).height(size.height); } }, {defer: true}); Kwf.onJElementHide('.kwcAdvancedCommunityVideo', function(el) { el.data('iframeHtml', el.find('.communityVideoPlayer').html()); el.find('iframe').remove(); }); Kwf.onJElementShow('.kwcAdvancedCommunityVideo', function(el) { if(el.data('iframeHtml')) { el.find('.communityVideoPlayer').html(el.data('iframeHtml')); } });
Kwf.onJElementReady('.kwcAdvancedCommunityVideo', function(el, config) { el.data('config', config); }, {priority: -1}); Kwf.onJElementWidthChange('.kwcAdvancedCommunityVideo', function(el, config) { var config = el.data('config'); var iframe = el.find('iframe'); if(config.fullWidth) { var size = {}; switch(config.ratio) { case "16x9": size = { width: $(el).width(), height: ($(el).width() / 16) * 9 }; break; case "4x3": size = { width: $(el).width(), height: ($(el).width() / 4) * 3 }; break; default: return false; } iframe.width(size.width).height(size.height); } }, {defer: true}); Kwf.onJElementHide('.kwcAdvancedCommunityVideo', function(el) { var iframe = el.find('iframe'); iframe.parent().data('source', iframe.attr('src')); iframe.parent().data('iframeWidth', iframe.attr('width')); iframe.parent().data('iframeHeight', iframe.attr('height')); iframe.remove(); }); Kwf.onJElementShow('.kwcAdvancedCommunityVideo', function(el) { var iframeParent = el.find('.communityVideoPlayer'); if(iframeParent.data('source')) { iframeParent.html('<iframe src="'+iframeParent.data('source')+'" width="'+iframeParent.data('iframeWidth')+'" height="'+iframeParent.data('iframeHeight')+'" frameborder="0" allowfullscreen="true"></iframe>'); } });
Fix bug when locale isn't English.
/** * @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == "undefined" || !dosamigos) { var dosamigos = {}; } dosamigos.ckEditorWidget = (function ($) { var pub = { registerOnChangeHandler: function (id) { CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[id].updateElement(); $('#' + id).trigger('change'); return false; }); }, registerCsrfImageUploadHandler: function () { yii & $(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () { var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form'); var csrfName = yii.getCsrfParam(); $forms.each(function () { if (!$(this).find('input[name=' + csrfName + ']').length) { var csrfTokenInput = $('<input/>').attr({ 'type': 'hidden', 'name': csrfName }).val(yii.getCsrfToken()); $(this).append(csrfTokenInput); } }); }); } }; return pub; })(jQuery);
/** * @copyright Copyright (c) 2012-2015 2amigOS! Consulting Group LLC * @link http://2amigos.us * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ if (typeof dosamigos == "undefined" || !dosamigos) { var dosamigos = {}; } dosamigos.ckEditorWidget = (function ($) { var pub = { registerOnChangeHandler: function (id) { CKEDITOR && CKEDITOR.instances[id] && CKEDITOR.instances[id].on('change', function () { CKEDITOR.instances[id].updateElement(); $('#' + id).trigger('change'); return false; }); }, registerCsrfImageUploadHandler: function () { yii & $(document).off('click', '.cke_dialog_tabs a[title="Upload"]').on('click', '.cke_dialog_tabs a[title="Upload"]', function () { var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form'); var csrfName = yii.getCsrfParam(); $forms.each(function () { if (!$(this).find('input[name=' + csrfName + ']').length) { var csrfTokenInput = $('<input/>').attr({ 'type': 'hidden', 'name': csrfName }).val(yii.getCsrfToken()); $(this).append(csrfTokenInput); } }); }); } }; return pub; })(jQuery);
Add pubsub dependency for tests
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.0.1" setup(name='tgext.socketio', version=version, description="SocketIO support for TurboGears through gevent-socketio", long_description=README, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='turbogears2.extension, socketio, gevent', author='Alessandro Molina', author_email='[email protected]', url='http://github.com/amol-/tgext.socketio', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['tgext'], include_package_data=True, zip_safe=False, install_requires=[ 'gevent', 'gevent-socketio' ], test_suite='nose.collector', tests_require=[ 'TurboGears2', 'WebTest==1.4.3', 'repoze.who', 'nose', 'coverage', 'mock', 'pastedeploy', 'formencode', 'anypubsub' ], entry_points={ 'paste.server_runner': [ 'socketio = tgext.socketio.server:socketio_server_runner' ] } )
from setuptools import setup, find_packages import sys, os here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() except IOError: README = '' version = "0.0.1" setup(name='tgext.socketio', version=version, description="SocketIO support for TurboGears through gevent-socketio", long_description=README, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='turbogears2.extension, socketio, gevent', author='Alessandro Molina', author_email='[email protected]', url='http://github.com/amol-/tgext.socketio', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['tgext'], include_package_data=True, zip_safe=False, install_requires=[ 'gevent', 'gevent-socketio' ], test_suite='nose.collector', tests_require=[ 'TurboGears2', 'WebTest==1.4.3', 'repoze.who', 'nose', 'coverage', 'mock', 'pastedeploy', 'formencode' ], entry_points={ 'paste.server_runner': [ 'socketio = tgext.socketio.server:socketio_server_runner' ] } )
Add blank line after use
<?php namespace ClientBundle\Validator\Constraints; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Constraint; use Doctrine\ORM\EntityRepository; /** * Class ContainsCheckHaveAllContactTypesValidator */ class ContainsCheckHaveAllContactTypesValidator extends ConstraintValidator { protected $repository; /** * ContainsCheckHaveAllContactTypesValidator constructor. * @param EntityRepository $repository */ public function __construct(EntityRepository $repository) { $this->repository = $repository; } /** * @param mixed $client * @param Constraint $constraint */ public function validate($client, Constraint $constraint) { $clientContacts = $client->getContacts(); $allContactsTypeId = []; if (!empty($this->repository)) { $allContactsTypeId = $this->repository->getAllIds(); } $clientContactsTypeId = []; foreach ($clientContacts as $contact) { $clientContactsTypeId[] = $contact->getType()->getId(); } $result = array_diff($allContactsTypeId, $clientContactsTypeId); if (!empty($result)) { $this->context->buildViolation($constraint->message) ->setParameter('%name%', $client->getFirstName()) ->addViolation(); } } }
<?php namespace ClientBundle\Validator\Constraints; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Constraint; use Doctrine\ORM\EntityRepository; /** * Class ContainsCheckHaveAllContactTypesValidator */ class ContainsCheckHaveAllContactTypesValidator extends ConstraintValidator { protected $repository; /** * ContainsCheckHaveAllContactTypesValidator constructor. * @param EntityRepository $repository */ public function __construct(EntityRepository $repository) { $this->repository = $repository; } /** * @param mixed $client * @param Constraint $constraint */ public function validate($client, Constraint $constraint) { $clientContacts = $client->getContacts(); $allContactsTypeId = []; if (!empty($this->repository)) { $allContactsTypeId = $this->repository->getAllIds(); } $clientContactsTypeId = []; foreach ($clientContacts as $contact) { $clientContactsTypeId[] = $contact->getType()->getId(); } $result = array_diff($allContactsTypeId, $clientContactsTypeId); if (!empty($result)) { $this->context->buildViolation($constraint->message) ->setParameter('%name%', $client->getFirstName()) ->addViolation(); } } }
Include shortcode for Google Translate plugin.
<?php /** * The main template file. * */ get_header(); ?> <div class="page-content"> <div class="wrapper"> <div style="float: left; width: 200px;"> <?php get_sidebar(); ?> </div> <div style="float: right; width: 600px; text-align: left;"> <script src="//platform.linkedin.com/in.js" type="text/javascript"> /* <![CDATA[ */ lang: en_US /* ]]> */ </script> <!-- THIS IS WHERE THE WORDPRESS CODE TO INCLUDE CONTENT GOES...! --> <?php if ( is_page( 'Home' ) ) { get_template_part( 'latest-solicitations', get_post_format() ); } ?> <?php if(have_posts()) : while(have_posts()) : ?> <p> <?php the_post(); ?> <div class="alert alert-info"> <?php edit_post_link( 'Edit this page ', '', '' ); ?> &middot; <a href="<?php _e(get_delete_post_link()); ?>">Delete this page</a> </div> <?php the_content(); endwhile; endif; ?> </div> </div> </div> <?php do_shortcode('[google-translator]'); get_footer();
<?php /** * The main template file. * */ get_header(); ?> <div class="page-content"> <div class="wrapper"> <div style="float: left; width: 200px;"> <?php get_sidebar(); ?> </div> <div style="float: right; width: 600px; text-align: left;"> <script src="//platform.linkedin.com/in.js" type="text/javascript"> /* <![CDATA[ */ lang: en_US /* ]]> */ </script> <!-- THIS IS WHERE THE WORDPRESS CODE TO INCLUDE CONTENT GOES...! --> <?php if ( is_page( 'Home' ) ) { get_template_part( 'latest-solicitations', get_post_format() ); } ?> <?php if(have_posts()) : while(have_posts()) : ?> <p> <?php the_post(); ?> <div class="alert alert-info"> <?php edit_post_link( 'Edit this page ', '', '' ); ?> &middot; <a href="<?php _e(get_delete_post_link()); ?>">Delete this page</a> </div> <?php the_content(); endwhile; endif; ?> </div> </div> </div>
Add ability to pass autoNumeric config object to the decorator function
Ractive.decorators.autoNumeric = function (node, relativeKeypath, boundValue, autoNumericCfg) { var self = this, $el = $(node), context = self.getContext(node), updateModel = function () { context.set(relativeKeypath, $el.autoNumeric('getNumber')); }; if (typeof relativeKeypath !== 'string') { throw new Error('The binding name is required.'); } if (arguments.length !== 3) { throw new Error('Invalid number of arguments specified. Correct usage: as-autoNumeric="\'relativeKeypath\', relativeKeypath"'); } if (context.isBound()) { throw new Error('You cannot use two-way binding for the "autoNumeric" decorator.'); } $el.autoNumeric('init', autoNumericCfg) .autoNumeric('set', boundValue) .on('input', updateModel); return { update: function (newRelativeKeypath, newValue) { if (newRelativeKeypath !== relativeKeypath) { relativeKeypath = newRelativeKeypath; } if ($el.autoNumeric('getNumber') !== newValue) { $el.autoNumeric('set', newValue); } }, teardown: function () { $el.off('input', updateModel) .autoNumeric('destroy'); } }; };
Ractive.decorators.autoNumeric = function (node, relativeKeypath, boundValue) { var self = this, $el = $(node), context = self.getContext(node), updateModel = function () { context.set(relativeKeypath, $el.autoNumeric('getNumber')); }; if (typeof relativeKeypath !== 'string') { throw new Error('The binding name is required.'); } if (arguments.length !== 3) { throw new Error('Invalid number of arguments specified. Correct usage: as-autoNumeric="\'relativeKeypath\', relativeKeypath"'); } if (context.isBound()) { throw new Error('You cannot use two-way binding for the "autoNumeric" decorator.'); } $el.autoNumeric('init') .autoNumeric('set', boundValue) .on('input', updateModel); return { update: function (newRelativeKeypath, newValue) { if (newRelativeKeypath !== relativeKeypath) { relativeKeypath = newRelativeKeypath; } if ($el.autoNumeric('getNumber') !== newValue) { $el.autoNumeric('set', newValue); } }, teardown: function () { $el.off('input', updateModel) .autoNumeric('destroy'); } }; };
Add atlas as an argument for mesh initialisation.
from atlases import BoxAtlas class RectangularMesh(object): def __init__(self, atlas, d, meshname='mesh'): if not isinstance(d, (tuple, list)) or len(d) != 3: raise ValueError('Cellsize d must be a tuple of length 3.') elif d[0] <= 0 or d[1] <= 0 or d[2] <= 0: raise ValueError('Cellsize dimensions must be positive.') else: self.d = d if not isinstance(atlas, BoxAtlas): raise ValueError('atlas must be a string.') else: self.atlas = atlas if not isinstance(meshname, str): raise ValueError('name must be a string.') else: self.meshname = meshname def get_mif(self): # Create mif string. mif = '# RectangularMesh\n' mif += 'Specify Oxs_RectangularMesh:{}'.format(self.meshname) + ' {\n' mif += '\tcellsize {' mif += ' {} {} {} '.format(self.d[0], self.d[1], self.d[2]) mif += '}\n' mif += '\tatlas {}\n'.format(self.atlas.name) mif += '}\n\n' return mif
class RectangularMesh(object): def __init__(self, d, atlas='atlas', meshname='mesh'): if not isinstance(d, (tuple, list)) or len(d) != 3: raise ValueError('Cellsize d must be a tuple of length 3.') elif d[0] <= 0 or d[1] <= 0 or d[2] <= 0: raise ValueError('Cellsize dimensions must be positive.') else: self.d = d if not isinstance(atlas, str): raise ValueError('atlas must be a string.') else: self.atlas = atlas if not isinstance(meshname, str): raise ValueError('name must be a string.') else: self.meshname = meshname def get_mif(self): # Create mif string. mif = '# RectangularMesh\n' mif += 'Specify Oxs_RectangularMesh:{}'.format(self.meshname) + ' {\n' mif += '\tcellsize {' mif += ' {} {} {} '.format(self.d[0], self.d[1], self.d[2]) mif += '}\n' mif += '\tatlas {}\n'.format(self.atlas) mif += '}\n\n' return mif
[MOD] Use browse record instead of ids
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants = self.filtered(lambda x: True) for quant2merge in self: if (quant2merge in pending_quants and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost pending_quants -= quant quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, api class StockQuant(models.Model): _inherit = 'stock.quant' @api.multi def merge_stock_quants(self): pending_quants_ids = self.ids for quant2merge in self: if (quant2merge.id in pending_quants_ids and not quant2merge.reservation_id): quants = self.search( [('id', '!=', quant2merge.id), ('product_id', '=', quant2merge.product_id.id), ('lot_id', '=', quant2merge.lot_id.id), ('package_id', '=', quant2merge.package_id.id), ('location_id', '=', quant2merge.location_id.id), ('reservation_id', '=', False), ('propagated_from_id', '=', quant2merge.propagated_from_id.id)]) for quant in quants: if (self._get_latest_move(quant2merge) == self._get_latest_move(quant)): quant2merge.qty += quant.qty quant2merge.cost += quant.cost if quant.id in pending_quants_ids: pending_quants_ids.remove(quant.id) quant.sudo().unlink() @api.model def quants_unreserve(self, move): quants = move.reserved_quant_ids super(StockQuant, self).quants_unreserve(move) quants.merge_stock_quants()
Fix time selection modal bug
const $ = require('jquery'); import { getPlayer } from './player/player'; import { insertTimestamp, convertTimestampToSeconds, formatMilliseconds } from './timestamps'; let timeSelectionModalActive = false; const $timeSelection = $('.controls .time-selection'); const hide = () => { timeSelectionModalActive = false; $('.controls .time-selection').removeClass('active'); } const show = () => { timeSelectionModalActive = true; const player = getPlayer(); if (timeSelectionModalActive === true) { $timeSelection.addClass('active'); $timeSelection.find('input') .off() .val(formatMilliseconds(player.getTime())) .keyup(onTimeSelectionModalSubmit) .focus() .select(); } else { $('.controls .time-selection').removeClass('active'); } function onTimeSelectionModalSubmit(ev) { if (ev.keyCode === 13) { // return key const time = $(this).val(); if (time.indexOf(':') > -1) { player.setTime(convertTimestampToSeconds(time)); } else { // assume user is thinking in minutes player.setTime(parseFloat(time) * 60); } hide(); } } } const toggle = () => { if (timeSelectionModalActive) { hide(); } else { show(); } } export default { toggle, show, hide }
const $ = require('jquery'); import { getPlayer } from './player/player'; import { insertTimestamp, convertTimestampToSeconds, formatMilliseconds } from './timestamps'; let timeSelectionModalActive = false; const $timeSelection = $('.controls .time-selection'); const hide = () => { timeSelectionModalActive = false; $('.controls .time-selection').removeClass('active'); } const show = () => { timeSelectionModalActive = true; const player = getPlayer(); if (timeSelectionModalActive === true) { $timeSelection.addClass('active'); $timeSelection.find('input') .off() .val(formatMilliseconds(player.getTime())) .keyup(onTimeSelectionModalSubmit) .focus() .select(); } else { $('.controls .time-selection').removeClass('active'); } function onTimeSelectionModalSubmit(ev) { if (event.keyCode === 13) { // return key const time = $(this).val(); if (time.indexOf(':') > -1) { player.setTime(convertTimestampToSeconds(time)); } else { // assume user is thinking in minutes player.setTime(parseFloat(time) * 60); } hide(); } } } const toggle = () => { if (timeSelectionModalActive) { hide(); } else { show(); } } export default { toggle, show, hide }
Implement default controller to redirect in function of role
<?php namespace Project\AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use JMS\SecurityExtraBundle\Annotation\Secure; class DefaultController extends Controller { /** * Routes to the right application part in function of role. * * @Secure(roles={"ROLE_MANAGER", "ROLE_SPEAKER", "ROLE_STUDENT"}) * @Route("/", name="project_app_index") * @Method("GET") * @Template() */ public function indexAction() { // Get logged in user $user = $this->getUser(); $userRoles = $user->getRoles(); if(in_array('ROLE_MANAGER', $userRoles)) { // Redirect to promotion gestion return $this->redirect($this->generateUrl('promotion')); } elseif(in_array('ROLE_SPEAKER', $userRoles)) { // Redirect to missing list return $this->redirect($this->generateUrl('missing')); } elseif(in_array('ROLE_STUDENT', $userRoles)) { // Redirect to the agenda return $this->redirect($this->generateUrl('project_app_agenda_index')); } } }
<?php namespace Project\AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use JMS\SecurityExtraBundle\Annotation\Secure; use Project\AppBundle\Entity\User; use Project\AppBundle\Form\UserType; class DefaultController extends Controller { /** * Lists all User entities. * * @Secure(roles={"ROLE_MANAGER", "ROLE_SPEAKER", "ROLE_STUDENT"}) * @Route("/", name="project_app_index") * @Method("GET") * @Template() */ public function indexAction() { // Get logged in user $user = $this->getUser(); $userRoles = $user->getRoles(); if(in_array('ROLE_MANAGER', $userRoles)) { return $this->redirect($this->generateUrl('promotion')); } elseif(in_array('ROLE_SPEAKER', $userRoles)) { return $this->redirect($this->generateUrl('missing')); } elseif(in_array('ROLE_STUDENT', $userRoles)) { return $this->redirect($this->generateUrl('project_app_agenda_index')); } } }
Fix find configuration by prefix
<?php namespace CommonBundle\Repository\General; use Doctrine\ORM\EntityRepository; /** * Config * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Config extends EntityRepository { public function findAll() { $query = $this->_em->createQueryBuilder(); $resultSet = $query->select('c') ->from('CommonBundle\Entity\General\Config', 'c') ->orderBy('c.key', 'ASC') ->getQuery() ->getResult(); return $resultSet; } public function findAllByPrefix($prefix) { $configs = $this->_em ->createQuery('SELECT c FROM CommonBundle\Entity\General\Config c WHERE c.key LIKE \'' . $prefix . '.%\'') ->getResult(); $result = array(); foreach ($configs as $config) { $key = $config->getKey(); $value = $config->getValue(); $key = str_replace($prefix . '.','', $key); $result[$key] = $value; } return $result; } public function getConfigValue($key) { $config = $this->find($key); if($config === null) throw new \RuntimeException('Configuration entry ' . $key . ' not found'); return $config->getValue(); } }
<?php namespace CommonBundle\Repository\General; use Doctrine\ORM\EntityRepository; /** * Config * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Config extends EntityRepository { public function findAll() { $query = $this->_em->createQueryBuilder(); $resultSet = $query->select('c') ->from('CommonBundle\Entity\General\Config', 'c') ->orderBy('c.key', 'ASC') ->getQuery() ->getResult(); return $resultSet; } public function findAllByPrefix($prefix) { $configs = $this->_em ->createQuery('SELECT c FROM Litus\Entity\General\Config c WHERE c.key LIKE \'' . $prefix . '.%\'') ->getResult(); $result = array(); foreach ($configs as $config) { $key = $config->getKey(); $value = $config->getValue(); $key = str_replace($prefix . '.','', $key); $result[$key] = $value; } return $result; } public function getConfigValue($key) { $config = $this->find($key); if($config === null) throw new \RuntimeException('Configuration entry ' . $key . ' not found'); return $config->getValue(); } }
Change default api url to admin.openpension.org.il
var baseUrl = "http://admin.openpension.org.il/"; var quarter2String = { 0: "ראשון", 1: "שני", 2: "שלישי", 3: "רביעי" }; var Model = function() { var self = this; self.name = ko.observable(""); self.quarterId = ko.observable(-1); self.managingBody = ko.observable(""); self.fund = ko.observable(""); self.quarter = ko.observable(""); self.url = ko.observable(""); self.getNext= function() { self.url(""); $.getJSON(baseUrl + "funds_quarters/missing/random", function(data) { console.log(data); self.quarterId(data.id); self.managingBody(data.managing_body_heb); self.fund(data.fund_name); self.quarter(quarter2String[data.quarter] + " " + data.year); }); }; self.sendQuarter = function() { $.ajax({ url: baseUrl + "funds_quarters/" + self.quarterId(), type: "PUT", dataType: "json", data: { name: self.name(), url: self.url() }}) .done(function() { self.getNext(); }) .fail(function() { // TODO }); }; }; var model = new Model(); // Load first model.getNext(); ko.applyBindings(model);
var baseUrl = "http://localhost:4000/"; var quarter2String = { 0: "ראשון", 1: "שני", 2: "שלישי", 3: "רביעי" }; var Model = function() { var self = this; self.name = ko.observable(""); self.quarterId = ko.observable(-1); self.managingBody = ko.observable(""); self.fund = ko.observable(""); self.quarter = ko.observable(""); self.url = ko.observable(""); self.getNext= function() { self.url(""); $.getJSON(baseUrl + "funds_quarters/missing/random", function(data) { console.log(data); self.quarterId(data.id); self.managingBody(data.managing_body_heb); self.fund(data.fund_name); self.quarter(quarter2String[data.quarter] + " " + data.year); }); }; self.sendQuarter = function() { $.ajax({ url: baseUrl + "funds_quarters/" + self.quarterId(), type: "PUT", dataType: "json", data: { name: self.name(), url: self.url() }}) .done(function() { self.getNext(); }) .fail(function() { // TODO }); }; }; var model = new Model(); // Load first model.getNext(); ko.applyBindings(model);
bii: Call fetch_and_import on the right module
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): cont.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
# /ciscripts/coverage/bii/coverage.py # # Submit coverage totals for a bii project to coveralls # # See /LICENCE.md for Copyright information """Submit coverage totals for a bii project to coveralls.""" import errno import os from contextlib import contextmanager def _move_ignore_enoent(src, dst): """Move src to dst, ignoring ENOENT.""" try: os.rename(src, dst) except OSError as error: if error.errno != errno.ENOENT: raise error @contextmanager def _bii_deps_in_place(cont): """Move bii project dependencies into layout. The coverage step may require these dependencies to be present. """ bii_dir = os.path.join(cont.named_cache_dir("cmake-build"), "bii") _move_ignore_enoent(bii_dir, os.path.join(os.getcwd(), "bii")) try: yield finally: _move_ignore_enoent(os.path.join(os.getcwd(), "bii"), bii_dir) def run(cont, util, shell, argv=None): """Submit coverage total to coveralls, with bii specific preparation.""" with _bii_deps_in_place(cont): util.fetch_and_import("coverage/cmake/coverage.py").run(cont, util, shell, argv)
Fix mypy error by asserting Since we just asked `is_panel_active`, the following `find_output_panel` *must* succeed. So we `assert panel` to tell it mypy.
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""): window = self.window if is_panel_active(window): panel = window.find_output_panel(PANEL_NAME) assert panel else: panel = window.create_output_panel(PANEL_NAME) syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax" try: # Try the resource first, in case we're in the middle of an upgrade sublime.load_resource(syntax_path) except Exception: return panel.assign_syntax(syntax_path) scroll_to = panel.size() msg = msg.rstrip() + '\n\n\n' panel.set_read_only(False) panel.run_command('append', {'characters': msg}) panel.set_read_only(True) panel.show(scroll_to) window.run_command("show_panel", {"panel": OUTPUT_PANEL}) class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand): def run(self): self.window.destroy_output_panel(PANEL_NAME) def is_panel_active(window): return window.active_panel() == OUTPUT_PANEL
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""): window = self.window if is_panel_active(window): panel = window.find_output_panel(PANEL_NAME) else: panel = window.create_output_panel(PANEL_NAME) syntax_path = "Packages/SublimeLinter/panel/message_view.sublime-syntax" try: # Try the resource first, in case we're in the middle of an upgrade sublime.load_resource(syntax_path) except Exception: return panel.assign_syntax(syntax_path) scroll_to = panel.size() msg = msg.rstrip() + '\n\n\n' panel.set_read_only(False) panel.run_command('append', {'characters': msg}) panel.set_read_only(True) panel.show(scroll_to) window.run_command("show_panel", {"panel": OUTPUT_PANEL}) class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand): def run(self): self.window.destroy_output_panel(PANEL_NAME) def is_panel_active(window): return window.active_panel() == OUTPUT_PANEL
Fix checking type of data (array is recognized as an object)
(function () { 'use strict'; var mod = angular.module('components.utils', []); mod.factory('Utils', ['$window', function Utils($window) { function stringify(obj, prefix) { var str = []; for(var p in obj) { var k = prefix ? prefix + '[' + p + ']' : p, v = obj[p]; str.push(typeof v == 'object' ? stringify(v, k) : encodeURIComponent(k) + '=' + encodeURIComponent(v)); } return str.join('&'); } function objectToFormData(data) { var formData = new $window.FormData(); for(var i in data) { if(_.isArray(data[i])) { for(var k in data[i]) { formData.append(i + '[]', data[i][k]); } } else if(_.isObject(data[i])) { for(var j in data[i]) { formData.append(i + '[' + j + ']', data[i][j]); } } else { formData.append(i, data[i]); } } return formData; } return { stringify: stringify, objectToFormData: objectToFormData }; }]); }());
(function () { 'use strict'; var mod = angular.module('components.utils', []); mod.factory('Utils', ['$window', function Utils($window) { function stringify(obj, prefix) { var str = []; for(var p in obj) { var k = prefix ? prefix + '[' + p + ']' : p, v = obj[p]; str.push(typeof v == 'object' ? stringify(v, k) : encodeURIComponent(k) + '=' + encodeURIComponent(v)); } return str.join('&'); } function objectToFormData(data) { var formData = new $window.FormData(); for(var i in data) { if(_.isObject(data[i])) { for(var j in data[i]) { formData.append(i + '[' + j + ']', data[i][j]); } } else if(_.isArray(data[i])) { for(var k in data[i]) { formData.append(i + '[]', data[i][k]); } } else { formData.append(i, data[i]); } } return formData; } return { stringify: stringify, objectToFormData: objectToFormData }; }]); }());
Set webpack publicPath to /static/
var path = require("path"); var HTMLPlugin = require("html-webpack-plugin"); var CleanPlugin = require("clean-webpack-plugin"); var config = { entry: "./src/js/app.js", module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loaders: ["babel-loader", "eslint-loader"] }, {test: /\.css$/, loader: "style!css"}, {test: /\.woff$/, loader: "url?limit=100000"} ] }, resolve: { alias: {virtool: path.resolve(__dirname, "./src")} }, node: { fs: "empty" }, output: { path: "dist", filename: "app.[hash].js", publicPath: "/static/" }, eslint: { configFile: "./.eslintrc" }, plugins: [ new HTMLPlugin({ filename: "index.html", title: "Virtool", favicon: "./src/images/favicon.ico", template: "./src/index.html", inject: "body" }), new CleanPlugin(["dist"], { verbose: true }) ], progress: true, colors: true, watch: true }; module.exports = config;
var path = require("path"); var HTMLPlugin = require("html-webpack-plugin"); var CleanPlugin = require("clean-webpack-plugin"); var config = { entry: "./src/js/app.js", module: { loaders: [ { test: /\.js$/, exclude: /(node_modules)/, loaders: ["babel-loader", "eslint-loader"] }, {test: /\.css$/, loader: "style!css"}, {test: /\.woff$/, loader: "url?limit=100000"} ] }, resolve: { alias: {virtool: path.resolve(__dirname, "./src")} }, node: { fs: "empty" }, output: { path: "dist", filename: "app.[hash].js" }, eslint: { configFile: "./.eslintrc" }, plugins: [ new HTMLPlugin({ filename: "index.html", title: "Virtool", favicon: "./src/images/favicon.ico", template: "./src/index.html", inject: "body" }), new CleanPlugin(["dist"], { verbose: true }) ], progress: true, colors: true, watch: true }; module.exports = config;
Add note about admin review link
<?php namespace Rogue\Http\Transformers; use Rogue\Models\Post; use League\Fractal\TransformerAbstract; class PhoenixGalleryTransformer extends TransformerAbstract { /** * Transform resource data. * * @param \Rogue\Models\Photo $photo * @return array */ public function transform(Post $post) { $signup = $post->signup; $result = [ 'id' => $post->postable_id, 'status' => $post->status, 'caption' => $post->caption, // Add link to review reportback item in Rogue here once that page exists // 'uri' => 'link_goes_here' 'media' => [ 'uri' => $post->file_url, 'type' => 'image', ], 'created_at' => $post->created_at->toIso8601String(), 'reportback' => [ 'id' => $signup->id, 'created_at' => $signup->created_at->toIso8601String(), 'updated_at' => $signup->updated_at->toIso8601String(), 'quantity' => $signup->quantity, 'why_participated' => $signup->why_participated, 'flagged' => 'false', ], ]; return $result; } }
<?php namespace Rogue\Http\Transformers; use Rogue\Models\Post; use League\Fractal\TransformerAbstract; class PhoenixGalleryTransformer extends TransformerAbstract { /** * Transform resource data. * * @param \Rogue\Models\Photo $photo * @return array */ public function transform(Post $post) { $signup = $post->signup; $result = [ 'id' => $post->postable_id, 'status' => $post->status, 'caption' => $post->caption, 'uri' => $post->file_url, 'media' => [ 'uri' => $post->file_url, 'type' => 'image', ], 'created_at' => $post->created_at->toIso8601String(), 'reportback' => [ 'id' => $signup->id, 'created_at' => $signup->created_at->toIso8601String(), 'updated_at' => $signup->updated_at->toIso8601String(), 'quantity' => $signup->quantity, 'why_participated' => $signup->why_participated, 'flagged' => 'false', ], ]; return $result; } }
Update `djangorestframework` from 2.4.3 to 2.4.4
from setuptools import find_packages, setup version = '6.0.0' install_requires = ( 'djangorestframework>=2.4.4,<3', 'incuna_mail>=2.0.0,<3', ) extras_require = { 'avatar': [ 'django-imagekit>=3.2', ], 'utils': [ 'raven>=5.1.1', ], } setup( name='django-user-management', packages=find_packages(), include_package_data=True, version=version, description='User management model mixins and api views.', long_description='', keywords='django rest framework user management api', author='Incuna', author_email='[email protected]', url='https://github.com/incuna/django-user-management/', install_requires=install_requires, extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities', ], )
from setuptools import find_packages, setup version = '6.0.0' install_requires = ( 'djangorestframework>=2.4.3,<3', 'incuna_mail>=2.0.0,<3', ) extras_require = { 'avatar': [ 'django-imagekit>=3.2', ], 'utils': [ 'raven>=5.1.1', ], } setup( name='django-user-management', packages=find_packages(), include_package_data=True, version=version, description='User management model mixins and api views.', long_description='', keywords='django rest framework user management api', author='Incuna', author_email='[email protected]', url='https://github.com/incuna/django-user-management/', install_requires=install_requires, extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities', ], )
Comment out authentification checkker in order to remove failures from PHP tests
<?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Annotation\Route; class APIController extends Controller { /** * @param $request Request * @throws NotFoundHttpException - if the webservice is not found (status code 404) * @return \Symfony\Component\HttpFoundation\JsonResponse * @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true}) */ public function apiAction(Request $request, $namespace, $classname){ try{ $service = $this->get('app.api.webservice')->factory($namespace, $classname); } catch (Exception $e){ throw $this->createNotFoundException('Webservice not found in the API'); } $queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all())); $user = null; // if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){ // $user = $this->get('security.token_storage')->getToken()->getUser(); // } $result = $service->execute($queryData, $user); $response = $this->json($result); $response->headers->set('Access-Control-Allow-Origin', '*'); return $response; } }
<?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Annotation\Route; class APIController extends Controller { /** * @param $request Request * @throws NotFoundHttpException - if the webservice is not found (status code 404) * @return \Symfony\Component\HttpFoundation\JsonResponse * @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true}) */ public function apiAction(Request $request, $namespace, $classname){ try{ $service = $this->get('app.api.webservice')->factory($namespace, $classname); } catch (Exception $e){ throw $this->createNotFoundException('Webservice not found in the API'); } $queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all())); $user = null; if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){ $user = $this->get('security.token_storage')->getToken()->getUser(); } $result = $service->execute($queryData, $user); $response = $this->json($result); $response->headers->set('Access-Control-Allow-Origin', '*'); return $response; } }
Remove warning when no configuration is defined
<?php namespace Ontic\NoFraud\Utils; use Ontic\NoFraud\Interfaces\IPlugin; use Symfony\Component\Yaml\Yaml; class PluginUtils { /** * @return IPlugin[] */ public static function loadPlugins() { $plugins = []; $configurationFile = PROJECT_ROOT . '/data/config.yml'; $configuration = Yaml::parse(file_get_contents($configurationFile)); foreach($configuration['plugins'] as $pluginConfig) { $code = $pluginConfig['code']; $weight = isset($pluginConfig['weight']) ? $pluginConfig['weight'] : 1; $authoritative = isset($pluginConfig['authoritative']) ? $pluginConfig['authoritative'] : false; $configuration = isset($pluginConfig['config']) ? $pluginConfig['config'] : []; $pluginClass = 'Ontic\NoFraud\Plugins\\' . static::toPascalCase($code) . 'Plugin'; $plugins[] = new $pluginClass($weight, $authoritative, $configuration); } return $plugins; } private static function toPascalCase($string) { return preg_replace_callback("/(?:^|_)([a-z])/", function($matches) { return strtoupper($matches[1]); }, $string); } }
<?php namespace Ontic\NoFraud\Utils; use Ontic\NoFraud\Interfaces\IPlugin; use Symfony\Component\Yaml\Yaml; class PluginUtils { /** * @return IPlugin[] */ public static function loadPlugins() { $plugins = []; $configurationFile = PROJECT_ROOT . '/data/config.yml'; $configuration = Yaml::parse(file_get_contents($configurationFile)); foreach($configuration['plugins'] as $pluginConfig) { $code = $pluginConfig['code']; $weight = isset($pluginConfig['weight']) ? $pluginConfig['weight'] : 1; $authoritative = isset($pluginConfig['authoritative']) ? $pluginConfig['authoritative'] : false; $configuration = $pluginConfig['config']; $pluginClass = 'Ontic\NoFraud\Plugins\\' . static::toPascalCase($code) . 'Plugin'; $plugins[] = new $pluginClass($weight, $authoritative, $configuration); } return $plugins; } private static function toPascalCase($string) { return preg_replace_callback("/(?:^|_)([a-z])/", function($matches) { return strtoupper($matches[1]); }, $string); } }
Add handlebars to require js config
/* Sitewide require configuration * This file MUST be loaded asynchronously on all pages for require to work */ // These settings are mirrored in build.main.js, if you're going to change them check there too requirejs.config({ paths: { jquery: '../lib/jquery-1.10.2.min', bootstrap: '../lib/bootstrap', Leaflet: '../lib/leaflet', 'Leaflet-google': '../lib/leaflet-google', Handlebars: '../lib/handlebars', async: '../lib/require-plugins/async', text: '../lib/require-plugins/text' }, shim: { 'bootstrap': { // http://stackoverflow.com/a/13556882/639619 // Don't use the return value from bootstrap, it should attach stuff to the // $ object, require jquery and use it instead deps: ['jquery'], exports: '$.fn.popover' }, 'Leaflet': { exports: 'L' }, 'Leaflet-google': { deps: ['Leaflet'], exports: 'L.Google' }, '../lib/response': { deps: ['jquery'], exports: 'Response', init: function ($) { return this.Response.noConflict(); } }, 'Handlebars': { exports: 'Handlebars' } }, enforceDefine: true });
/* Sitewide require configuration * This file MUST be loaded asynchronously on all pages for require to work */ // These settings are mirrored in build.main.js, if you're going to change them check there too requirejs.config({ paths: { jquery: '../lib/jquery-1.10.2.min', bootstrap: '../lib/bootstrap', Leaflet: '../lib/leaflet', 'Leaflet-google': '../lib/leaflet-google', async: '../lib/require-plugins/async' }, shim: { 'bootstrap': { // http://stackoverflow.com/a/13556882/639619 // Don't use the return value from bootstrap, it should attach stuff to the // $ object, require jquery and use it instead deps: ['jquery'], exports: '$.fn.popover' }, 'Leaflet': { exports: 'L' }, 'Leaflet-google': { deps: ['Leaflet'], exports: 'L.Google' }, '../lib/response': { deps: ['jquery'], exports: 'Response', init: function ($) { return this.Response.noConflict(); } } }, enforceDefine: true });
Make sure el exists before manipulating it Otherwise it crashes when the overlay is open in the initial store state.
// essentials import React from 'react' import { connect } from 'react-redux' // actions import toggleTracklistWindow from '../actions/toggleTracklistWindow' import togglePlaylistWindow from '../actions/togglePlaylistWindow' const Overlay = React.createClass({ getInitialState() { return { el: null } }, componentDidMount() { const overlay = document.querySelector('.overlay') this.setState({ el: overlay }) }, toggle() { this.props.dispatch(togglePlaylistWindow(false)) this.props.dispatch(toggleTracklistWindow(false)) setTimeout(() => { this.state.el.style.display = 'none' }, 500) }, render() { let cn if (this.props.pVisible || this.props.tVisible) { cn = `overlay visible` if (this.state.el) { this.state.el.style.display = 'block' } } else { cn = `overlay` } return ( <div className={cn} onClick={this.toggle} > </div> ) } }) const mapStateToProps = store => ({ pVisible: store.playlistWindowVisible, tVisible: store.tracklistWindowVisible }) export default connect(mapStateToProps)(Overlay)
// essentials import React from 'react' import { connect } from 'react-redux' // actions import toggleTracklistWindow from '../actions/toggleTracklistWindow' import togglePlaylistWindow from '../actions/togglePlaylistWindow' const Overlay = React.createClass({ getInitialState() { return { el: null } }, componentDidMount() { const overlay = document.querySelector('.overlay') this.setState({ el: overlay }) }, toggle() { this.props.dispatch(togglePlaylistWindow(false)) this.props.dispatch(toggleTracklistWindow(false)) setTimeout(() => { this.state.el.style.display = 'none' }, 500) }, render() { let cn if (this.props.pVisible || this.props.tVisible) { cn = `overlay visible` this.state.el.style.display = 'block' } else { cn = `overlay` } return ( <div className={cn} onClick={this.toggle} > </div> ) } }) const mapStateToProps = store => ({ pVisible: store.playlistWindowVisible, tVisible: store.tracklistWindowVisible }) export default connect(mapStateToProps)(Overlay)
Fix wrong type (Travis complaint)
<?php namespace Recruiter; use MongoDB; class FactoryTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $this->factory = new Factory(); $this->dbHost = 'localhost:27017'; $this->dbName = 'recruiter'; } public function testShouldCreateAMongoDatabaseConnection() { $this->assertInstanceOf( 'MongoDB', $this->creationOfDefaultMongoDb() ); } public function testWriteConcernIsMajorityByDefault() { $mongoDb = $this->creationOfDefaultMongoDb(); $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']); } public function testShouldOverwriteTheWriteConcernPassedInTheOptions() { $mongoDb = $this->factory->getMongoDb( $host = 'localhost:27017', $options = [ 'connectTimeoutMS' => 1000, 'w' => '0', ], $dbName = 'recruiter' ); $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']); } private function creationOfDefaultMongoDb() { return $this->factory->getMongoDb( $host = $this->dbHost, $options = ['connectTimeoutMS' => 1000], $dbName = $this->dbName ); } }
<?php namespace Recruiter; use MongoDB; class FactoryTest extends \PHPUnit_Framework_TestCase { protected function setUp() { $this->factory = new Factory(); $this->dbHost = 'localhost:27017'; $this->dbName = 'recruiter'; } public function testShouldCreateAMongoDatabaseConnection() { $this->assertInstanceOf( 'MongoDB', $this->creationOfDefaultMongoDb() ); } public function testWriteConcernIsMajorityByDefault() { $mongoDb = $this->creationOfDefaultMongoDb(); $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']); } public function testShouldOverwriteTheWriteConcernPassedInTheOptions() { $mongoDb = $this->factory->getMongoDb( $host = 'localhost:27017', $options = [ 'connectTimeoutMS' => '1000', 'w' => '0', ], $dbName = 'recruiter' ); $this->assertEquals('majority', $mongoDb->getWriteConcern()['w']); } private function creationOfDefaultMongoDb() { return $this->factory->getMongoDb( $host = $this->dbHost, $options = ['connectTimeoutMS' => '1000'], $dbName = $this->dbName ); } }
Update testing harness to support *.ts files.
'use strict'; const fs = require('fs'); const path = require('path'); const runInlineTest = require('jscodeshift/dist/testUtils').runInlineTest; const EmberQUnitTransform = require('../ember-qunit-codemod'); const fixtureFolder = `${__dirname}/../__testfixtures__/ember-qunit-codemod`; describe('ember-qunit-codemod', function() { fs .readdirSync(fixtureFolder) .filter(filename => /\.input\.[jt]s$/.test(filename)) .forEach(filename => { let extension = path.extname(filename); let testName = filename.replace(`.input${extension}`, ''); let inputPath = path.join(fixtureFolder, `${testName}.input${extension}`); let outputPath = path.join(fixtureFolder, `${testName}.output${extension}`); describe(testName, function() { it('transforms correctly', function() { runInlineTest( EmberQUnitTransform, {}, { source: fs.readFileSync(inputPath, 'utf8') }, fs.readFileSync(outputPath, 'utf8') ); }); it('is idempotent', function() { runInlineTest( EmberQUnitTransform, {}, { source: fs.readFileSync(outputPath, 'utf8') }, fs.readFileSync(outputPath, 'utf8') ); }); }); }); });
'use strict'; const fs = require('fs'); const path = require('path'); const runInlineTest = require('jscodeshift/dist/testUtils').runInlineTest; const EmberQUnitTransform = require('../ember-qunit-codemod'); const fixtureFolder = `${__dirname}/../__testfixtures__/ember-qunit-codemod`; describe('ember-qunit-codemod', function() { fs .readdirSync(fixtureFolder) .filter(filename => /\.input\.js$/.test(filename)) .forEach(filename => { let testName = filename.replace('.input.js', ''); let inputPath = path.join(fixtureFolder, `${testName}.input.js`); let outputPath = path.join(fixtureFolder, `${testName}.output.js`); describe(testName, function() { it('transforms correctly', function() { runInlineTest( EmberQUnitTransform, {}, { source: fs.readFileSync(inputPath, 'utf8') }, fs.readFileSync(outputPath, 'utf8') ); }); it('is idempotent', function() { runInlineTest( EmberQUnitTransform, {}, { source: fs.readFileSync(outputPath, 'utf8') }, fs.readFileSync(outputPath, 'utf8') ); }); }); }); });
Fix bug - not node
import Area from './templete' import { getRangeAncestorElem, getRange, isSelectionInArea, createSelectionBaseNode, createRange } from 'utils/selection' const sciprt = ({ options, widget, el, __S_ }) => { $(document).on('selectionchange', () => { const isInArea = isSelectionInArea(el.$area) if (isInArea && el.$area.html() === '') { const $p = $('<p><br /></p>') el.$area.append($p) createRange($p.get(0), 0, $p.get(0), 0) } }) const insertEmptyP = $elem => { const $p = $('<p><br></p>') $p.insertBefore($elem) $elem.remove() createSelectionBaseNode($p.get(0), true) } // 将回车之后生成的非 <p> 的顶级标签,改为 <p> const pHandle = e => { const range = getRange() const elem = getRangeAncestorElem(range) const $elem = $(elem) const $parentElem = $elem.parent() const nodeName = elem.nodeName if (!$parentElem.is(el.$area)) return if (nodeName === 'P') return if ($elem.text()) return insertEmptyP($elem) } el.$area.on('keyup', e => { if (e.keyCode !== 13) return pHandle(e) }) } const area = { Tpl: Area, run: sciprt } export default area
import Area from './templete' import { getRangeAncestorElem, getRange, isSelectionInArea, createSelectionBaseNode, createRange } from 'utils/selection' const sciprt = ({ options, widget, el, __S_ }) => { $(document).on('selectionchange', () => { const isInArea = isSelectionInArea(el.$area) if (isInArea && el.$area.html() === '') { const p = '<p><br /></p>' el.$area.append(p) createRange(p, 0, p, 0) } }) const insertEmptyP = $elem => { const $p = $('<p><br></p>') $p.insertBefore($elem) $elem.remove() createSelectionBaseNode($p.get(0), true) } // 将回车之后生成的非 <p> 的顶级标签,改为 <p> const pHandle = e => { const range = getRange() const elem = getRangeAncestorElem(range) const $elem = $(elem) const $parentElem = $elem.parent() const nodeName = elem.nodeName if (!$parentElem.is(el.$area)) return if (nodeName === 'P') return if ($elem.text()) return insertEmptyP($elem) } el.$area.on('keyup', e => { if (e.keyCode !== 13) return pHandle(e) }) } const area = { Tpl: Area, run: sciprt } export default area
Make pep8 dependency more explicit
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup def version(): """Return version string.""" with open('autopep8.py') as input_file: for line in input_file: if line.startswith('__version__'): import ast return ast.literal_eval(line.split('=')[1].strip()) with open('README.rst') as readme: setup( name='autopep8', version=version(), description='A tool that automatically formats Python code to conform ' 'to the PEP 8 style guide', long_description=readme.read(), license='Expat License', author='Hideo Hattori', author_email='[email protected]', url='https://github.com/hhatto/autopep8', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Unix Shell', ], keywords='automation, pep8, format', install_requires=['pep8 >= 1.3'], test_suite='test.test_autopep8', py_modules=['autopep8'], zip_safe=False, entry_points={'console_scripts': ['autopep8 = autopep8:main']}, )
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup def version(): """Return version string.""" with open('autopep8.py') as input_file: for line in input_file: if line.startswith('__version__'): import ast return ast.literal_eval(line.split('=')[1].strip()) with open('README.rst') as readme: setup( name='autopep8', version=version(), description='A tool that automatically formats Python code to conform ' 'to the PEP 8 style guide', long_description=readme.read(), license='Expat License', author='Hideo Hattori', author_email='[email protected]', url='https://github.com/hhatto/autopep8', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Programming Language :: Unix Shell', ], keywords='automation, pep8, format', install_requires=['pep8'], test_suite='test.test_autopep8', py_modules=['autopep8'], zip_safe=False, entry_points={'console_scripts': ['autopep8 = autopep8:main']}, )
Fix bug associated with bad ABC implementation.
from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @property def deps_build_info(self): return self._deps_build_info @property def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @abstractproperty def deps_build_info(self): return self._deps_build_info @abstractproperty def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
Fix MySQL / PostgreSQL json column compatibility
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTagsTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create(config('rinvex.tags.tables.tags'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('slug'); $table->{$this->jsonable()}('name'); $table->{$this->jsonable()}('description')->nullable(); $table->mediumInteger('sort_order')->unsigned()->default(0); $table->string('group')->nullable(); $table->timestamps(); $table->softDeletes(); // Indexes $table->unique('slug'); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists(config('rinvex.tags.tables.tags')); } /** * Get jsonable column data type. * * @return string */ protected function jsonable(): string { $driverName = DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME); $dbVersion = DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); $isOldVersion = version_compare($dbVersion, '5.7.8', 'lt'); return $driverName === 'mysql' && $isOldVersion ? 'text' : 'json'; } }
<?php declare(strict_types=1); use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTagsTable extends Migration { /** * Run the migrations. * * @return void */ public function up(): void { Schema::create(config('rinvex.tags.tables.tags'), function (Blueprint $table) { // Columns $table->increments('id'); $table->string('slug'); $table->{$this->jsonable()}('name'); $table->{$this->jsonable()}('description')->nullable(); $table->mediumInteger('sort_order')->unsigned()->default(0); $table->string('group')->nullable(); $table->timestamps(); $table->softDeletes(); // Indexes $table->unique('slug'); }); } /** * Reverse the migrations. * * @return void */ public function down(): void { Schema::dropIfExists(config('rinvex.tags.tables.tags')); } /** * Get jsonable column data type. * * @return string */ protected function jsonable(): string { return DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) === 'mysql' && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge') ? 'json' : 'text'; } }
Remove one last vestage of compressed data chunks We used to allow data chunks to be up to twice the size of the block size to allow for incompressible chunks. Since compression is gone, so can that be.
package com.socrata.ssync; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.*; public class PatchBuilder { private final OutputStreamWriteHelper out; private final int blockSize; // Does NOT take ownership of the outputstream! public PatchBuilder(OutputStream outStream, String checksumAlgorithm, int blockSize) throws IOException, NoSuchAlgorithmException { this.out = new OutputStreamWriteHelper(outStream, MessageDigest.getInstance(checksumAlgorithm)); if(blockSize <= 0 || blockSize >= Patch.MaxBlockSize) throw new IllegalArgumentException("blockSize"); this.blockSize = blockSize; out.writeCheckumNameWithoutUpdatingChecksum(); out.writeInt(blockSize); } public void writeEnd() throws IOException { writeOp(Patch.End); out.writeChecksumWithoutUpdatingChecksum(); } public void writeBlockNum(int blockNum) throws IOException { writeOp(Patch.Block); out.writeInt(blockNum); } public void writeData(byte[] data) throws IOException { writeData(data, 0, data.length); } public void writeData(byte[] data, int offset, int length) throws IOException { while(length != 0) { writeOp(Patch.Data); int toWrite = Math.min(length, blockSize); out.writeInt(toWrite); out.writeBytes(data, offset, toWrite); length -= toWrite; offset += toWrite; } } private void writeOp(int op) throws IOException { out.writeByte(op); } }
package com.socrata.ssync; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.*; public class PatchBuilder { private final OutputStreamWriteHelper out; private final int maxDataBlockSize; // Does NOT take ownership of the outputstream! public PatchBuilder(OutputStream outStream, String checksumAlgorithm, int blockSize) throws IOException, NoSuchAlgorithmException { this.out = new OutputStreamWriteHelper(outStream, MessageDigest.getInstance(checksumAlgorithm)); if(blockSize <= 0 || blockSize >= Patch.MaxBlockSize) throw new IllegalArgumentException("blockSize"); this.maxDataBlockSize = blockSize * 2; out.writeCheckumNameWithoutUpdatingChecksum(); out.writeInt(blockSize); } public void writeEnd() throws IOException { writeOp(Patch.End); out.writeChecksumWithoutUpdatingChecksum(); } public void writeBlockNum(int blockNum) throws IOException { writeOp(Patch.Block); out.writeInt(blockNum); } public void writeData(byte[] data) throws IOException { writeData(data, 0, data.length); } public void writeData(byte[] data, int offset, int length) throws IOException { while(length != 0) { writeOp(Patch.Data); int toWrite = Math.min(length, maxDataBlockSize); out.writeInt(toWrite); out.writeBytes(data, offset, toWrite); length -= toWrite; offset += toWrite; } } private void writeOp(int op) throws IOException { out.writeByte(op); } }
Fix for truncated text 'see more' click triggering text click events.
(function () { 'use strict'; angular .module('GVA.Common') .directive('truncatedText', truncatedText); truncatedText.$inject = ['$parse']; function truncatedText() { function truncateText(text, limit) { var words = text.split(' '); var truncatedtext = words.reduce(function (prev, curr) { if (curr.length + prev.length >= limit) { return prev; } else { return prev + ' ' + curr; } }); return truncatedtext; } function link(scope) { activate(); function activate() { scope.maxChars = parseInt(scope.maxChars) || 160; scope.fullText = ''; scope.truncatedText = ''; scope.$watch('ngModel', function () { scope.fullText = scope.ngModel; if (scope.fullText) { scope.truncatedText = truncateText(scope.fullText, scope.maxChars); scope.truncated = scope.fullText !== scope.truncatedText; } else { scope.truncated = false; } }); } } return { restrict: 'A', scope: { ngModel: '=', maxChars: '@', }, link: link, template: '<span ng-if="!truncated">{{fullText}}</span>' + '<span ng-if="truncated">{{truncatedText}}</span>' + '<span ng-show="truncated">... <a style="cursor:pointer" ng-click="truncated=false;$event.stopPropagation();">Show More</a></span>' }; } })();
(function () { 'use strict'; angular .module('GVA.Common') .directive('truncatedText', truncatedText); truncatedText.$inject = ['$parse']; function truncatedText() { function truncateText(text, limit) { var words = text.split(' '); var truncatedtext = words.reduce(function (prev, curr) { if (curr.length + prev.length >= limit) { return prev; } else { return prev + ' ' + curr; } }); return truncatedtext; } function link(scope) { activate(); function activate() { scope.maxChars = parseInt(scope.maxChars) || 160; scope.fullText = ''; scope.truncatedText = ''; scope.$watch('ngModel', function () { scope.fullText = scope.ngModel; if (scope.fullText) { scope.truncatedText = truncateText(scope.fullText, scope.maxChars); scope.truncated = scope.fullText !== scope.truncatedText; } else { scope.truncated = false; } }); } } return { restrict: 'A', scope: { ngModel: '=', maxChars: '@', }, link: link, template: '<span ng-if="!truncated">{{fullText}}</span>' + '<span ng-if="truncated">{{truncatedText}}</span>' + '<span ng-show="truncated">... <a style="cursor:pointer" ng-click="truncated=false">Show More</a></span>' }; } })();
Make test names lower case prefix
import unittest import src import sys from io import StringIO class TestConfigFileLoading(unittest.TestCase): filepath_prefix = '' @classmethod def setUpClass(cls): if sys.argv[0].endswith('nosetests'): cls.filepath_prefix = "./resources/config/" else: cls.filepath_prefix = "../resources/config/" def testReadJsonCorrectly(self): config_file = self.filepath_prefix + "default-config.json" exp_res = 17 config_json = src.read_json(config_file) result = len(config_json) self.assertEqual(result, exp_res) def testReadJsonBadFileName(self): config_file = self.filepath_prefix + "fig.json" with self.assertRaises(FileNotFoundError): src.read_json(config_file) def testLoadConfigFileCheckRead(self): exp_res = "Read styling config JSON correctly." out = StringIO() src.load_config_file(out=out) result = out.getvalue().strip() self.assertEqual(result, exp_res) def testDefaultConfigOverwritten(self): exp_res = 666 config = src.load_config_file() result = config["max_line_length"] self.assertEqual(result, exp_res) def testDefaultConfigPersists(self): exp_res = True config = src.load_config_file() result = config["spellcheck"] self.assertEqual(result, exp_res)
import unittest import src import sys from io import StringIO class TestConfigFileLoading(unittest.TestCase): filepath_prefix = '' @classmethod def setUpClass(cls): if sys.argv[0].endswith('nosetests'): cls.filepath_prefix = "./resources/config/" else: cls.filepath_prefix = "../resources/config/" def TestReadJsonCorrectly(self): config_file = self.filepath_prefix + "default-config.json" exp_res = 17 config_json = src.read_json(config_file) result = len(config_json) self.assertEqual(result, exp_res) def TestReadJsonBadFileName(self): config_file = self.filepath_prefix + "fig.json" with self.assertRaises(FileNotFoundError): src.read_json(config_file) def TestLoadConfigFileCheckRead(self): exp_res = "Read styling config JSON correctly." out = StringIO() src.load_config_file(out=out) result = out.getvalue().strip() self.assertEqual(result, exp_res) def TestDefaultConfigOverwritten(self): exp_res = 666 config = src.load_config_file() result = config["max_line_length"] self.assertEqual(result, exp_res) def TestDefaultConfigPersists(self): exp_res = True config = src.load_config_file() result = config["spellcheck"] self.assertEqual(result, exp_res)
Set sass output style to compressed
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'), sass = require('gulp-sass'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); gulp.watch('./spec/**/*.js', ['test']); gulp.watch('./src/scss/**/*.scss', ['css']); }); gulp.task('build', ['javascript', 'css']); gulp.task('css', function () { gulp.src('./src/scss/bowler.scss') .pipe(sourcemaps.init()) .pipe(sass({ outputStyle: 'compressed' })) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/css')); }); gulp.task('javascript', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['javascript'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
'use strict'; var gulp = require('gulp'), browserify = require('browserify'), transform = require('vinyl-transform'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), jasmine = require('gulp-jasmine'), sass = require('gulp-sass'); gulp.task('default', ['build', 'watch']); gulp.task('watch', function () { gulp.watch('./src/js/**/*.js', ['test']); gulp.watch('./spec/**/*.js', ['test']); gulp.watch('./src/scss/**/*.scss', ['css']); }); gulp.task('build', ['javascript', 'css']); gulp.task('css', function () { gulp.src('./src/css/bowler.scss') .pipe(sourcemaps.init()) .pipe(sass()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/css')); }); gulp.task('javascript', function () { var browserified = transform(function (filename) { var b = browserify({ entries: filename, debug: true }); return b.bundle(); }); return gulp.src('./src/js/bowler.js') .pipe(browserified) .pipe(sourcemaps.init({ loadMaps: true })) .pipe(uglify()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('./dist/js')); }); gulp.task('test', ['javascript'], function () { return gulp.src('./spec/**/*.js') .pipe(jasmine()); });
[read] Deal with the read action.
import { ADD_NOTIFICATION, ADD_NOTIFICATIONS, READ_NOTIFICATION} from '../actions'; import {RECEIVE_NOTIFICATIONS} from '../actions/fetch-notifications'; import generateError from './util/error-generator'; import {isObject, isArray} from 'lodash/lang'; const REDUCER_NAME = 'NOTIFICATION_LIST'; // reducers in charge of generatin the notification list export default function notifications(state = [], action = {}) { const {type, index, payload} = action; switch (type) { case ADD_NOTIFICATION: if(!isObject(payload)) { throw new Error (generateError({name: REDUCER_NAME, action, expectedType: 'object'})); } return [...state, { ...payload, read: false }]; case ADD_NOTIFICATIONS: case RECEIVE_NOTIFICATIONS: if(!isArray(payload)) { throw new Error(generateError({name: REDUCER_NAME, action, expectedType: 'array'})); } const data = action.payload.map((notif) => ({...notif, read: false})); return [...state, ...data]; case READ_NOTIFICATION: const index = state.findIndex( (notif) => notif.uuid === action.payload); return [ ...state.slice(0, index), ...state.slice(index + 1) ]; default: return state; } }
import { ADD_NOTIFICATION, ADD_NOTIFICATIONS, READ_NOTIFICATION} from '../actions'; import {RECEIVE_NOTIFICATIONS} from '../actions/fetch-notifications'; import generateError from './util/error-generator'; import {isObject, isArray} from 'lodash/lang'; const REDUCER_NAME = 'NOTIFICATION_LIST'; // reducers in charge of generatin the notification list export default function notifications(state = [], action = {}) { const {type, index, payload} = action; switch (type) { case ADD_NOTIFICATION: if(!isObject(payload)) { throw new Error (generateError({name: REDUCER_NAME, action, expectedType: 'object'})); } return [...state, { ...payload, read: false }]; case ADD_NOTIFICATIONS: case RECEIVE_NOTIFICATIONS: if(!isArray(payload)) { throw new Error(generateError({name: REDUCER_NAME, action, expectedType: 'array'})); } const data = action.payload.map((notif) => ({...notif, read: false})); return [...state, ...data]; case READ_NOTIFICATION: return [ ...state.slice(0, action.index), Object.assign({}, state[action.index], { read: true }), ...state.slice(action.index + 1) ]; default: return state; } }
Change the pkg url to its github repo
from distutils.core import setup setup( name='django-databrowse', version='1.3', packages=['django_databrowse', 'django_databrowse.plugins'], package_dir={'django_databrowse': 'django_databrowse'}, package_data={ 'django_databrowse': [ 'templates/databrowse/*.html', 'templates/databrowse/include/*.html' ] }, provides=['django_databrowse'], include_package_data=True, url='https://github.com/Alir3z4/django-databrowse', license=open('LICENSE').read(), author='Alireza Savand', author_email='[email protected]', description='Databrowse is a Django application that lets you browse your data.', long_description=open('README.rst').read(), install_requires=['django', ], keywords=[ 'django', 'web', 'databrowse', 'data' ], platforms='OS Independent', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Framework :: Django', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development' ], )
from distutils.core import setup setup( name='django-databrowse', version='1.3', packages=['django_databrowse', 'django_databrowse.plugins'], package_dir={'django_databrowse': 'django_databrowse'}, package_data={ 'django_databrowse': [ 'templates/databrowse/*.html', 'templates/databrowse/include/*.html' ] }, provides=['django_databrowse'], include_package_data=True, url='http://pypi.python.org/pypi/django-databrowse', license=open('LICENSE').read(), author='Alireza Savand', author_email='[email protected]', description='Databrowse is a Django application that lets you browse your data.', long_description=open('README.rst').read(), install_requires=['django', ], keywords=[ 'django', 'web', 'databrowse', 'data' ], platforms='OS Independent', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Framework :: Django', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development' ], )
Add Extension .pot for powerpoint
package org.dstadler.commoncrawl; /** * Which extensions we are interested in. * * @author dominik.stadler */ public class Extensions { private static final String[] EXTENSIONS = new String[] { // Excel ".xls", ".xlsx", ".xlsm", ".xltx", ".xlsb", // Word ".doc", ".docx", ".dotx", ".docm", ".ooxml", // Powerpoint ".ppt", ".pot", ".pptx", ".pptm", ".ppsm", ".ppsx", ".thmx", ".potx", // Outlook ".msg", // Publisher ".pub", // Visio - binary ".vsd", ".vss", ".vst", ".vsw", // Visio - ooxml (currently unsupported) ".vsdm", ".vsdx", ".vssm", ".vssx", ".vstm", ".vstx", // POIFS ".ole2", // Microsoft Admin Template? ".adm", // Microsoft TNEF // ".dat", new HMEFFileHandler()); }; public static boolean matches(String url) { for(String ext : EXTENSIONS) { if(url.endsWith(ext)) { return true; } } return false; } }
package org.dstadler.commoncrawl; /** * Which extensions we are interested in. * * @author dominik.stadler */ public class Extensions { private static final String[] EXTENSIONS = new String[] { // Excel ".xls", ".xlsx", ".xlsm", ".xltx", ".xlsb", // Word ".doc", ".docx", ".dotx", ".docm", ".ooxml", // Powerpoint ".ppt", ".pptx", ".pptm", ".ppsm", ".ppsx", ".thmx", // Outlook ".msg", // Publisher ".pub", // Visio - binary ".vsd", ".vss", ".vst", ".vsw", // Visio - ooxml (currently unsupported) ".vsdm", ".vsdx", ".vssm", ".vssx", ".vstm", ".vstx", // POIFS ".ole2", // Microsoft Admin Template? ".adm", // Microsoft TNEF // ".dat", new HMEFFileHandler()); }; public static boolean matches(String url) { for(String ext : EXTENSIONS) { if(url.endsWith(ext)) { return true; } } return false; } }
Use base color when hovering a connector
import React from 'react'; import { Group } from 'react-art'; import Connector from './Connector.js'; import DrawingUtils from '../utils/DrawingUtils.js'; import { getDisplayName } from './Utils.js'; const { PropTypes } = DrawingUtils; export default CircuitComponent => { class Connectors extends React.Component { render() { const { hovered, hoveredConnectorIndex, connectors, theme } = this.props; let connectorViews = null; if (hovered) { connectorViews = connectors.map((connector, i) => { const color = i === hoveredConnectorIndex ? theme.COLORS.base : theme.COLORS.transBase; return ( <Connector position={connector} color={color} key={i} /> ); }); } return ( <Group> {connectorViews} </Group> ); } } Connectors.propTypes = { connectors: React.PropTypes.arrayOf(PropTypes.Vector).isRequired, theme: React.PropTypes.object.isRequired, hovered: React.PropTypes.bool, hoveredConnectorIndex: React.PropTypes.number // index of connector being hovered }; Connectors.defaultProps = { hovered: false }; Connectors.displayName = `ConnectorsFor(${getDisplayName(CircuitComponent)})`; return Connectors; };
import React from 'react'; import { Group } from 'react-art'; import Connector from './Connector.js'; import DrawingUtils from '../utils/DrawingUtils.js'; import { getDisplayName } from './Utils.js'; const { PropTypes } = DrawingUtils; export default CircuitComponent => { class Connectors extends React.Component { render() { const { hovered, hoveredConnectorIndex, connectors, theme } = this.props; let connectorViews = null; if (hovered) { connectorViews = connectors.map((connector, i) => { const color = i === hoveredConnectorIndex ? theme.COLORS.highlight : theme.COLORS.transBase; return ( <Connector position={connector} color={color} key={i} /> ); }); } return ( <Group> {connectorViews} </Group> ); } } Connectors.propTypes = { connectors: React.PropTypes.arrayOf(PropTypes.Vector).isRequired, theme: React.PropTypes.object.isRequired, hovered: React.PropTypes.bool, hoveredConnectorIndex: React.PropTypes.number // index of connector being hovered }; Connectors.defaultProps = { hovered: false }; Connectors.displayName = `ConnectorsFor(${getDisplayName(CircuitComponent)})`; return Connectors; };
Fix partners not correctly handled.
<?php namespace Korko\SecretSanta\Http\Controllers; use Korko\SecretSanta\Http\Requests\RandomFormRequest; use Korko\SecretSanta\Libs\Randomizer; use Illuminate\Http\Request; use Mail; class RandomFormController extends Controller { public function view() { return view('randomForm'); } public function handle(RandomFormRequest $request) { $names = $request->input('name'); $emails = $request->input('email'); $partners = $request->input('partner', []); $participants = []; for ($i = 0; $i < count($names); $i++) { $participants[$i] = array( 'name' => $names[$i], 'email' => $emails[$i], 'partner' => !empty($partners[$i]) ? $names[$partners[$i]] : null ); } $hat = Randomizer::randomize($participants); foreach ($hat as $santaIdx => $targetName) { $santa = $participants[$santaIdx]; $content = str_replace(['{SANTA}', '{TARGET}'], [$santa['name'], $targetName], $request->input('content')); Mail::raw($content, function ($m) use ($santa, $request) { $m->to($santa['email'], $santa['name'])->subject($request->input('title')); }); } $message = 'Envoyé avec succès !'; return $request->ajax() ? [$message] : redirect('/')->with('message', $message); } }
<?php namespace Korko\SecretSanta\Http\Controllers; use Korko\SecretSanta\Http\Requests\RandomFormRequest; use Korko\SecretSanta\Libs\Randomizer; use Illuminate\Http\Request; use Mail; class RandomFormController extends Controller { public function view() { return view('randomForm'); } public function handle(RandomFormRequest $request) { $participants = []; for ($i = 0; $i < count($request->input('name')); $i++) { $participants[$i] = array( 'name' => $request->input('name')[$i], 'email' => $request->input('email')[$i], 'partner' => array_get($request->input('partner', []), $i) ); } $hat = Randomizer::randomize($participants); foreach ($hat as $santaIdx => $targetName) { $santa = $participants[$santaIdx]; $content = str_replace(['{SANTA}', '{TARGET}'], [$santa['name'], $targetName], $request->input('content')); Mail::raw($content, function ($m) use ($santa, $request) { $m->to($santa['email'], $santa['name'])->subject($request->input('title')); }); } $message = 'Envoyé avec succès !'; return $request->ajax() ? [$message] : redirect('/')->with('message', $message); } }
Enforce working version of svgpathtools
# -*- coding: utf-8 -*- import setuptools import versioneer with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="PcbDraw", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author="Jan Mrázek", author_email="[email protected]", description="Utility to produce nice looking drawings of KiCAD boards", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/yaqwsx/PcbDraw", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ "numpy", "lxml", "mistune", "pybars3", "wand", "pyyaml", "svgpathtools==1.4.1", "pcbnewTransition>=0.2" ], setup_requires=[ "versioneer" ], zip_safe=False, include_package_data=True, entry_points = { "console_scripts": [ "pcbdraw=pcbdraw.pcbdraw:main", "populate=pcbdraw.populate:main" ], } )
# -*- coding: utf-8 -*- import setuptools import versioneer with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="PcbDraw", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author="Jan Mrázek", author_email="[email protected]", description="Utility to produce nice looking drawings of KiCAD boards", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/yaqwsx/PcbDraw", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ "numpy", "lxml", "mistune", "pybars3", "wand", "pyyaml", "svgpathtools", "pcbnewTransition>=0.2" ], setup_requires=[ "versioneer" ], zip_safe=False, include_package_data=True, entry_points = { "console_scripts": [ "pcbdraw=pcbdraw.pcbdraw:main", "populate=pcbdraw.populate:main" ], } )
Add gzip to cx-freeze packages
import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "gzip", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")
import importlib from cx_Freeze import setup, Executable backend_path = importlib.import_module("bcrypt").__path__[0] backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend") # Dependencies are automatically detected, but it might need # fine tuning. build_exe_options = { "include_files": [ ("client/dist", "client"), "LICENSE", "templates", "readme.md", (backend_path, "lib/.libs_cffi_backend") ], "includes": [ "cffi", "numpy", "numpy.core._methods", "numpy.lib", "numpy.lib.format", "raven.processors" ], "packages": [ "_cffi_backend", "appdirs", "asyncio", "bcrypt", "cffi", "idna", "motor", "packaging", "ssl", "uvloop" ] } options = { "build_exe": build_exe_options } executables = [ Executable('run.py', base="Console") ] classifiers=[ "Programming Language :: Python :: 3.7" ] importlib.import_module("virtool") setup(name='virtool', executables=executables, options=options, classifiers=classifiers, python_requires=">=3.6")