text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Exclude node modules from webpack using dir name
var webpack = require('webpack') var path = require('path'); module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'test/**/*.js' ], preprocessors: { // add webpack as preprocessor 'src/**/*.js': ['webpack', 'sourcemap'], 'test/**/*.js': ['webpack', 'sourcemap'] }, webpack: { //kind of a copy of your webpack config devtool: 'inline-source-map', //just do inline source maps instead of the default module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: path.resolve(__dirname, 'node_modules'), query: { presets: ['airbnb'] } }, { test: /\.json$/, loader: 'json', }, ] }, externals: { 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true } }, webpackServer: { noInfo: true //please don't spam the console when running in karma! }, plugins: [ 'karma-webpack', 'karma-jasmine', 'karma-sourcemap-loader', 'karma-chrome-launcher', 'karma-phantomjs-launcher' ], babelPreprocessor: { options: { presets: ['airbnb'] } }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, }) };
var webpack = require('webpack') module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'test/**/*.js' ], preprocessors: { // add webpack as preprocessor 'src/**/*.js': ['webpack', 'sourcemap'], 'test/**/*.js': ['webpack', 'sourcemap'] }, webpack: { //kind of a copy of your webpack config devtool: 'inline-source-map', //just do inline source maps instead of the default module: { loaders: [ { test: /\.js$/, loader: 'babel', query: { presets: ['airbnb'] } }, { test: /\.json$/, loader: 'json', }, ] }, externals: { 'react/lib/ExecutionEnvironment': true, 'react/lib/ReactContext': true } }, webpackServer: { noInfo: true //please don't spam the console when running in karma! }, plugins: [ 'karma-webpack', 'karma-jasmine', 'karma-sourcemap-loader', 'karma-chrome-launcher', 'karma-phantomjs-launcher' ], babelPreprocessor: { options: { presets: ['airbnb'] } }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, }) };
Read More module: changes to filter logic Absence of a post indicates we are previewing content.
<?php class ReadMore extends Modules { public function __init() { # Replace comment codes before markup modules filters them. $this->setPriority("markup_post_text", 4); } public function markup_post_text($text, $post = null) { if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches)) return $text; $route = Route::current(); $controller = $route->controller; if (!isset($post) or $route->action == "view" or ($controller instanceof MainController and $controller->feed)) return preg_replace("/<!-- *more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (!$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
<?php class ReadMore extends Modules { public function __init() { # Replace comment codes before markup modules filters them. $this->setPriority("markup_post_text", 4); } public function markup_post_text($text, $post = null) { if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches)) return $text; $route = Route::current(); $controller = $route->controller; if ($route->action == "view" or ($controller instanceof MainController and $controller->feed)) return preg_replace("/<!-- *more(.+?)?-->/i", "", $text); $more = oneof(trim(fallback($matches[1])), __("&hellip;more", "read_more")); $url = (isset($post) and !$post->no_results) ? $post->url() : "#" ; $split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY); return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>'; } public function title_from_excerpt($text) { $split = preg_split('/<a class="read_more"/', $text); return $split[0]; } }
Delete data check in __construct()
<?php namespace ApiAi\Model; /** * Class Base * * @package ApiAi\Model */ class Base implements \JsonSerializable { /** * @var array */ private $data; /** * Base constructor. * * @param array $data */ public function __construct($data = []) { $this->data = $data; } /** * @return array */ public function jsonSerialize() { return $this->data; } /** * @param string $name * * @return bool */ public function has($name) { return isset($this->data[$name]); } /** * @param string $name * @param mixed $default * * @return mixed */ public function get($name, $default = null) { return $this->getField($name, $default); } /** * @param string $name * @param mixed $value */ public function add($name, $value) { $this->data[$name] = $value; } /** * @param string $name */ public function remove($name) { unset($this->data[$name]); } /** * @param string $name * @param mixed $default * * @return mixed */ private function getField($name, $default = null) { return $this->has($name) ? $this->data[$name] : $default; } }
<?php namespace ApiAi\Model; /** * Class Base * * @package ApiAi\Model */ class Base implements \JsonSerializable { /** * @var array */ private $data; /** * Base constructor. * * @param array $data */ public function __construct($data = []) { if (empty($data)) { throw new \InvalidArgumentException('__construct() $data must be defined'); } $this->data = $data; } /** * @return array */ public function jsonSerialize() { return $this->data; } /** * @param string $name * * @return bool */ public function has($name) { return isset($this->data[$name]); } /** * @param string $name * @param mixed $default * * @return mixed */ public function get($name, $default = null) { return $this->getField($name, $default); } /** * @param string $name * @param mixed $value */ public function add($name, $value) { $this->data[$name] = $value; } /** * @param string $name */ public function remove($name) { unset($this->data[$name]); } /** * @param string $name * @param mixed $default * * @return mixed */ private function getField($name, $default = null) { return $this->has($name) ? $this->data[$name] : $default; } }
Fix cityInfo tab not loading data after user completes form
'use strict'; const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const request = require('request'); const models = require('../../db/models'); module.exports.getAll = (req, res) => { models.User.where({ email: req.user.email}).fetch() .then((result) => { models.Stats.where({city: result.attributes.destination}).fetchAll() .then(data => { if (data.length === 0) { request .get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`, (error, response, stats) => { if (error) { console.error(err); } models.Stats.forge({ city: result.attributes.destination, city_stats: stats }) .save() .then(data => { res.status(201).send(data.attributes.city_stats); }) .catch(err => { res.status(500).send(err); }); }) .on('error', (err) => { console.log(err); res.status(500).send(err); }); } else { res.status(200).send(data.attributes.city_stats); } }) .catch(err => { res.status(503).send(err); }); }) .catch(err => { res.status(503).send(err); }); };
'use strict'; const express = require('express'); const router = express.Router(); const bodyParser = require('body-parser'); const request = require('request'); const models = require('../../db/models'); module.exports.getAll = (req, res) => { models.User.where({ email: req.user.email}).fetch() .then((result) => { models.Stats.where({city: result.attributes.destination}).fetchAll() .then(data => { if (data.length === 0) { request .get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`, (error, response, stats) => { if (error) { console.error(err); } models.Stats.forge({ city: result.attributes.destination, city_stats: stats }) .save() .then(data => { res.status(201).send(data.attributes.city_stats); }) .catch(err => { res.status(500).send(err); }); }) .on('error', (err) => { console.log(err); res.status(500).send(err); }); } else { res.status(200).send(data.models[0].attributes.city_stats); } }) .catch(err => { res.status(503).send(err); }); }) .catch(err => { res.status(503).send(err); }); };
Change fov scaling to "Hor+".
#!/usr/bin/env python2 import math import sys from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d import ecs from player import PlayerController class NodePathComponent(ecs.Component): __slots__ = [ "nodepath", ] def __init__(self, modelpath=None): if modelpath is not None: self.nodepath = base.loader.loadModel(modelpath) else: self.nodepath = p3d.NodePath(p3d.PandaNode('node')) class Sigurd(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() self.ecsmanager = ecs.ECSManager() def run_ecs(task): self.ecsmanager.update(0) task.cont self.taskMgr.add(run_ecs, 'ECS') level = ecs.Entity() np_component = NodePathComponent('models/level') np_component.nodepath.reparent_to(base.render) self.ecsmanager.add_entity(level) PlayerController(self.camera) self.accept('escape-up', sys.exit) self.accept('aspectRatioChanged', self.cb_resize) def cb_resize(self): vfov = 70 aspect = self.camLens.get_aspect_ratio() hfov = math.degrees(2 * math.atan(math.tan(math.radians(vfov)/2.0) * aspect)) print(hfov) self.camLens.setFov(hfov, vfov) if __name__ == '__main__': app = Sigurd() app.run()
#!/usr/bin/env python2 import sys from direct.showbase.ShowBase import ShowBase import panda3d.core as p3d import ecs from player import PlayerController class NodePathComponent(ecs.Component): __slots__ = [ "nodepath", ] def __init__(self, modelpath=None): if modelpath is not None: self.nodepath = base.loader.loadModel(modelpath) else: self.nodepath = p3d.NodePath(p3d.PandaNode('node')) class Sigurd(ShowBase): def __init__(self): ShowBase.__init__(self) self.disableMouse() self.ecsmanager = ecs.ECSManager() def run_ecs(task): self.ecsmanager.update(0) task.cont self.taskMgr.add(run_ecs, 'ECS') level = ecs.Entity() np_component = NodePathComponent('models/level') np_component.nodepath.reparent_to(base.render) self.ecsmanager.add_entity(level) PlayerController(self.camera) self.camLens.setFov(90) self.accept('escape-up', sys.exit) if __name__ == '__main__': app = Sigurd() app.run()
Update error handler test for php52
<?php class ClientTest extends PHPUnit_Framework_TestCase { protected $client; protected function setUp(){ // Mock the notify function $this->client = $this->getMockBuilder('Bugsnag_Client') ->setMethods(array('notify')) ->setConstructorArgs(array('6015a72ff14038114c3d12623dfb018f')) ->getMock(); // Activate the Bugsnag handlers set_error_handler(array($this->client, "errorHandler")); set_exception_handler(array($this->client, "exceptionHandler")); } protected function tearDown() { // Remove the Bugsnag handlers restore_error_handler(); restore_exception_handler(); } public function testErrorHandler() { $this->client->expects($this->once()) ->method('notify'); $this->client->errorHandler(E_NOTICE, "Something broke", "somefile.php", 123); } public function testExceptionHandler() { $this->client->expects($this->once()) ->method('notify'); $this->client->exceptionHandler(new Exception("Something broke")); } public function testManualErrorNotification() { $this->client->expects($this->once()) ->method('notify'); $this->client->notifyError("SomeError", "Some message"); } public function testManualExceptionNotification() { $this->client->expects($this->once()) ->method('notify'); $this->client->notifyException(new Exception("Something broke")); } } ?>
<?php class ClientTest extends PHPUnit_Framework_TestCase { protected $client; protected function setUp(){ // Mock the notify function $this->client = $this->getMockBuilder('Bugsnag_Client') ->setMethods(array('notify')) ->setConstructorArgs(array('6015a72ff14038114c3d12623dfb018f')) ->getMock(); // Activate the Bugsnag handlers set_error_handler(array($this->client, "errorHandler")); set_exception_handler(array($this->client, "exceptionHandler")); } protected function tearDown() { // Remove the Bugsnag handlers restore_error_handler(); restore_exception_handler(); } public function testErrorHandler() { $this->client->expects($this->once()) ->method('notify'); // Triggers a E_NOTICE, which should be handled by our errorHandler $foo = $bar; } public function testExceptionHandler() { $this->client->expects($this->once()) ->method('notify'); $this->client->exceptionHandler(new Exception("Something broke")); } public function testManualErrorNotification() { $this->client->expects($this->once()) ->method('notify'); $this->client->notifyError("SomeError", "Some message"); } public function testManualExceptionNotification() { $this->client->expects($this->once()) ->method('notify'); $this->client->notifyException(new Exception("Something broke")); } } ?>
Update GLPI to 0.91 in unit tests
<?php require_once('commonfunction.php'); include_once (GLPI_ROOT . "/config/based_config.php"); include_once (GLPI_ROOT . "/inc/dbmysql.class.php"); include_once (GLPI_CONFIG_DIR . "/config_db.php"); class GLPIInstallTest extends PHPUnit_Framework_TestCase { /** * @test */ public function installDatabase() { $DBvars = get_class_vars('DB'); drop_database( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'] ); $result = load_mysql_file( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'], GLPI_ROOT ."/install/mysql/glpi-0.91-empty.sql" ); $output = array(); $returncode = 0; exec( "php -f ".GLPI_ROOT. "/tools/cliupdate.php -- --upgrade", $output, $returncode ); $this->assertEquals(0,$returncode, "Error when update GLPI in CLI mode\n". implode("\n",$output) ); $this->assertEquals( 0, $result['returncode'], "Failed to install GLPI database:\n". implode("\n", $result['output']) ); } }
<?php require_once('commonfunction.php'); include_once (GLPI_ROOT . "/config/based_config.php"); include_once (GLPI_ROOT . "/inc/dbmysql.class.php"); include_once (GLPI_CONFIG_DIR . "/config_db.php"); class GLPIInstallTest extends PHPUnit_Framework_TestCase { /** * @test */ public function installDatabase() { $DBvars = get_class_vars('DB'); drop_database( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'] ); $result = load_mysql_file( $DBvars['dbuser'], $DBvars['dbhost'], $DBvars['dbdefault'], $DBvars['dbpassword'], GLPI_ROOT ."/install/mysql/glpi-0.90-empty.sql" ); $output = array(); $returncode = 0; exec( "php -f ".GLPI_ROOT. "/tools/cliupdate.php -- --upgrade", $output, $returncode ); $this->assertEquals(0,$returncode, "Error when update GLPI in CLI mode\n". implode("\n",$output) ); $this->assertEquals( 0, $result['returncode'], "Failed to install GLPI database:\n". implode("\n", $result['output']) ); } }
Fix broken code, comment out sun.awt.X11.XLayerProtocol
package dr.inference.model; import dr.xml.*; //import sun.awt.X11.XLayerProtocol; /** * @author Joseph Heled * Date: 4/09/2009 */ public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser { public static String VALUES_POOL = "valuesPool"; public static String VALUES = "values"; public static String SELECTOR = "selector"; public Object parseXMLObject(XMLObject xo) throws XMLParseException { final Variable pool = (Variable)xo.getElementFirstChild(VALUES); final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR); if( pool.getSize() != selector.getSize() ) { throw new XMLParseException("variable Pool and selector must have equal length."); } return new ValuesPool(pool, selector); } public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[] { new ElementRule(VALUES, new XMLSyntaxRule[]{ new ElementRule(Variable.class,1,1) }), new ElementRule(SELECTOR, new XMLSyntaxRule[]{ new ElementRule(Variable.class,1,1) }) }; } public String getParserDescription() { return ""; } public Class getReturnType() { return ValuesPool.class; } public String getParserName() { return VALUES_POOL; } }
package dr.inference.model; import dr.xml.*; import sun.awt.X11.XLayerProtocol; /** * @author Joseph Heled * Date: 4/09/2009 */ public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser { public static String VALUES_POOL = "valuesPool"; public static String VALUES = "values"; public static String SELECTOR = "selector"; public Object parseXMLObject(XMLObject xo) throws XMLParseException { final Variable pool = (Variable)xo.getElementFirstChild(VALUES); final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR); if( pool.getSize() != selector.getSize() ) { throw new XMLParseException("variable Pool and selector must have equal length."); } return new ValuesPool(pool, selector); } public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[] { new ElementRule(VALUES, new XMLSyntaxRule[]{ new ElementRule(Variable.class,1,1) }), new ElementRule(SELECTOR, new XMLSyntaxRule[]{ new ElementRule(Variable.class,1,1) }) }; } public String getParserDescription() { return ""; } public Class getReturnType() { return ValuesPool.class; } public String getParserName() { return VALUES_POOL; } }
Correct header params on adapter
# coding: utf-8 from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) params.setdefault('headers', {}).update({ 'Authorization': 'Bearer %s' % api_params.get('token', ''), 'Harvest-Account-Id': api_params.get('account_id', ''), 'User-Agent': api_params.get('user_agent', '') }) return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
# coding: utf-8 from tapioca import ( TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin) from requests.auth import HTTPBasicAuth from .resource_mapping import RESOURCE_MAPPING class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter): resource_mapping = RESOURCE_MAPPING api_root = 'https://api.harvestapp.com/v2/' def get_request_kwargs(self, api_params, *args, **kwargs): params = super(HarvestClientAdapter, self).get_request_kwargs( api_params, *args, **kwargs) headers = { 'Authorization': 'Bearer %s' % params.get('token', ''), 'Harvest-Account-Id': params.get('account_id', ''), 'User-Agent': params.get('user_agent', '') } params['headers'] = params.get('headers', headers) params['headers']['Accept'] = 'application/json' return params def get_iterator_list(self, response_data): return response_data def get_iterator_next_request_kwargs(self, iterator_request_kwargs, response_data, response): pass def response_to_native(self, response): if response.content.strip(): return super(HarvestClientAdapter, self).response_to_native(response) Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
Set controller without __invoke method from invokable class
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Routing; use Symfony\Component\Routing\Loader\AnnotationClassLoader; use Symfony\Component\Routing\Route; /** * AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader * that sets the '_controller' default based on the class and method names. * * @author Fabien Potencier <[email protected]> */ class AnnotatedRouteControllerLoader extends AnnotationClassLoader { /** * Configures the _controller default parameter of a given Route instance. * * @param mixed $annot The annotation class instance */ protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot) { if ('__invoke' === $method->getName()) { $route->setDefault('_controller', $class->getName()); } else { $route->setDefault('_controller', $class->getName().'::'.$method->getName()); } } /** * Makes the default route name more sane by removing common keywords. * * @return string */ protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method) { return preg_replace(array( '/(bundle|controller)_/', '/action(_\d+)?$/', '/__/', ), array( '_', '\\1', '_', ), parent::getDefaultRouteName($class, $method)); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\FrameworkBundle\Routing; use Symfony\Component\Routing\Loader\AnnotationClassLoader; use Symfony\Component\Routing\Route; /** * AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader * that sets the '_controller' default based on the class and method names. * * @author Fabien Potencier <[email protected]> */ class AnnotatedRouteControllerLoader extends AnnotationClassLoader { /** * Configures the _controller default parameter of a given Route instance. * * @param mixed $annot The annotation class instance */ protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot) { $route->setDefault('_controller', $class->getName().'::'.$method->getName()); } /** * Makes the default route name more sane by removing common keywords. * * @return string */ protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method) { return preg_replace(array( '/(bundle|controller)_/', '/action(_\d+)?$/', '/__/', ), array( '_', '\\1', '_', ), parent::getDefaultRouteName($class, $method)); } }
Support for value of None in MoneyField.compress. Leaving a MoneyField blank in the Django admin site caused an issue when attempting to save an exception was raised since Money was getting an argument list of None.
from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): try: if data_list[0] is None: return None except IndexError: return None return Money(*data_list[:2])
from __future__ import unicode_literals from warnings import warn from django.forms import MultiValueField, DecimalField, ChoiceField from moneyed.classes import Money from .widgets import MoneyWidget, CURRENCY_CHOICES __all__ = ('MoneyField',) class MoneyField(MultiValueField): def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs): if currency_choices != CURRENCY_CHOICES: warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning) choices = currency_choices decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs) choice_field = ChoiceField(choices=currency_choices) self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget, currency_widget=choice_field.widget) fields = (decimal_field, choice_field) super(MoneyField, self).__init__(fields, *args, **kwargs) def compress(self, data_list): return Money(*data_list[:2])
Implement destroy function for category destroy
@if ((int) count($categories) === 0) <div class="alert alert-info" role="alert"> <strong><span class="fa fa-info-circle"></span> Info:</strong> Er zijn geen categorieen gevonden voor de helpdesk in het systeem. </div> @else <table class="table table-condensed table-hover"> <thead> <tr> <th>#</th> <th>Aangemaakt door:</th> <th>Categorie:</th> <th colspan="2">Vragen:</th> {{-- Colspan 2 is needed because the functions are embedded. --}} </tr> </thead> <tbody> @foreach($categories as $category) <tr> <td><code>#C{{ $category->id }}</code></td> <td>{{ $category->creator->name }}</td> <td>{{ $category->category }}</td> <td><span class="label label-primary">{{ count($category->question) }} Vragen </span></td> {{-- Functions --}} <td> <a href="{{ base_url() }}" class="label label-success">Bekijken</a> <a href="{{ base_url('category/destroy/', $category->id) }}" class="label label-danger">Verwijder</a> </td> {{-- /Functions --}} </tr> @endforeach </tbody> </table> @endif
@if ((int) count($categories) === 0) <div class="alert alert-info" role="alert"> <strong><span class="fa fa-info-circle"></span> Info:</strong> Er zijn geen categorieen gevonden voor de helpdesk in het systeem. </div> @else <table class="table table-condensed table-hover"> <thead> <tr> <th>#</th> <th>Aangemaakt door:</th> <th>Categorie:</th> <th colspan="2">Vragen:</th> {{-- Colspan 2 is needed because the functions are embedded. --}} </tr> </thead> <tbody> @foreach($categories as $category) <tr> <td><code>#C{{ $category->id }}</code></td> <td>{{ $category->creator->name }}</td> <td>{{ $category->category }}</td> <td><span class="label label-primary">{{ count($category->question) }} Vragen </span></td> {{-- Functions --}} <td> <a href="#" class="label label-success">Bekijken</a> <a href="#" class="label label-danger">Verwijder</a> </td> {{-- /Functions --}} </tr> @endforeach </tbody> </table> @endif
Allow newer versions of pyinotify
#!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'spotter', version = '1.7', url = "http://github.com/borntyping/spotter", author = "Sam Clements", author_email = "[email protected]", description = "A command line tool for watching files and running shell commands when they change.", long_description = open('README.rst').read(), license = 'MIT', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Operating System :: Unix', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Testing', 'Topic :: System :: Monitoring', 'Topic :: Utilities', ], packages = find_packages(), entry_points = { 'console_scripts': [ 'spotter = spotter:main', ] }, install_requires = [ 'pyinotify>=0.9.4', ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name = 'spotter', version = '1.7', url = "http://github.com/borntyping/spotter", author = "Sam Clements", author_email = "[email protected]", description = "A command line tool for watching files and running shell commands when they change.", long_description = open('README.rst').read(), license = 'MIT', classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Operating System :: Unix', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Testing', 'Topic :: System :: Monitoring', 'Topic :: Utilities', ], packages = find_packages(), entry_points = { 'console_scripts': [ 'spotter = spotter:main', ] }, install_requires = [ 'pyinotify==0.9.4', ], )
Update LTS versions in test matrix
/* eslint-env node */ module.exports = { scenarios: [ { name: 'ember-lts-2.12', npm: { devDependencies: { 'ember-source': '~2.12.0' } } }, { name: 'ember-lts-2.16', npm: { devDependencies: { 'ember-source': '~2.16.0' } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-canary', bower: { dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-default', npm: { devDependencies: {} } } ] };
/* eslint-env node */ module.exports = { scenarios: [ { name: 'ember-lts-2.8', bower: { dependencies: { 'ember': 'components/ember#lts-2-8' }, resolutions: { 'ember': 'lts-2-8' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-lts-2.12', npm: { devDependencies: { 'ember-source': '~2.12.0' } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-canary', bower: { dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-default', npm: { devDependencies: {} } } ] };
Update language for over view charts
'use strict'; module.exports = { $meta: 'English translation file', navigation: { overview: { $filter: 'role', district: 'District Performance', block: 'Block Performance', $default: 'Overview Performance' }, discrete: { $filter: 'role', district: 'Block Performance', block: 'Panchayat Performance', $default: 'Discrete Performance' } }, messages: { loading: 'Loading graph data', not_found: 'Page does not exist' }, payment_steps: { '1': 'Muster roll closure to muster roll entry', '2': 'Muster roll entry to wage list generation', '3': 'FTO generation to first signature', '4': 'Wage list generation to wage list sign', '5': 'Wage list sign to FTO generation', '6': 'First signature to second signature', '7': 'Second signature to processed by bank' }, performance: { overview: { performance_chart: { title: { $filter: 'role', district: 'District Performance', block: 'Block Performance', $default: 'Overview Performance' }, description: { $filter: 'role', district: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', block: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', $default: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' } } } } };
'use strict'; module.exports = { $meta: 'English translation file', navigation: { overview: { $filter: 'role', district: 'District Performance', block: 'Block Performance', $default: 'Overview Performance' }, discrete: { $filter: 'role', district: 'Block Performance', block: 'Panchayat Performance', $default: 'Discrete Performance' } }, messages: { loading: 'Loading graph data', not_found: 'Page does not exist' }, payment_steps: { '1': 'Muster roll closure to muster roll entry', '2': 'Muster roll entry to wage list generation', '3': 'FTO generation to first signature', '4': 'Wage list generation to wage list sign', '5': 'Wage list sign to FTO generation', '6': 'First signature to second signature', '7': 'Second signature to processed by bank' }, performance: { overview: { title: { $filter: 'role', district: 'You are looking at payment processing time in', block: 'You are looking at payment processing time in', $default: 'You are looking at payment processing time in' } } } };
Use heroku api by default
import React from 'react'; import { StyleSheet, Text, View, TextInput, Button } from 'react-native'; import Login from './components/Login/Login.js'; // TODO Use prod server in prod mode const server = 'https://satoshi-api.herokuapp.com' // const server = 'http://localhost:8080' export default class HomeScreen extends React.Component { constructor(props) { super(props); this.state = { text: null }; } onLogin = async (nickname) => { const deviceId = 'TODO DeviceID' console.log(`Login: (${nickname}, ${deviceId})`) // user credentials let response = await fetch(`${server}/api/login`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ nickname: nickname, deviceId: deviceId, }) }) let json = await response.json(); switch (json.status) { case 'STATUS_OK': this.props.navigation.navigate('Profile', { nickname: nickname }) return; } console.log('Username does not exist'); // TODO Display Error } render() { return ( <View> <Text>Welcome to Satoshi</Text> <Login onLogin={this.onLogin} /> </View> ); } }
import React from 'react'; import { StyleSheet, Text, View, TextInput, Button } from 'react-native'; import Login from './components/Login/Login.js'; // TODO Use prod server in prod mode // const server = 'https://satoshi-api.herokuapp.com' const server = 'http://localhost:8080' export default class HomeScreen extends React.Component { constructor(props) { super(props); this.state = { text: null }; } onLogin = async (nickname) => { const deviceId = 'TODO DeviceID' console.log(`Login: (${nickname}, ${deviceId})`) // user credentials let response = await fetch(`${server}/api/login`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ nickname: nickname, deviceId: deviceId, }) }) let json = await response.json(); switch (json.status) { case 'STATUS_OK': this.props.navigation.navigate('Profile', { nickname: nickname }) return; } console.log('Username does not exist'); // TODO Display Error } render() { return ( <View> <Text>Welcome to Satoshi</Text> <Login onLogin={this.onLogin} /> </View> ); } }
[TASK] Adjust test fixture to Doctrine.ORM 2.2.0 The proxy interface in Common is now used, the fixture needs to be adjusted. Change-Id: I0ed772ad4d04cf80679f7f726698c9278812b2d9 Related: #32608 Releases: 1.1 Original-Commit-Hash: c2c171d440e60457cbefc8e11ec83bc41b4fc7f9
<?php namespace TYPO3\FLOW3\Tests\Functional\Reflection\Fixtures; /* * * This script belongs to the FLOW3 framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ /** * A fixture for testing that doctrine proxies can never be reflected. * * See issue http://forge.typo3.org/issues/29449 for details. */ class BrokenClassImplementingDoctrineProxy { // This class just exists to satisfy the class loader -- else the compilation // run during functional tests will fail, as it expects to find a class named // like the file. It is NOT used for the testcase. } namespace TYPO3\FLOW3\Persistence\Doctrine\Proxies; /** * This is our fake "doctrine proxy class"; which is in the same namespace * as all the other doctrine proxies. Trying to reflect this class should * result in an exception. * */ abstract class FakePackageDomainModelBrokenClassProxy implements \Doctrine\ORM\Proxy\Proxy { } ?>
<?php namespace TYPO3\FLOW3\Tests\Functional\Reflection\Fixtures; /* * * This script belongs to the FLOW3 framework. * * * * It is free software; you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License, either version 3 * * of the License, or (at your option) any later version. * * * * The TYPO3 project - inspiring people to share! * * */ /** * A fixture for testing that doctrine proxies can never be reflected. * * See issue http://forge.typo3.org/issues/29449 for details. */ class BrokenClassImplementingDoctrineProxy { // This class just exists to satisfy the class loader -- else the compilation // run during functional tests will fail. It is NOT used for the testcase. } namespace TYPO3\FLOW3\Persistence\Doctrine\Proxies; /** * This is our fake "doctrine proxy class"; which is in the same namespace * as all the other doctrine proxies. Trying to reflect this class should * result in an exception. * */ class FakePackageDomainModelBrokenClassProxy implements \Doctrine\ORM\Proxy\Proxy { } ?>
Update the version of the config too.
package ro.nicuch.citizensbooks; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.Map; public class ConfigUpdater { public static boolean updateConfig(CitizensBooksPlugin plugin, int oldVersion) { if (oldVersion == 7) { Map<String, String> commandsMap = new HashMap<>(); plugin.getSettings().getConfigurationSection("commands").getKeys(false).forEach(str -> commandsMap.put(str, plugin.getSettings().getString("commands." + str))); plugin.getSettings().set("commands", null); commandsMap.forEach((key, value) -> { plugin.getSettings().set("commands." + key + ".filter_name", value); plugin.getSettings().set("commands." + key + ".permission", "none"); //default permission is to none }); plugin.getSettings().set("lang.player_not_found", ConfigDefaults.player_not_found); plugin.getSettings().set("lang.filter_not_found", ConfigDefaults.filter_not_found); plugin.getSettings().set("lang.usage.forceopen", ConfigDefaults.usage_forceopen); plugin.getSettings().set("lang.help.forceopen", ConfigDefaults.help_forceopen); plugin.getSettings().set("version", plugin.configVersion); //update the version plugin.saveSettings(); //save settings return true; } return false; } }
package ro.nicuch.citizensbooks; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.inventory.ItemStack; import java.util.HashMap; import java.util.Map; public class ConfigUpdater { public static boolean updateConfig(CitizensBooksPlugin plugin, int oldVersion) { if (oldVersion == 7) { Map<String, String> commandsMap = new HashMap<>(); plugin.getSettings().getConfigurationSection("commands").getKeys(false).forEach(str -> commandsMap.put(str, plugin.getSettings().getString("commands." + str))); plugin.getSettings().set("commands", null); commandsMap.forEach((key, value) -> { plugin.getSettings().set("commands." + key + ".filter_name", value); plugin.getSettings().set("commands." + key + ".permission", "none"); //default permission is to none }); plugin.getSettings().set("lang.player_not_found", ConfigDefaults.player_not_found); plugin.getSettings().set("lang.filter_not_found", ConfigDefaults.filter_not_found); plugin.getSettings().set("lang.usage.forceopen", ConfigDefaults.usage_forceopen); plugin.getSettings().set("lang.help.forceopen", ConfigDefaults.help_forceopen); plugin.saveSettings(); //save settings return true; } return false; } }
Remove bluebird require from AdapterManager
var fs = require('fs'), Path = require('path'); /** * Represents an object capable of listing and loading adapters using defined * conventions. * * @constructor */ var Adapters = function() { this.basePath = Path.resolve(Path.join(__dirname, '..', 'adapters')); }; Adapters.prototype = { /** * Gets a list of available adapters in the adapters folder. * @return {String[]} List containing the names of available adapters. */ getAdapters: function() { return fs.readdirSync(this.basePath) .map(d => Path.join(this.basePath, d)) .filter(d => fs.statSync(d).isDirectory()) .filter(d => fs.readdirSync(d).some(f => f === 'index.js')) .map(d => Path.basename(d)); }, /** * Loads an adapter. * @param {String} name Name of the adapter to be loaded. * @return {Promise} Promise that will be resolved when the given adapter is loaded. * Can be rejected if there's a problem during the process. */ loadAdapter: function(name) { return new Promise((resolve, reject) => { var entrypoint = Path.join(this.basePath, name, 'index.js'); try { var klass = require(entrypoint); resolve(klass); } catch(ex) { reject(ex); } }); } }; module.exports = Adapters;
var fs = require('fs'), Path = require('path'), Promise = require('bluebird'); /** * Represents an object capable of listing and loading adapters using defined * conventions. * * @constructor */ var Adapters = function() { this.basePath = Path.resolve(Path.join(__dirname, '..', 'adapters')); }; Adapters.prototype = { /** * Gets a list of available adapters in the adapters folder. * @return {String[]} List containing the names of available adapters. */ getAdapters: function() { return fs.readdirSync(this.basePath) .map(d => Path.join(this.basePath, d)) .filter(d => fs.statSync(d).isDirectory()) .filter(d => fs.readdirSync(d).some(f => f === 'index.js')) .map(d => Path.basename(d)); }, /** * Loads an adapter. * @param {String} name Name of the adapter to be loaded. * @return {Promise} Promise that will be resolved when the given adapter is loaded. * Can be rejected if there's a problem during the process. */ loadAdapter: function(name) { return new Promise((resolve, reject) => { var entrypoint = Path.join(this.basePath, name, 'index.js'); try { var klass = require(entrypoint); resolve(klass); } catch(ex) { reject(ex); } }); } }; module.exports = Adapters;
Fix group on equality iterator type hints
<?php namespace Pinq\Iterators\Standard; use Pinq\Iterators\Common; /** * Implementation of the join iterator using the fetch method. * * @author Elliot Levin <[email protected]> */ class GroupJoinOnEqualityIterator extends GroupJoinIterator { use Common\JoinOnEqualityIterator; /** * @var OrderedMap */ protected $innerGroups; public function __construct( IIterator $outerIterator, IIterator $innerIterator, callable $traversableFactory, callable $outerKeyFunction, callable $innerKeyFunction) { parent::__construct($outerIterator, $innerIterator, $traversableFactory); self::__constructJoinOnEqualityIterator($outerKeyFunction, $innerKeyFunction); } protected function doRewind() { $this->innerGroups = (new OrderedMap($this->innerIterator))->groupBy($this->innerKeyFunction); parent::doRewind(); } protected function getInnerValuesIterator($outerKey, $outerValue) { $outerKeyFunction = $this->outerKeyFunction; $traversableFactory = $this->traversableFactory; $groupKey = $outerKeyFunction($outerValue, $outerKey); $traversableGroup = $traversableFactory($this->innerGroups->contains($groupKey) ? $this->innerGroups->get($groupKey) : []); return new ArrayIterator([$groupKey => $traversableGroup]); } }
<?php namespace Pinq\Iterators\Standard; use Pinq\Iterators\Common; /** * Implementation of the join iterator using the fetch method. * * @author Elliot Levin <[email protected]> */ class GroupJoinOnEqualityIterator extends GroupJoinIterator { use Common\JoinOnEqualityIterator; /** * @var OrderedMap */ protected $innerGroups; public function __construct( \Traversable $outerIterator, \Traversable $innerIterator, callable $traversableFactory, callable $outerKeyFunction, callable $innerKeyFunction) { parent::__construct($outerIterator, $innerIterator, $traversableFactory); self::__constructJoinOnEqualityIterator($outerKeyFunction, $innerKeyFunction); } protected function doRewind() { $this->innerGroups = (new OrderedMap($this->innerIterator))->groupBy($this->innerKeyFunction); parent::doRewind(); } protected function getInnerValuesIterator($outerKey, $outerValue) { $outerKeyFunction = $this->outerKeyFunction; $traversableFactory = $this->traversableFactory; $groupKey = $outerKeyFunction($outerValue, $outerKey); $traversableGroup = $traversableFactory($this->innerGroups->contains($groupKey) ? $this->innerGroups->get($groupKey) : []); return new ArrayIterator([$groupKey => $traversableGroup]); } }
Add user page favorites and uploads number indicator
import React, { Component, PropTypes } from 'react' import { Container, Segment, Menu, Header, Label } from 'semantic-ui-react' import { Link } from 'react-router' import moment from 'moment' const propTypes = { user: PropTypes.object } class UserPage extends Component { render() { const { user } = this.props if (!user) return null return ( <Container> <Segment> <Menu secondary> <Menu.Item> <Header> <Link to={`/user/${user._id}`}>{user.username}</Link> <Header.Subheader> Joined {moment(user.createdAt).fromNow()} </Header.Subheader> </Header> </Menu.Item> <Menu.Item as={Link} to={`/user/${user._id}/favorites`} name="Favorites" activeClassName="active" > Favorites <Label color="yellow" content={user.favorites.length} floating /> </Menu.Item> <Menu.Item as={Link} to={`/user/${user._id}/uploads`} name="Uploads" activeClassName="active" > Uploads <Label color="teal" content={user.screenshots.length} floating /> </Menu.Item> {/* <Menu.Item name='Settings' activeClassName="active" /> */} </Menu> </Segment> <Segment basic vertical> {this.props.children} </Segment> </Container> ) } } UserPage.propTypes = propTypes export default UserPage
import React, { Component, PropTypes } from 'react' import { Container, Segment, Menu, Header } from 'semantic-ui-react' import { Link } from 'react-router' import moment from 'moment' const propTypes = { user: PropTypes.object } class UserPage extends Component { render() { const { user } = this.props if (!user) return null return ( <Container> <Segment> <Menu secondary> <Menu.Item> <Header> <Link to={`/user/${user._id}`}>{user.username}</Link> <Header.Subheader> Joined {moment(user.createdAt).fromNow()} </Header.Subheader> </Header> </Menu.Item> <Menu.Item as={Link} to={`/user/${user._id}/favorites`} name="Favorites" activeClassName="active" /> <Menu.Item as={Link} to={`/user/${user._id}/uploads`} name="Uploads" activeClassName="active" /> {/* <Menu.Item name='Settings' activeClassName="active" /> */} </Menu> </Segment> <Segment basic vertical> {this.props.children} </Segment> </Container> ) } } UserPage.propTypes = propTypes export default UserPage
Use the right case for the package name
#!/usr/bin/env python from distutils.core import setup, Command class TestDiscovery(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess errno = subprocess.call([ sys.executable, '-m', 'unittest', 'discover', '-p', '*.py', 'tests', ]) raise SystemExit(errno) setup(name='steel', version='0.1', description='A Python framework for describing binary file formats', author='Marty Alchin', author_email='[email protected]', url='https://github.com/gulopine/steel', packages=['steel'], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: System :: Filesystems', ], cmdclass={'test': TestDiscovery}, )
#!/usr/bin/env python from distutils.core import setup, Command class TestDiscovery(Command): user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import sys, subprocess errno = subprocess.call([ sys.executable, '-m', 'unittest', 'discover', '-p', '*.py', 'tests', ]) raise SystemExit(errno) setup(name='Steel', version='0.1', description='A Python framework for describing binary file formats', author='Marty Alchin', author_email='[email protected]', url='https://github.com/gulopine/steel', packages=['steel'], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: System :: Filesystems', ], cmdclass={'test': TestDiscovery}, )
Add Dependent Fixture Interface to fix fixture loading
<?php namespace Soflomo\Blog\Fixture; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Faker; use Soflomo\Blog\Entity\Article; class ArticleData extends AbstractFixture implements DependentFixtureInterface { protected $n = 10; public function load(ObjectManager $manager) { $blog = $this->getReference('blog'); $faker = Faker\Factory::create('nl_NL'); for ($i=1; $i<=$this->n; $i++) { $article = new Article; $article->setTitle($faker->sentence(rand(3,6))); // Words $article->setLead($faker->paragraph(rand(6,8))); // Sentences $article->setBody($faker->paragraph(rand(6,10))); // Sentences if (!$faker->boolean(10)) { // For 9/10 cases post has publish date $article->setPublishDate($faker->dateTimeThisMonth); } $article->setBlog($blog); $manager->persist($article); } $manager->flush(); } public function getDependencies() { return array( 'Soflomo\Blog\Fixture\BlogData', ); } }
<?php namespace Soflomo\Blog\Fixture; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\AbstractFixture; use Faker; use Soflomo\Blog\Entity\Article; class ArticleData extends AbstractFixture { protected $n = 10; public function load(ObjectManager $manager) { $blog = $this->getReference('blog'); $faker = Faker\Factory::create('nl_NL'); for ($i=1; $i<=$this->n; $i++) { $article = new Article; $article->setTitle($faker->sentence(rand(3,6))); // Words $article->setLead($faker->paragraph(rand(6,8))); // Sentences $article->setBody($faker->paragraph(rand(6,10))); // Sentences if (!$faker->boolean(10)) { // For 9/10 cases post has publish date $article->setPublishDate($faker->dateTimeThisMonth); } $article->setBlog($blog); $manager->persist($article); } $manager->flush(); } public function getDependencies() { return array( 'Soflomo\Blog\Fixture\BlogData', ); } }
Check we've got a result object before exiting the results loop.
/** * bit.ly access library code. */ Shortener = { displayName: 'Shortener', shorten: function() { var uri, callback, name; if (typeof arguments[0] == 'string') { uri = arguments[0]; callback = arguments[1]; } else { uri = window.location.href; callback = arguments[0]; } name = this._registerCallback(callback); if (name && this.CLIENT) { this.CLIENT.call('shorten', {'longUrl': uri}, 'BitlyCB.' + name); } }, _dispatcher: function(callback, data) { var result, p; // Results are keyed by longUrl, so we need to grab the first one. for (p in data.results) { result = data.results[p]; if (typeof result == 'object') break; } callback.call(null, result, data); }, _registerCallback: function(callback) { if (!this.NAMESPACE) return false; var name = 'abbr' + this.callbackCount, self = this; this.callbackCount += 1; this.NAMESPACE[name] = function(data) { self._dispatcher(callback, data); }; return name; }, callbackCount: 0, CLIENT: BitlyClient, NAMESPACE: BitlyCB };
/** * bit.ly access library code. */ Shortener = { displayName: 'Shortener', shorten: function() { var uri, callback, name; if (typeof arguments[0] == 'string') { uri = arguments[0]; callback = arguments[1]; } else { uri = window.location.href; callback = arguments[0]; } name = this._registerCallback(callback); if (name && this.CLIENT) { this.CLIENT.call('shorten', {'longUrl': uri}, 'BitlyCB.' + name); } }, _dispatcher: function(callback, data) { var result, p; // Results are keyed by longUrl, so we need to grab the first one. for (p in data.results) { result = data.results[p]; break; } callback.call(null, result, data); }, _registerCallback: function(callback) { if (!this.NAMESPACE) return false; var name = 'abbr' + this.callbackCount, self = this; this.callbackCount += 1; this.NAMESPACE[name] = function(data) { self._dispatcher(callback, data); }; return name; }, callbackCount: 0, CLIENT: BitlyClient, NAMESPACE: BitlyCB };
Update bookmark interface to work with mercurial 3.0.2 --HG-- extra : transplant_source : Qn%AB4%08%F4%3D%60%0DDb%10%E1%9C%A2%82%00z%1D5
# Mimic the hggit extension. try: from hggit import * hggit_reposetup = reposetup except ImportError: # Allow this module to be imported without # hg-git installed, eg for setup.py pass __version__ = "0.1.4" def reposetup(ui, repo, **kwargs): """ Automatically adds Bitbucket->GitHub mirror paths to the repo. Also creates a `master` bookmark for the `default` branch. """ if len(getattr(repo, "changelog", [])) == 0: return hggit_reposetup(ui, repo, **kwargs) bb = "ssh://[email protected]/" for pathname, path in ui.configitems("paths"): if path.startswith(bb): user, project = path.replace(bb, "").split("/", 1) # Strip slash and everything after it, # such as mq patch queue path. project = project.split("/")[0] for k, v in ui.configitems("github"): if k == "username": user = v gh_path = "git+ssh://[email protected]/%s/%s.git" % (user, project) if pathname == "default": if "master" not in repo._bookmarks: from mercurial.commands import bookmark bookmark(ui, repo, "master", rev="default") gh_pathname = "github" else: gh_pathname = "github-" + pathname ui.setconfig("paths", gh_pathname, gh_path)
# Mimic the hggit extension. try: from hggit import * hggit_reposetup = reposetup except ImportError: # Allow this module to be imported without # hg-git installed, eg for setup.py pass __version__ = "0.1.4" def reposetup(ui, repo, **kwargs): """ Automatically adds Bitbucket->GitHub mirror paths to the repo. Also creates a `master` bookmark for the `default` branch. """ if len(getattr(repo, "changelog", [])) == 0: return hggit_reposetup(ui, repo, **kwargs) bb = "ssh://[email protected]/" for pathname, path in ui.configitems("paths"): if path.startswith(bb): user, project = path.replace(bb, "").split("/", 1) # Strip slash and everything after it, # such as mq patch queue path. project = project.split("/")[0] for k, v in ui.configitems("github"): if k == "username": user = v gh_path = "git+ssh://[email protected]/%s/%s.git" % (user, project) if pathname == "default": if "master" not in repo._bookmarks: from mercurial.commands import bookmark bookmark(ui, repo, mark="master", rev="default") gh_pathname = "github" else: gh_pathname = "github-" + pathname ui.setconfig("paths", gh_pathname, gh_path)
Make mono channel output activation more readable
from keras.layers import Convolution2D, Reshape, Lambda, Activation from eva.layers.masked_convolution2d import MaskedConvolution2D class OutChannels(object): def __init__(self, height, width, channels, masked=False, palette=256): self.height = height self.width = width self.channels = channels self.cxp = MaskedConvolution2D if masked else Convolution2D self.palette = palette def __call__(self, model): if self.channels == 1: outs = Convolution2D(1, 1, 1, border_mode='valid')(model) outs = Activation('sigmoid')(outs) else: out = self.cxp(self.palette*self.channels, 1, 1, border_mode='valid', name='channels_mult_palette')(model) out = Reshape((self.height, self.width, self.palette, self.channels), name='palette_channels')(out) outs = [None] * self.channels for i in range(self.channels): outs[i] = Lambda(lambda x: x[:, :, :, :, i], name='channel'+str(i)+'_extract')(out) outs[i] = Reshape((self.height * self.width, self.palette), name='hw_palette'+str(i))(outs[i]) outs[i] = Activation('softmax', name='channel'+str(i))(outs[i]) return outs
from keras.layers import Convolution2D, Reshape, Lambda, Activation from eva.layers.masked_convolution2d import MaskedConvolution2D class OutChannels(object): def __init__(self, height, width, channels, masked=False, palette=256): self.height = height self.width = width self.channels = channels self.cxp = MaskedConvolution2D if masked else Convolution2D self.palette = palette def __call__(self, model): if self.channels == 1: outs = Convolution2D(1, 1, 1, activation='sigmoid', border_mode='valid')(model) else: out = self.cxp(self.palette*self.channels, 1, 1, border_mode='valid', name='channels_mult_palette')(model) out = Reshape((self.height, self.width, self.palette, self.channels), name='palette_channels')(out) outs = [None] * self.channels for i in range(self.channels): outs[i] = Lambda(lambda x: x[:, :, :, :, i], name='channel'+str(i)+'_extract')(out) outs[i] = Reshape((self.height * self.width, self.palette), name='hw_palette'+str(i))(outs[i]) outs[i] = Activation('softmax', name='channel'+str(i))(outs[i]) return outs
[HeartBeat] Allow current frame modifictation by event
(function($, document, window) { "use strict" window.animationHeartBeat = function (steps) { var max = steps; var delay = 70; var current = 0; var interval; var beat; $(document).bind('animation.stop', function() { console.log('animation.stop event caught'); clearInterval(interval); }); $(document).bind('animation.start', function() { console.log('animation.start event caught'); if (current > max) { $(document).trigger('animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('animation.reset', function() { console.log('animation.reset event caught'); current = 0; }); $(document).bind('animation.beat', function(event, animation) { current = animation.current + 1; }); beat = function () { $(document).trigger('animation.beat', [{'current': current, 'max': max}]); if (current > max) { $(document).trigger('animation.stop'); } } } })(jQuery, document, window);
(function($, document, window) { "use strict" window.animationHeartBeat = function (steps) { var max = steps; var delay = 70; var current = 0; var interval; var beat; $(document).bind('animation.stop', function() { console.log('animation.stop event caught'); clearInterval(interval); }); $(document).bind('animation.start', function() { console.log('animation.start event caught'); if (current > max) { $(document).trigger('animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('animation.reset', function() { console.log('animation.reset event caught'); current = 0; }); beat = function () { $(document).trigger('animation.beat', [{'current': current, 'max': max}]); current++; if (current > max) { $(document).trigger('animation.stop'); } } } })(jQuery, document, window);
Fix broken default config file
<?php namespace Jigsaw\Jigsaw\Console; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class InitCommand extends Command { private $files; private $base; public function __construct(Filesystem $files) { $this->files = $files; parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Scaffold a new Jigsaw project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base = getcwd() . '/' . $base; $this->createBaseDirectory(); } $this->createSourceFolder(); $this->createBaseConfig(); $this->info('Site initialized successfully!'); } private function createBaseDirectory() { if (! $this->files->isDirectory($this->base)) { $this->files->makeDirectory($this->base); } } private function createSourceFolder() { $this->files->makeDirectory($this->base . '/source'); } private function createBaseConfig() { $this->files->put($this->base . '/config.php', <<<EOT <?php return [ 'production' => false, ]; EOT ); } }
<?php namespace Jigsaw\Jigsaw\Console; use Illuminate\Filesystem\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class InitCommand extends Command { private $files; private $base; public function __construct(Filesystem $files) { $this->files = $files; parent::__construct(); } protected function configure() { $this->setName('init') ->setDescription('Scaffold a new Jigsaw project.') ->addArgument( 'name', InputArgument::OPTIONAL, 'Where should we initialize this project?' ); } protected function fire() { if ($base = $this->input->getArgument('name')) { $this->base = getcwd() . '/' . $base; $this->createBaseDirectory(); } $this->createSourceFolder(); $this->createBaseConfig(); $this->info('Site initialized successfully!'); } private function createBaseDirectory() { if (! $this->files->isDirectory($this->base)) { $this->files->makeDirectory($this->base); } } private function createSourceFolder() { $this->files->makeDirectory($this->base . '/source'); } private function createBaseConfig() { $this->files->put($this->base . '/config.php', <<<EOT <?php return [ 'production' = false, ]; EOT ); } }
Replace one last place where aioes was used
import elasticsearch import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except elasticsearch.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
import aioes import os.path from datetime import datetime from .utils import read_json_file from .settings import ELASTICSEARCH_ALIAS def create_new_index(elastic): print("Creating new index...") module_path = os.path.dirname(__file__) config_filename = os.path.join(module_path, 'configuration', 'index.json') index_configuration = read_json_file(config_filename) index_name = generate_index_name() elastic.indices.create(index_name, index_configuration) return index_name def switch_alias_to_index(elastic, alias_name, index_name): print("Switching alias '%s' to index '%s'..." % (alias_name, index_name)) try: existing_aliases = elastic.indices.get_alias(name=alias_name) except aioes.NotFoundError: existing_aliases = [] actions = [] for existing_index_name in existing_aliases: actions.append({ 'remove': { 'index': existing_index_name, 'alias': alias_name, } }) actions.append({ 'add': { 'index': index_name, 'alias': alias_name } }) elastic.indices.update_aliases({'actions': actions}) def generate_index_name(): return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
Make it so library doesn't spit out error, when trying to display 0
<?php namespace ByteUnits; class PowerScale { private $base; private $scale; private $precision; public function __construct($base, $scale, $precision) { $this->base = $base; $this->scale = $scale; $this->precision = $precision; } public function scaleToUnit($quantity, $unit) { if ($quantity === "0") return "0"; return bcdiv( $quantity, bcpow($this->base, $this->scale[$unit], $this->precision), $this->precision ); } public function scaleFromUnit($quantity, $unit) { return $quantity * bcpow( $this->base, $this->scale[$unit], $this->precision ); } public function isKnownUnit($unitAsString) { return preg_match( '/^(?:' . implode('|', array_keys($this->scale)) . ')$/i', trim($unitAsString) ); } public function normalizeNameOfUnit($unitAsString) { foreach ($this->scale as $unit => $_) { if (strtolower($unit) === strtolower($unitAsString)) { return $unit; } } } public function normalUnitFor($quantity) { foreach ($this->scale as $unit => $_) { $scaled = $this->scaleToUnit($quantity, $unit); if (bccomp($scaled, 1) >= 0) { return $unit; } } } public function isBaseUnit($unit) { return (!isset($this->scale[$unit]) || $this->scale[$unit] === 0); } }
<?php namespace ByteUnits; class PowerScale { private $base; private $scale; private $precision; public function __construct($base, $scale, $precision) { $this->base = $base; $this->scale = $scale; $this->precision = $precision; } public function scaleToUnit($quantity, $unit) { return bcdiv( $quantity, bcpow($this->base, $this->scale[$unit], $this->precision), $this->precision ); } public function scaleFromUnit($quantity, $unit) { return $quantity * bcpow( $this->base, $this->scale[$unit], $this->precision ); } public function isKnownUnit($unitAsString) { return preg_match( '/^(?:' . implode('|', array_keys($this->scale)) . ')$/i', trim($unitAsString) ); } public function normalizeNameOfUnit($unitAsString) { foreach ($this->scale as $unit => $_) { if (strtolower($unit) === strtolower($unitAsString)) { return $unit; } } } public function normalUnitFor($quantity) { foreach ($this->scale as $unit => $_) { $scaled = $this->scaleToUnit($quantity, $unit); if (bccomp($scaled, 1) >= 0) { return $unit; } } } public function isBaseUnit($unit) { return $this->scale[$unit] === 0; } }
Simplify definition of jscs task
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ] }, jscs: { src: "<%= jshint.all %>" }, nodeunit: { test: "test/test.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
module.exports = function( grunt ) { "use strict"; grunt.initConfig({ bump: { options: { files: [ "package.json" ], // Commit commit: true, commitMessage: "Release v%VERSION%", commitFiles: [ "package.json" ], // Tag createTag: true, tagName: "%VERSION%", tagMessage: "Version %VERSION%", // Push push: true, pushTo: "origin" } }, jshint: { options: { jshintrc: ".jshintrc" }, all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ] }, jscs: { all: { files: { src: "<%= jshint.all %>" }, options: { junit: "jscs-output.xml" } } }, nodeunit: { test: "test/test.js" } }); // Load grunt tasks from NPM packages require( "load-grunt-tasks" )( grunt ); grunt.loadTasks( "tasks" ); grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] ); };
Add flushing for console logging
package io.airlift.log; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Handler; import java.util.logging.LogRecord; import static java.nio.charset.StandardCharsets.UTF_8; final class OutputStreamHandler extends Handler { private final StaticFormatter formatter = new StaticFormatter(); private final AtomicBoolean reported = new AtomicBoolean(); private final Writer writer; public OutputStreamHandler(OutputStream out) { writer = new OutputStreamWriter(out, UTF_8); } @Override public void publish(LogRecord record) { if (!isLoggable(record)) { return; } try { writer.write(formatter.format(record)); writer.flush(); } catch (Exception e) { // try to report the first error if (!reported.getAndSet(true)) { PrintWriter error = new PrintWriter(writer); error.print("LOGGING FAILED: "); e.printStackTrace(error); error.flush(); } } } @Override public void flush() {} @Override public void close() {} }
package io.airlift.log; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.logging.Handler; import java.util.logging.LogRecord; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.logging.ErrorManager.CLOSE_FAILURE; import static java.util.logging.ErrorManager.FLUSH_FAILURE; import static java.util.logging.ErrorManager.FORMAT_FAILURE; import static java.util.logging.ErrorManager.WRITE_FAILURE; final class OutputStreamHandler extends Handler { private final Writer writer; public OutputStreamHandler(OutputStream out) { writer = new OutputStreamWriter(out, UTF_8); setFormatter(new StaticFormatter()); } @Override public void publish(LogRecord record) { if (!isLoggable(record)) { return; } String message; try { message = getFormatter().format(record); } catch (Exception e) { reportError(null, e, FORMAT_FAILURE); return; } try { writer.write(message); } catch (Exception e) { reportError(null, e, WRITE_FAILURE); } } @Override public void flush() { try { writer.flush(); } catch (Exception e) { reportError(null, e, FLUSH_FAILURE); } } @Override public void close() { try { writer.flush(); } catch (Exception e) { reportError(null, e, CLOSE_FAILURE); } } }
Fix for erroneous service definition
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ return array( 'factories' => array( 'BedRest.Dispatcher' => 'BedRest\Framework\Zend2\Service\DispatcherFactory', 'BedRest.ResourceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory', 'BedRest.ServiceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory', 'BedRest.ContentNegotiator' => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory', 'BedRest.ContentNegotiationStrategy' => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory', 'BedRest.ExceptionStrategy' => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory', 'BedRest.Request' => 'BedRest\Framework\Zend2\Service\RequestFactory' ) );
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ return array( 'factories' => array( 'BedRest.Dispatcher' => 'BedRest\Framework\Zend2\Service\DispatcherFactory', 'BedRest.ResourceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory', 'BedRest.ServiceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory', 'BedRest.ContentNegotiator' => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory', 'BedRest.ContentNegotiationStrategy' => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory', 'BedRest.ExceptionStrategy' => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory', 'BedRest.Request' => 'BedRest\Framework\Zend2\Service\Request' ) );
Make default QueryFactory return data (fixes test)
from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select app, name from django_migrations"
from django.conf import settings from django.contrib.auth.models import User import factory from website.models import Db, Query class TagsFactory(factory.DjangoModelFactory): class Meta: abstract = True @factory.post_generation def tags(self, create, extracted): if create and extracted: self.tags.add(*extracted) class UserFactory(factory.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda x: "user{}".format(x)) email = factory.Sequence(lambda x: "user{}@example.com".format(x)) password = factory.PostGenerationMethodCall('set_password', "password") class DbFactory(TagsFactory): class Meta: model = Db exclude = ('DB',) DB = settings.DATABASES['default'] name_short = "default" name_long = "default" type = "MySQL" host = factory.LazyAttribute(lambda a: a.DB['HOST']) db = factory.LazyAttribute(lambda a: a.DB['NAME']) port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306") username = factory.LazyAttribute(lambda a: a.DB['USER']) password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD']) class QueryFactory(TagsFactory): class Meta: model = Query title = "title" description = "description" db = factory.SubFactory(DbFactory) owner = factory.SubFactory(UserFactory) graph_extra = "{}" query_text = "select id, username from auth_user"
Fix issue observed in jenkins errors (missing comma)
/* global UTILS */ 'use strict'; angular.module('alienUiApp').factory('appEnvMngrService', ['applicationEnvironmentServices', function(applicationEnvironmentServices) { return { init: function(applicationId) { if(this.applicationId !== null) { this.close(); } this.applicationId = applicationId; this.update(); }, update: function() { var instance = this; return applicationEnvironmentServices.getAllEnvironments(this.applicationId).then(function(result) { instance.environments = result.data.data; instance.updateRegistrations(); return instance; }); }, updateRegistrations: function() { if(UTILS.isUndefinedOrNull(this.eventRegistrations)) { this.eventRegistrations = {}; } }, /** * Register for websocket updates on an environment status. */ register: function(environment) { var registration = environmentEventServicesFactory(application.id, environment, callback); this.eventRegistrations[environment.id] = registration; var isEnvDeployer = alienAuthService.hasResourceRole(environment, 'DEPLOYMENT_MANAGER'); if(isManager || isEnvDeployer) { this.deployEnvironments.push(environment); } isDeployer = isDeployer || isEnvDeployer; }, close: function() { for(var i=0; i < this.eventRegistrations.length; i++) { this.eventRegistrations[i].close(); } this.eventRegistrations = null; this.environments = null; this.deployEnvironments = null; } }; }]);
/* global UTILS */ 'use strict'; angular.module('alienUiApp').factory('appEnvMngrService', ['applicationEnvironmentServices', function(applicationEnvironmentServices) { return { init: function(applicationId) { if(this.applicationId !== null) { this.close(); } this.applicationId = applicationId; this.update(); }, update: function() { var instance = this; return applicationEnvironmentServices.getAllEnvironments(this.applicationId).then(function(result) { instance.environments = result.data.data; instance.updateRegistrations(); return instance; }); }, updateRegistrations: function() { if(UTILS.isUndefinedOrNull(this.eventRegistrations)) { this.eventRegistrations = {}; } }, /** * Register for websocket updates on an environment status. */ register: function(environment) { var registration = environmentEventServicesFactory(application.id, environment, callback); this.eventRegistrations[environment.id] = registration; var isEnvDeployer = alienAuthService.hasResourceRole(environment, 'DEPLOYMENT_MANAGER'); if(isManager || isEnvDeployer) { this.deployEnvironments.push(environment); } isDeployer = isDeployer || isEnvDeployer; } close: function() { for(var i=0; i < this.eventRegistrations.length; i++) { this.eventRegistrations[i].close(); } this.eventRegistrations = null; this.environments = null; this.deployEnvironments = null; } }; }]);
FIx Document provider not refetching
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; export const fetchCountriesDocumentsInit = createAction( 'fetchCountriesDocumentsInit' ); export const fetchCountriesDocumentsReady = createAction( 'fetchCountriesDocumentsReady' ); export const fetchCountriesDocumentsFail = createAction( 'fetchCountriesDocumentsFail' ); export const fetchCountriesDocuments = createThunkAction( 'fetchCountriesDocuments', location => (dispatch, state) => { const { countriesDocuments } = state(); if ( !countriesDocuments.loading && (!location || !countriesDocuments.data || isEmpty(countriesDocuments.data[location])) ) { const url = `/api/v1/ndcs/countries_documents${ location ? `?location=${location}` : '' }`; dispatch(fetchCountriesDocumentsInit()); fetch(url) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchCountriesDocumentsReady(data.data)); }) .catch(error => { console.warn(error); dispatch(fetchCountriesDocumentsFail()); }); } } ); export default { fetchCountriesDocuments, fetchCountriesDocumentsInit, fetchCountriesDocumentsReady, fetchCountriesDocumentsFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; import isEmpty from 'lodash/isEmpty'; export const fetchCountriesDocumentsInit = createAction( 'fetchCountriesDocumentsInit' ); export const fetchCountriesDocumentsReady = createAction( 'fetchCountriesDocumentsReady' ); export const fetchCountriesDocumentsFail = createAction( 'fetchCountriesDocumentsFail' ); export const fetchCountriesDocuments = createThunkAction( 'fetchCountriesDocuments', location => (dispatch, state) => { const { countriesDocuments } = state(); if ( !countriesDocuments.loading && (isEmpty(countriesDocuments.data) || (!!location && isEmpty(countriesDocuments.data[location]))) ) { const url = `/api/v1/ndcs/countries_documents${ location ? `?location=${location}` : '' }`; dispatch(fetchCountriesDocumentsInit()); fetch(url) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchCountriesDocumentsReady(data.data)); }) .catch(error => { console.warn(error); dispatch(fetchCountriesDocumentsFail()); }); } } ); export default { fetchCountriesDocuments, fetchCountriesDocumentsInit, fetchCountriesDocumentsReady, fetchCountriesDocumentsFail };
Add error logging level methods
<?php namespace LaravelDecouplr\Log; use Decouplr\Decouplr; use Illuminate\Log\Writer; abstract class LaravelLogDecouplr extends Decouplr { public function __construct(Writer $writer){ $this->decoupled = $writer; } public function useFiles() { return $this->delegate(__FUNCTION__, func_get_args()); } public function useDailyFiles() { return $this->delegate(__FUNCTION__, func_get_args()); } public function useErrorLog() { return $this->delegate(__FUNCTION__, func_get_args()); } public function listen() { return $this->delegate(__FUNCTION__, func_get_args()); } public function getMonolog() { return $this->delegate(__FUNCTION__, func_get_args()); } public function getEventDispatcher() { return $this->delegate(__FUNCTION__, func_get_args()); } public function setEventDispatcher() { return $this->delegate(__FUNCTION__, func_get_args()); } public function write() { return $this->delegate(__FUNCTION__, func_get_args()); } public function debug() { return $this->delegate(__FUNCTION__, func_get_args()); } public function notice() { return $this->delegate(__FUNCTION__, func_get_args()); } public function warning() { return $this->delegate(__FUNCTION__, func_get_args()); } public function error() { return $this->delegate(__FUNCTION__, func_get_args()); } public function critical() { return $this->delegate(__FUNCTION__, func_get_args()); } public function alert() { return $this->delegate(__FUNCTION__, func_get_args()); } }
<?php namespace LaravelDecouplr\Log; use Decouplr\Decouplr; use Illuminate\Log\Writer; abstract class LaravelLogDecouplr extends Decouplr { public function __construct(Writer $writer){ $this->decoupled = $writer; } public function useFiles() { return $this->delegate(__FUNCTION__, func_get_args()); } public function useDailyFiles() { return $this->delegate(__FUNCTION__, func_get_args()); } public function useErrorLog() { return $this->delegate(__FUNCTION__, func_get_args()); } public function listen() { return $this->delegate(__FUNCTION__, func_get_args()); } public function getMonolog() { return $this->delegate(__FUNCTION__, func_get_args()); } public function getEventDispatcher() { return $this->delegate(__FUNCTION__, func_get_args()); } public function setEventDispatcher() { return $this->delegate(__FUNCTION__, func_get_args()); } public function write() { return $this->delegate(__FUNCTION__, func_get_args()); } }
Make the weather page use a named controller. We have to use named controllers rather than inline controllers because we want to be able to indicate to the client which controller to use to render the page. We can send the client a string to look up, but we can't reliably serialize the controller function and transmit it.
var app = angular.module('simpleapp', ['ng', 'ngRoute']); app.controller( 'simpleController', function ($scope, $location, $http) { $scope.currentUrl = $location.absUrl(); } ); app.controller( 'weatherController', function (weatherData, $scope) { $scope.weather = weatherData; } ); app.config( function ($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider.when( '/weather', { template: '<h2>Weather for {{weather.name}}</h2><pre>{{weather | json}}</pre>', resolve: { weatherData: function ($http) { return $http.get( 'http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,%20CA,%20US' ).then(function (resp) { return resp.data; }); } }, controller: 'weatherController' } ); $routeProvider.otherwise( { template: '<a href="/weather">Weather</a>' } ); } );
var app = angular.module('simpleapp', ['ng', 'ngRoute']); app.controller( 'simpleController', function ($scope, $location, $http) { $scope.currentUrl = $location.absUrl(); } ); app.config( function ($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider.when( '/weather', { template: '<h2>Weather for {{weather.name}}</h2><pre>{{weather | json}}</pre>', resolve: { weatherData: function ($http) { return $http.get( 'http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,%20CA,%20US' ).then(function (resp) { return resp.data; }); } }, controller: function (weatherData, $scope) { $scope.weather = weatherData; } } ); $routeProvider.otherwise( { template: '<a href="/weather">Weather</a>' } ); } );
Remove unused and commented code
#!/usr/bin/env node var S=require('surku'); var fs=require('fs'); var surkuConfig={ maxMutations:20, minMutations:1, chunkSize:3000 }; var surku=new S(surkuConfig); function init(config){ surkuConfig.tempDirectory=config.tempDirectory; } function generateTestCase(getSample,callback){ var prefix=new Date().getTime()+Math.random().toString().split('.')[1]; var sampleFile=getSample(1)[0]; if(sampleFile){ var fileName=surkuConfig.tempDirectory+'/samples/'+prefix; var fileContent=fs.readFileSync(sampleFile); var chunkSize=Math.ceil(fileContent.length/100); if(chunkSize>3000){ surku.config.chunkSize=3000; }else if(chunkSize<500){ surku.config.chunkSize=500; } else{ surku.config.chunkSize=chunkSize; } var testCase=surku.generateTestCase(fileContent); fs.writeFile(fileName,testCase,function(){ callback({type:"file",data:fileName}); }); } else{ callback(); } } module.exports={ init, generateTestCase };
#!/usr/bin/env node var S=require('surku'); var fs=require('fs'); var path=require('path'); var surkuConfig={ maxMutations:20, minMutations:1, chunkSize:3000 }; var surku=new S(surkuConfig); function init(config){ surkuConfig.tempDirectory=config.tempDirectory; } function generateTestCase(getSample,callback){ //console.log('surku') var prefix=new Date().getTime()+Math.random().toString().split('.')[1]; var sampleFile=getSample(1)[0]; if(sampleFile){ var fileName=surkuConfig.tempDirectory+'/samples/'+prefix; var fileContent=fs.readFileSync(sampleFile); var chunkSize=Math.ceil(fileContent.length/100); if(chunkSize>3000){ surku.config.chunkSize=3000; }else if(chunkSize<500){ surku.config.chunkSize=500; } else{ surku.config.chunkSize=chunkSize; } var testCase=surku.generateTestCase(fileContent); fs.writeFile(fileName,testCase,function(){ //console.log(fileName) //console.log("New length: "+testCase.length+ " Original length: "+fileContent.length) callback({type:"file",data:fileName}); }); } else{ callback(); } } module.exports={ init, generateTestCase };
Update mtgox api endpoint to use SSL
"""Bitccoin ticker module for ppbot. @package ppbot Displays the current bitcoin pricing from mtgox @syntax btc """ import requests import string import json from xml.dom.minidom import parseString from modules import * class Bitcoin(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "https://data.mtgox.com/api/1/BTCUSD/ticker" def _register_events(self): """Register module commands.""" self.add_command('btc') def btc(self, event): """Action to react/respond to user calls.""" data = {} try: result = self.lookup()['return'] data['high'] = result['high']['display_short'] data['last'] = result['last_local']['display_short'] data['low'] = result['low']['display_short'] data['volume'] = result['vol']['display_short'] message = "Last: %(last)s - High/Low: (%(high)s/%(low)s) - Volume: %(volume)s" % (data) self.msg(event['target'], message) except: pass def lookup(self): """Connects to google's secret finance API and parses the receiving json for the stock info.""" # make the parser, and send the xml to be parsed result = requests.get(self.url) return result.json()
"""Bitccoin ticker module for ppbot. @package ppbot Displays the current bitcoin pricing from mtgox @syntax btc """ import requests import string import json from xml.dom.minidom import parseString from modules import * class Bitcoin(Module): def __init__(self, *args, **kwargs): """Constructor""" Module.__init__(self, kwargs=kwargs) self.url = "http://data.mtgox.com/api/1/BTCUSD/ticker" def _register_events(self): """Register module commands.""" self.add_command('btc') def btc(self, event): """Action to react/respond to user calls.""" data = {} try: result = self.lookup()['return'] data['high'] = result['high']['display_short'] data['last'] = result['last_local']['display_short'] data['low'] = result['low']['display_short'] data['volume'] = result['vol']['display_short'] message = "Last: %(last)s - High/Low: (%(high)s/%(low)s) - Volume: %(volume)s" % (data) self.msg(event['target'], message) except: pass def lookup(self): """Connects to google's secret finance API and parses the receiving json for the stock info.""" # make the parser, and send the xml to be parsed result = requests.get(self.url) return result.json()
Feature: Remove deprecated reference + always cleanup the <style> block
<?php namespace Fedeisas\LaravelMailCssInliner; use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; class CssInlinerPlugin implements \Swift_Events_SendListener { /** * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $converter = new CssToInlineStyles(); $converter->setUseInlineStylesBlock(); $converter->setStripOriginalStyleTags(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || ($message->getContentType() === 'multipart/alternative' && $message->getBody()) ) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } } /** * Do nothing * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(\Swift_Events_SendEvent $evt) { // Do Nothing } }
<?php namespace Fedeisas\LaravelMailCssInliner; use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; class CssInlinerPlugin implements \Swift_Events_SendListener { /** * @param Swift_Events_SendEvent $evt */ public function beforeSendPerformed(\Swift_Events_SendEvent $evt) { $message = $evt->getMessage(); $converter = new CssToInlineStyles(); $converter->setEncoding($message->getCharset()); $converter->setUseInlineStylesBlock(); $converter->setCleanup(); if ($message->getContentType() === 'text/html' || ($message->getContentType() === 'multipart/alternative' && $message->getBody()) ) { $converter->setHTML($message->getBody()); $message->setBody($converter->convert()); } foreach ($message->getChildren() as $part) { if (strpos($part->getContentType(), 'text/html') === 0) { $converter->setHTML($part->getBody()); $part->setBody($converter->convert()); } } } /** * Do nothing * * @param Swift_Events_SendEvent $evt */ public function sendPerformed(\Swift_Events_SendEvent $evt) { // Do Nothing } }
Bump version to see if pip installs it
import multiprocessing from setuptools import setup, find_packages setup( name='sow-generator', version='0.1.1', description='Create a scope of work from templates and version controlled documentation.', long_description = open('README.rst', 'r').read() + open('CHANGELOG.rst', 'r').read() + open('AUTHORS.rst', 'r').read(), author='Hedley Roos', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/sow-generator', packages = find_packages(), install_requires = [ 'Django<1.7', 'South', 'celery', 'django-celery', 'raven', 'PyYAML', 'requests', 'github3.py', 'pyandoc', 'django-object-tools', 'django-adminplus' ], include_package_data=True, tests_require=[ 'django-setuptest>=0.1.4', ], test_suite="setuptest.setuptest.SetupTestSuite", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
import multiprocessing from setuptools import setup, find_packages setup( name='sow-generator', version='0.1', description='Create a scope of work from templates and version controlled documentation.', long_description = open('README.rst', 'r').read() + open('CHANGELOG.rst', 'r').read() + open('AUTHORS.rst', 'r').read(), author='Hedley Roos', author_email='[email protected]', license='BSD', url='http://github.com/praekelt/sow-generator', packages = find_packages(), install_requires = [ 'Django<1.7', 'South', 'celery', 'django-celery', 'raven', 'PyYAML', 'requests', 'github3.py', 'pyandoc', 'django-object-tools', 'django-adminplus' ], include_package_data=True, tests_require=[ 'django-setuptest>=0.1.4', ], test_suite="setuptest.setuptest.SetupTestSuite", classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Framework :: Django", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], zip_safe=False, )
Fix gulp task. Bundle should start after Transform is done.
var plumber = require("gulp-plumber"); var webpack = require("gulp-webpack"); var cssmin = require("gulp-minify-css"); var csscon = require("gulp-concat-css"); var jshint = require("gulp-jshint"); var watch = require("gulp-watch"); var react = require("gulp-react"); var gulp = require("gulp"); gulp.task("lint", function () { return gulp.src(["server.js", "client.js", "test.js", "./build/*.js"]). pipe(jshint()). pipe(jshint.reporter("default")); }); gulp.task("bundle:css", function () { return gulp.src("stylesheet/*.css"). pipe(csscon("blog.0.1.0.min.css")). pipe(cssmin()). pipe(gulp.dest("static")); }); gulp.task("transform", function () { return gulp.src("component/*.jsx"). pipe(react()). pipe(jshint()). pipe(jshint.reporter("default", { verbose: true })). pipe(gulp.dest("build")); }); gulp.task("bundle:js", ["transform"], function () { return gulp.src("./client.js"). pipe(webpack(require("./webpack.config.js"))). pipe(gulp.dest("static")); }); gulp.task("default", function () { gulp.watch("stylesheet/*.css", ["bundle:css"]); gulp.watch("component/*.jsx", ["bundle:js"]); return; });
var plumber = require("gulp-plumber"); var webpack = require("gulp-webpack"); var cssmin = require("gulp-minify-css"); var csscon = require("gulp-concat-css"); var jshint = require("gulp-jshint"); var watch = require("gulp-watch"); var react = require("gulp-react"); var gulp = require("gulp"); gulp.task("css", function () { return gulp.src("stylesheet/*.css"). pipe(csscon("blog.0.1.0.min.css")). pipe(cssmin()). pipe(gulp.dest("static")); }); gulp.task("transform", function () { return gulp.src("component/*.jsx"). pipe(react()). pipe(jshint()). pipe(jshint.reporter("default", { verbose: true })). pipe(gulp.dest("build")); }); gulp.task("bundle", function () { return gulp.src("./client.js"). pipe(webpack(require("./webpack.config.js"))). pipe(gulp.dest("static")); }); gulp.task("default", function () { gulp.watch("stylesheet/*.css", ["css"]); gulp.watch("component/*.jsx", ["transform", "bundle"]); return; }); gulp.task("lint", function () { return gulp.src(["server.js", "client.js", "test.js", "./build/*.js"]). pipe(jshint()). pipe(jshint.reporter("default")); });
Use 'fields' instead of 'kwargs' to document intent.
# -*- coding: utf-8 -*- """ The Renderer class provides the infrastructure for generating template-based code. It's used by the .grammars module for parser generation. """ from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')}) override = self.render_fields(fields) if template is None: if override is not None: template = override else: template = self.template fields.update(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- """ The Renderer class provides the infrastructure for generating template-based code. It's used by the .grammars module for parser generation. """ from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **kwargs): fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')}) override = self.render_fields(fields) if template is None: if override is not None: template = override else: template = self.template fields.update(kwargs) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Set defalut focus on first input element in search panel
angular.module('openspecimen') .directive('osRightDrawer', function(osRightDrawerSvc) { return { restrict: 'A', link: function(scope, element, attrs) { element.addClass('os-right-drawer'); element.removeAttr('os-right-drawer'); var header = element.find('div.os-head'); if (header) { var divider = angular.element('<div/>') .addClass('os-divider'); header.after(divider); } osRightDrawerSvc.setDrawer(element); } }; }) .directive('osRightDrawerToggle', function(osRightDrawerSvc) { return { restrict: 'A', link: function(scope, element, attrs) { element.on('click', function() { osRightDrawerSvc.toggle(); }); } }; }) .factory('osRightDrawerSvc', function() { var drawerEl = undefined; return { setDrawer: function(drawer) { drawerEl = drawer; }, toggle: function() { drawerEl.toggleClass('active'); var cardsDiv = drawerEl.parent().find("div.os-cards"); if (drawerEl.hasClass('active')) { var firstInput = drawerEl.find("input")[0]; if (firstInput) { firstInput.focus(); } cardsDiv.css("width", "75%"); } else { cardsDiv.css("width", "100%"); } } } });
angular.module('openspecimen') .directive('osRightDrawer', function(osRightDrawerSvc) { return { restrict: 'A', link: function(scope, element, attrs) { element.addClass('os-right-drawer'); element.removeAttr('os-right-drawer'); var header = element.find('div.os-head'); if (header) { var divider = angular.element('<div/>') .addClass('os-divider'); header.after(divider); } osRightDrawerSvc.setDrawer(element); } }; }) .directive('osRightDrawerToggle', function(osRightDrawerSvc) { return { restrict: 'A', link: function(scope, element, attrs) { element.on('click', function() { osRightDrawerSvc.toggle(); }); } }; }) .factory('osRightDrawerSvc', function() { var drawerEl = undefined; return { setDrawer: function(drawer) { drawerEl = drawer; }, toggle: function() { drawerEl.toggleClass('active'); var cardsDiv = drawerEl.parent().find("div.os-cards"); if (drawerEl.hasClass('active')) { cardsDiv.css("width", "75%"); } else { cardsDiv.css("width", "100%"); } } } });
Fix Generator verification in loop()
<?php declare(strict_types=1); namespace Funktions; use Exception; use Generator; /** * Return a value based on a test * * @param boolean $test * @param callable $truthy * @param callable $falsy * @return mixed */ function condition(bool $test, callable $truthy, callable $falsy) { if ($test) { return call_user_func($truthy); } return call_user_func($falsy); } /** * Loop over items and pass them to a generator * * @param iterable $iterable * @param callable $callable * @return array */ function loop(iterable $iterable, callable $callable): array { $array = []; foreach ($iterable as $item) { $generator = call_user_func($callable, $item); if ($generator instanceof Generator === false) { throw new Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } return $array; } /** * Loop in a generator until a returned condition * * @param callable $callable * @return array */ function loop_until(callable $callable): array { $array = []; do { $generator = call_user_func($callable); if ($generator instanceof Generator === false) { throw Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } while(!$generator->getReturn()); return $array; }
<?php declare(strict_types=1); namespace Funktions; use Exception; /** * Return a value based on a test * * @param boolean $test * @param callable $truthy * @param callable $falsy * @return mixed */ function condition(bool $test, callable $truthy, callable $falsy) { if ($test) { return call_user_func($truthy); } return call_user_func($falsy); } /** * Loop over items and pass them to a generator * * @param iterable $iterable * @param callable $callable * @return array */ function loop(iterable $iterable, callable $callable): array { $array = []; foreach ($iterable as $item) { $generator = call_user_func($callable, $item); if ($generator instanceof Generator === false) { throw new Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } return $array; } /** * Loop in a generator until a returned condition * * @param callable $callable * @return array */ function loop_until(callable $callable): array { $array = []; do { $generator = call_user_func($callable); if ($generator instanceof Generator === false) { throw Exception('Callable must be a generator'); } $array = array_merge($array, iterator_to_array($generator)); } while(!$generator->getReturn()); return $array; }
Check in built Stateful mixin
define( ["ember","./machine","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var Mixin = __dependency1__.Mixin; var computed = __dependency1__.computed; var Machine = __dependency2__["default"] || __dependency2__; __exports__["default"] = Mixin.create({ fsmEvents: null, fsmStates: null, fsmInitialState: null, fsmIsLoading: computed.oneWay('__fsm__.isTransitioning'), fsmCurrentState: computed.oneWay('__fsm__.currentState'), init: function() { var params = {}; var mixin = {}; var fsm; params.target = this; params.events = this.get('fsmEvents'); params.states = this.get('fsmStates'); params.initialState = this.get('fsmInitialState'); fsm = Machine.create(params); this.set('__fsm__', fsm); fsm.isInStateAccessorProperties.forEach(function(prop) { mixin[prop] = computed.oneWay('__fsm__.' + prop); }); this.reopen(mixin); this._super(); }, sendStateEvent: function() { var fsm = this.get('__fsm__'); return fsm.send.apply(fsm, arguments); } }); });
define( ["ember","./machine","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var Mixin = __dependency1__.Mixin; var computed = __dependency1__.computed; var Machine = __dependency2__["default"] || __dependency2__; __exports__["default"] = Mixin.create({ fsmEvents: null, fsmStates: null, initialState: null, isLoading: computed.oneWay('__fsm__.isTransitioning'), currentState: computed.oneWay('__fsm__.currentState'), init: function() { var params = {}; var mixin = {}; var fsm; params.target = this; params.events = this.get('fsmEvents'); params.states = this.get('fsmStates'); params.initialState = this.get('initialState'); fsm = Machine.create(params); this.set('__fsm__', fsm); fsm.isInStateAccessorProperties.forEach(function(prop) { mixin[prop] = computed.oneWay('__fsm__.' + prop); }); this.reopen(mixin); this._super(); }, sendStateEvent: function() { var fsm = this.get('__fsm__'); return fsm.send.apply(fsm, arguments); } }); });
Add 'Systems Administration' to the list of project classifiers
from setuptools import setup, find_packages from suponoff import __version__ as version if __name__ == '__main__': with open("README.rst") as f: long_description = f.read() setup( name="suponoff", version=version, author="Gambit Research", author_email="[email protected]", description="An alternative Supervisor web interface.", long_description=long_description, license="BSD", url="", zip_safe=False, include_package_data=True, packages=find_packages(), scripts=[ 'suponoff-monhelper.py' ], install_requires=[ "Django >= 1.7", # just because I only tested with Django 1.7... ], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: WSGI", ("Topic :: Software Development :: Libraries :: " "Application Frameworks"), "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Systems Administration", ])
from setuptools import setup, find_packages from suponoff import __version__ as version if __name__ == '__main__': with open("README.rst") as f: long_description = f.read() setup( name="suponoff", version=version, author="Gambit Research", author_email="[email protected]", description="An alternative Supervisor web interface.", long_description=long_description, license="BSD", url="", zip_safe=False, include_package_data=True, packages=find_packages(), scripts=[ 'suponoff-monhelper.py' ], install_requires=[ "Django >= 1.7", # just because I only tested with Django 1.7... ], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: Linux", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Internet :: WWW/HTTP :: WSGI", ("Topic :: Software Development :: Libraries :: " "Application Frameworks"), "Topic :: Software Development :: Libraries :: Python Modules", ])
Use try_update_model in sign in handler instead of dict update.
""" """ from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) if (not self.try_update_model(m) or not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id})
""" """ from wheezy.core.collections import attrdict from wheezy.core.comp import u from wheezy.security import Principal from wheezy.web.authorization import authorize from shared.views import APIHandler from membership.validation import credential_validator class SignInHandler(APIHandler): def post(self): m = attrdict(username=u(''), password=u('')) m.update(self.request.form) if (not self.validate(m, credential_validator) or not self.authenticate(m)): return self.json_errors() return self.json_response({'username': m.username}) def authenticate(self, credential): with self.factory('ro') as f: user = f.membership.authenticate(credential) if not user: return False self.principal = Principal(id=user['id']) return True class SignUpHandler(APIHandler): def post(self): m = attrdict(email=u(''), username=u(''), password=u('')) m.update(self.request.form) if not self.signup(m): return self.json_errors() return self.json_response({}) def signup(self, m): self.error('This feature is not available yet.') return False class SignOutHandler(APIHandler): def get(self): del self.principal return self.json_response({'ok': True}) class UserHandler(APIHandler): @authorize def get(self): return self.json_response({'username': self.principal.id})
Implement deleteAll as a variant of delete Will need to add tests for this entire thing later. Change-Id: Ib40fe1d4f126923ed1788417f144d0d45fd24e61
package org.wikimedia.wikipedia.data; import android.content.ContentProviderClient; import android.net.Uri; import android.os.RemoteException; abstract public class ContentPersister<T> { private final ContentProviderClient client; private final PersistanceHelper<T> persistanceHelper; public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) { this.client = client; this.persistanceHelper = persistanceHelper; } public void persist(T obj) { Uri uri = Uri.parse("content://" + SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) + "/" + persistanceHelper.getTableName()); try { client.insert(uri, persistanceHelper.toContentValues(obj)); } catch (RemoteException e) { // This shouldn't happen throw new RuntimeException(e); } } public void deleteAll() { deleteWhere("", new String[] {}); } public void deleteWhere(String selection, String[] selectionArgs) { Uri uri = persistanceHelper.getBaseContentURI(); try { client.delete(uri, selection, selectionArgs); } catch (RemoteException e) { // This also shouldn't happen throw new RuntimeException(e); } } public void cleanup() { this.client.release(); } }
package org.wikimedia.wikipedia.data; import android.content.ContentProviderClient; import android.net.Uri; import android.os.RemoteException; abstract public class ContentPersister<T> { private final ContentProviderClient client; private final PersistanceHelper<T> persistanceHelper; public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) { this.client = client; this.persistanceHelper = persistanceHelper; } public void persist(T obj) { Uri uri = Uri.parse("content://" + SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) + "/" + persistanceHelper.getTableName()); try { client.insert(uri, persistanceHelper.toContentValues(obj)); } catch (RemoteException e) { // This shouldn't happen throw new RuntimeException(e); } } public void deleteAll() { Uri uri = persistanceHelper.getBaseContentURI(); try { client.delete(uri, "", new String[] {}); } catch (RemoteException e) { // This also shouldn't happen throw new RuntimeException(e); } } public void cleanup() { this.client.release(); } }
Fix duplicates in imported venues
var Event = require('../models/Event.js'); var Venue = require('../models/Venue.js'); exports.sync = function(events) { events.map(function(evt) { var eventquery = { 'title': evt.title, 'startAt': evt.startAt }; Event.findOne( eventquery, function (err, doc) { if (!doc) { Event.create(evt, function (err, doc) { if (err) { console.log("Something went wrong in creating new event"); } } ); } } ); var venuequery = { 'name': evt.venue.name }; var venue = {}; venue.name = evt.venue.name; venue.address = evt.venue.address; venue.latitude = evt.venue.latitude; venue.longitude = evt.venue.longitude; Venue.findOneAndUpdate( venuequery, venue, {'upsert': true}, function(err, doc) { if (err) { console.log("Something went wrong in creating new event"); } } ); }); };
var Event = require('../models/Event.js'); var Venue = require('../models/Venue.js'); exports.sync = function(events) { events.map(function(evt) { var eventquery = { 'title': evt.title, 'startAt': evt.startAt }; Event.findOne( eventquery, function(err, doc) { if(!doc){ Event.create(evt , function(err, doc){ if(err){ console.log("Something went wrong in creating new event"); } } );} } ); var venuequery = { 'name': evt.venue.name }; Venue.findOne( venuequery, function(err, doc) { if(!doc){ var venue = new Venue(); venue.name = evt.venue.name; venue.address = evt.venue.address; venue.latitude = evt.venue.latitude; venue.longitude = evt.venue.longitude; venue.save(function(err, doc){ if(err){ console.log("Something went wrong in creating new event"); } } );} } ); }); };
Fix encoding (thanks to Yasushi Masuda)
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
Change level and experience to regular integers.
module.exports = function(sequelize, DataTypes) { var User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true }, password: { type: DataTypes.STRING, allowNull: false }, email: { type: DataTypes.STRING, allowNull: false }, level: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 }, experience: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 } }, { classMethods: { associate: function(models) { User.hasMany(models.Quest, {as: 'OwnedQuests', foreignKey: 'OwnerId'}); User.belongsToMany(models.Quest, {through: 'UsersQuests'}); } }, instanceMethods: { /** * Experience formula taken from HabitRPG * http://habitrpg.wikia.com/wiki/Experience_Points */ getExperienceForLevel: function() { return Math.round((0.25 * Math.pow(this.level, 2) + 10 * this.level + 139.75) / 10) * 10; }, /** * Increase experience by `amount` XP. * Level up if necessary. */ increaseExperience: function(amount) { this.experience += amount; while (this.experience >= this.getExperienceForLevel()) { this.experience -= this.getExperienceForLevel(); this.level++; } this.save(); } } }); return User; };
module.exports = function(sequelize, DataTypes) { var User = sequelize.define('User', { username: { type: DataTypes.STRING, allowNull: false, unique: true }, password: { type: DataTypes.STRING, allowNull: false }, email: { type: DataTypes.STRING, allowNull: false }, level: { type: DataTypes.BIGINT, allowNull: false, defaultValue: 1 }, experience: { type: DataTypes.BIGINT, allowNull: false, defaultValue: 0 } }, { classMethods: { associate: function(models) { User.hasMany(models.Quest, {as: 'OwnedQuests', foreignKey: 'OwnerId'}); User.belongsToMany(models.Quest, {through: 'UsersQuests'}); } }, instanceMethods: { /** * Experience formula taken from HabitRPG * http://habitrpg.wikia.com/wiki/Experience_Points */ getExperienceForLevel: function() { return Math.round((0.25 * Math.pow(this.level, 2) + 10 * this.level + 139.75) / 10) * 10; }, /** * Increase experience by `amount` XP. * Level up if necessary. */ increaseExperience: function(amount) { this.experience += amount; while (this.experience >= this.getExperienceForLevel()) { this.experience -= this.getExperienceForLevel(); this.level++; } this.save(); } } }); return User; };
Put React lifecycle hooks on the prototype
import React from 'react'; import ReactDOM from 'react-dom'; /** * @param {ReactClass} Target The component that defines `onOutsideEvent` handler. * @param {String[]} supportedEvents A list of valid DOM event names. Default: ['mousedown']. * @return {ReactClass} */ export default (Target, supportedEvents = ['mousedown']) => { return class ReactOutsideEvent extends React.Component { componentDidMount() { if (!this.refs.target.onOutsideEvent) { throw new Error('Component does not define "onOutsideEvent" method.'); } supportedEvents.forEach((eventName) => { window.addEventListener(eventName, this.handleEvent, false); }); } componentWillUnmount() { supportedEvents.forEach((eventName) => { window.removeEventListener(eventName, this.handleEvent, false); }); } handleEvent = (event) => { let isInside, isOutside, target, targetElement; target = this.refs.target; targetElement = ReactDOM.findDOMNode(target); if (targetElement != undefined && !targetElement.contains(event.target)) { target.onOutsideEvent(event); } }; render() { return <Target ref='target' {... this.props} />; } }; };
import React from 'react'; import ReactDOM from 'react-dom'; /** * @param {ReactClass} Target The component that defines `onOutsideEvent` handler. * @param {String[]} supportedEvents A list of valid DOM event names. Default: ['mousedown']. * @return {ReactClass} */ export default (Target, supportedEvents = ['mousedown']) => { return class ReactOutsideEvent extends React.Component { componentDidMount = () => { if (!this.refs.target.onOutsideEvent) { throw new Error('Component does not define "onOutsideEvent" method.'); } supportedEvents.forEach((eventName) => { window.addEventListener(eventName, this.handleEvent, false); }); }; componentWillUnmount = () => { supportedEvents.forEach((eventName) => { window.removeEventListener(eventName, this.handleEvent, false); }); }; handleEvent = (event) => { let isInside, isOutside, target, targetElement; target = this.refs.target; targetElement = ReactDOM.findDOMNode(target); if (targetElement != undefined && !targetElement.contains(event.target)) { target.onOutsideEvent(event); } }; render() { return <Target ref='target' {... this.props} />; } }; };
Allow service provider to run from console
<?php namespace Watson\Breadcrumbs; use Illuminate\Support\ServiceProvider as BaseServiceProvider; class ServiceProvider extends BaseServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs'); $this->app->singleton('breadcrumbs', function ($app) { return $app->make(Manager::class); }); } /** * Perform post-registration booting of services. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'), ], 'config'); $this->publishes([ __DIR__.'/../views' => resource_path('views/vendor/breadcrumbs') ], 'views'); $this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs'); if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) { require $file; } } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['breadcrumbs']; } }
<?php namespace Watson\Breadcrumbs; use Illuminate\Support\ServiceProvider as BaseServiceProvider; class ServiceProvider extends BaseServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs'); $this->app->singleton('breadcrumbs', function ($app) { return $app->make(Manager::class); }); } /** * Perform post-registration booting of services. * * @return void */ public function boot() { if ($this->app->runningInConsole()) { // Can't generate breadcrumbs in the console as there is no route // from which we can build the trail from. return; } $this->publishes([ __DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'), ], 'config'); $this->publishes([ __DIR__.'/../views' => resource_path('views/vendor/breadcrumbs') ], 'views'); $this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs'); if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) { require $file; } } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['breadcrumbs']; } }
Order similar artist results properly
from django.db.models import Q import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] responses = SimilarResponse.objects.filter( normalized_name=artist.normalized_name) if responses.exists() and not force_update: return # Echo Nest similarities already added user = User.objects.get(email='echonest') artist_names = echonest.get_similar(artist.name) cc_artists = Artist.objects.filter(name__in=artist_names) for cc_artist in cc_artists: kwargs = dict( cc_artist=cc_artist, other_artist=artist, ) UserSimilarity.objects.get_or_create(defaults={'weight': 1}, user=user, **kwargs) similarities.append(Similarity.objects.get_or_create(**kwargs)[0]) update_similarities(similarities) def get_similar(name): artist, _ = GeneralArtist.objects.get_or_create( normalized_name=name.upper(), defaults={'name': name}) add_new_similarities(artist) similar = Q(similarity__other_artist=artist, similarity__weight__gt=0) return Artist.objects.filter(similar).order_by('-similarity__weight')
import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] responses = SimilarResponse.objects.filter( normalized_name=artist.normalized_name) if responses.exists() and not force_update: return # Echo Nest similarities already added user = User.objects.get(email='echonest') artist_names = echonest.get_similar(artist.name) cc_artists = Artist.objects.filter(name__in=artist_names) for cc_artist in cc_artists: kwargs = dict( cc_artist=cc_artist, other_artist=artist, ) UserSimilarity.objects.get_or_create(defaults={'weight': 1}, user=user, **kwargs) similarities.append(Similarity.objects.get_or_create(**kwargs)[0]) update_similarities(similarities) def get_similar(name): artist, _ = GeneralArtist.objects.get_or_create( normalized_name=name.upper(), defaults={'name': name}) add_new_similarities(artist) return Artist.objects.filter(similarity__other_artist=artist, similarity__weight__gt=0)
Use a non-locale aware output Otherwise, the alpha value will not be handled correctly i.e. in a German locale (this locale uses a comma instead of a dot).
<?php namespace OzdemirBurak\Iris\Traits; trait AlphaTrait { /** * @var double */ protected $alpha; /** * @param null $alpha * * @return $this|float */ public function alpha($alpha = null) { if ($alpha !== null) { $this->alpha = $alpha <= 1 ? $alpha : 1; return $this; } return $this->alpha; } /** * @return string */ protected function validationRules() { return '/^(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d\.\d{1,})$/'; } /** * @param $color * * @return string */ protected function fixPrecision($color) { if (strpos($color, ',') !== false) { $parts = explode(',', $color); $parts[3] = strpos($parts[3], '.') === false ? $parts[3] . '.0' : $parts[3]; $color = implode(',', $parts); } return $color; } /** * @param string $alpha * @return float */ protected function alphaHexToFloat(string $alpha): float { return sprintf('%0.2F', hexdec($alpha) / 255); } /** * @param float $alpha * @return string */ protected function alphaFloatToHex(float $alpha): string { return dechex($alpha * 255); } }
<?php namespace OzdemirBurak\Iris\Traits; trait AlphaTrait { /** * @var double */ protected $alpha; /** * @param null $alpha * * @return $this|float */ public function alpha($alpha = null) { if ($alpha !== null) { $this->alpha = $alpha <= 1 ? $alpha : 1; return $this; } return $this->alpha; } /** * @return string */ protected function validationRules() { return '/^(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d\.\d{1,})$/'; } /** * @param $color * * @return string */ protected function fixPrecision($color) { if (strpos($color, ',') !== false) { $parts = explode(',', $color); $parts[3] = strpos($parts[3], '.') === false ? $parts[3] . '.0' : $parts[3]; $color = implode(',', $parts); } return $color; } /** * @param string $alpha * @return float */ protected function alphaHexToFloat(string $alpha): float { return sprintf('%0.2f', hexdec($alpha) / 255); } /** * @param float $alpha * @return string */ protected function alphaFloatToHex(float $alpha): string { return dechex($alpha * 255); } }
Add rst long description for pypi
""" Copyright (c) 2010-2013, Anthony Garcia <[email protected]> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run the steamodd unit tests" user_options = [ ("key=", 'k', "Your API key") ] def initialize_options(self): self.key = None def finalize_options(self): if not self.key: raise DistutilsOptionError("API key is required") else: steam.api.key.set(self.key) def run(self): tests = TestLoader().discover("tests") TextTestRunner(verbosity = 2).run(tests) setup(name = "steamodd", version = steam.__version__, description = "High level Steam API implementation with low level reusable core", long_description = "Please see the `README <https://github.com/Lagg/steamodd/blob/master/README.md>`_ for a full description.", packages = ["steam"], author = steam.__author__, author_email = steam.__contact__, url = "https://github.com/Lagg/steamodd", classifiers = [ "License :: OSI Approved :: ISC License (ISCL)", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python" ], license = steam.__license__, cmdclass = {"run_tests": run_tests})
""" Copyright (c) 2010-2013, Anthony Garcia <[email protected]> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run the steamodd unit tests" user_options = [ ("key=", 'k', "Your API key") ] def initialize_options(self): self.key = None def finalize_options(self): if not self.key: raise DistutilsOptionError("API key is required") else: steam.api.key.set(self.key) def run(self): tests = TestLoader().discover("tests") TextTestRunner(verbosity = 2).run(tests) setup(name = "steamodd", version = steam.__version__, description = "High level Steam API implementation with low level reusable core", packages = ["steam"], author = steam.__author__, author_email = steam.__contact__, url = "https://github.com/Lagg/steamodd", classifiers = [ "License :: OSI Approved :: ISC License (ISCL)", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python" ], license = steam.__license__, cmdclass = {"run_tests": run_tests})
Include level, channel, and datetime in extra data sent to Rollbar.
<?php namespace Monolog\Handler; use RollbarNotifier; use Exception; /** * Sends errors to Rollbar * * @author Paul Statezny <[email protected]> */ class RollbarHandler extends AbstractProcessingHandler { /** * Rollbar notifier * * @var RollbarNotifier */ protected $rollbarNotifier; /** * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token * @param integer $level The minimum logging level at which this handler will be triggered * @param boolean $bubble Whether the messages that are handled can bubble up the stack or not */ public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true) { $this->rollbarNotifier = $rollbarNotifier; parent::__construct($level, $bubble); } /** * {@inheritdoc} */ protected function write(array $record) { if (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) { $this->rollbarNotifier->report_exception($record['context']['exception']); } else { $extraData = array( 'level' => $record['level'], 'channel' => $record['channel'], 'datetime' => $record['datetime'], ); $this->rollbarNotifier->report_message( $record['message'], $record['level_name'], array_merge($record['context'], $record['extra'], $extraData) ); } } /** * {@inheritdoc} */ public function close() { $this->rollbarNotifier->flush(); } }
<?php namespace Monolog\Handler; use RollbarNotifier; use Exception; /** * Sends errors to Rollbar * * @author Paul Statezny <[email protected]> */ class RollbarHandler extends AbstractProcessingHandler { /** * Rollbar notifier * * @var RollbarNotifier */ protected $rollbarNotifier; /** * @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token * @param integer $level The minimum logging level at which this handler will be triggered * @param boolean $bubble Whether the messages that are handled can bubble up the stack or not */ public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true) { $this->rollbarNotifier = $rollbarNotifier; parent::__construct($level, $bubble); } /** * {@inheritdoc} */ protected function write(array $record) { if (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) { $this->rollbarNotifier->report_exception($record['context']['exception']); } else { $this->rollbarNotifier->report_message( $record['message'], $record['level_name'], array_merge($record['context'], $record['extra']) ); } } /** * {@inheritdoc} */ public function close() { $this->rollbarNotifier->flush(); } }
Add the Windows compatibility for the processor counter
<?php namespace Liuggio\Fastest\Process; use Symfony\Component\Process\Process; /** * Number of processors seen by the OS and used for process scheduling. */ class ProcessorCounter { const PROC_DEFAULT_NUMBER = 4; const PROC_CPUINFO = '/proc/cpuinfo'; private static $count = null; private $procCPUInfo; public function __construct($procCPUInfo = self::PROC_CPUINFO) { $this->procCPUInfo = $procCPUInfo; } public function execute() { if (null !== self::$count) { return self::$count; } self::$count = $this->readFromProcCPUInfo(); return self::$count; } private function readFromProcCPUInfo() { if (PHP_OS === 'Darwin') { $processors = system('/usr/sbin/sysctl -n hw.physicalcpu'); if ($processors !== false && $processors) { return $processors; } } elseif (PHP_OS === 'Linux') { $file = $this->procCPUInfo; if (is_file($file) && is_readable($file)) { try { $contents = trim(file_get_contents($file)); return substr_count($contents, 'processor'); } catch (\Exception $e) { } } } elseif ('\\' === DIRECTORY_SEPARATOR) { $process = new Process('for /F "tokens=2 delims==" %C in (\'wmic cpu get NumberOfLogicalProcessors /value ^| findstr NumberOfLogicalProcessors\') do @echo %C'); $process->run(); if ($process->isSuccessful() && ($numProc = intval($process->getOutput())) > 0) { return $numProc; } } return self::PROC_DEFAULT_NUMBER; } }
<?php namespace Liuggio\Fastest\Process; /** * Number of processors seen by the OS and used for process scheduling. */ class ProcessorCounter { const PROC_DEFAULT_NUMBER = 4; const PROC_CPUINFO = '/proc/cpuinfo'; private static $count = null; private $procCPUInfo; public function __construct($procCPUInfo = self::PROC_CPUINFO) { $this->procCPUInfo = $procCPUInfo; } public function execute() { if (null !== self::$count) { return self::$count; } self::$count = $this->readFromProcCPUInfo(); return self::$count; } private function readFromProcCPUInfo() { if (PHP_OS === 'Darwin') { $processors = system('/usr/sbin/sysctl -n hw.physicalcpu'); if ($processors !== false && $processors) { return $processors; } } elseif (PHP_OS === 'Linux') { $file = $this->procCPUInfo; if (is_file($file) && is_readable($file)) { try { $contents = trim(file_get_contents($file)); return substr_count($contents, 'processor'); } catch (\Exception $e) { } } } return self::PROC_DEFAULT_NUMBER; } }
Make privacy checkbox on user form required via required attribute.
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField( required=True, widget=forms.CheckboxInput(attrs={'required': 'required'})) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
from django import forms from tower import ugettext_lazy as _lazy from flicks.base.util import country_choices from flicks.users.models import UserProfile class UserProfileForm(forms.ModelForm): # L10n: Used in a choice field where users can choose between receiving # L10n: HTML-based or Text-only newsletter emails. NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text'))) privacy_policy_agree = forms.BooleanField(required=True) mailing_list_signup = forms.BooleanField(required=False) mailing_list_format = forms.ChoiceField(required=False, choices=NEWSLETTER_FORMATS, initial='html') class Meta: model = UserProfile fields = ('full_name', 'nickname', 'country', 'address1', 'address2', 'city', 'mailing_country', 'state', 'postal_code') widgets = { 'full_name': forms.TextInput(attrs={'required': 'required'}), 'privacy_policy_agree': forms.CheckboxInput( attrs={'required': 'required'}), } def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) # Localize countries list self.fields['country'].choices = country_choices(allow_empty=False) self.fields['mailing_country'].choices = country_choices()
Add code in order to get the current user
<?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; } }
Create return the created object from mongodb
const ModelState = require('../model-state'); class BaseData { constructor(db, ModelClass, validator) { this.db = db; this.validator = validator; this.collectionName = ModelClass.name.toLowerCase() + 's'; this.collection = db.collection(this.collectionName); } getAll(filters) { if (filters) { return this.collection.find(filters).toArray(); } return this.collection.find().toArray(); } create(model) { const modelState = this.validate(model); if (!modelState.isValid) { return Promise.reject(modelState.errors); } return this.collection.insert(model) .then((status) => { // conatins the created Id return status.ops[0]; // return model; }); } /* findOrCreateBy(props) do we need this function ? https://github.com/TelerikAcademy/Web-Applications-with-Node.js/blob/master/Live-demos/project-structure/data/base/base.data.js */ updateById(model) { return this.collection.updateOne({ _id: model._id, }, model); } validate(model) { if (!this.validator || typeof this.validator.isValid !== 'function') { return ModelState.valid(); } return this.validator.isValid(model); } } module.exports = BaseData;
const ModelState = require('../model-state'); class BaseData { constructor(db, ModelClass, validator) { this.db = db; this.validator = validator; this.collectionName = ModelClass.name.toLowerCase() + 's'; this.collection = db.collection(this.collectionName); } getAll(filters) { if (filters) { return this.collection.find(filters).toArray(); } return this.collection.find().toArray(); } create(model) { const modelState = this.validate(model); if (!modelState.isValid) { return Promise.reject(modelState.errors); } return this.collection.insert(model) .then(() => { // TODO: refactor, parameters?, should return the whole model? return model; }); } /* findOrCreateBy(props) do we need this function ? https://github.com/TelerikAcademy/Web-Applications-with-Node.js/blob/master/Live-demos/project-structure/data/base/base.data.js */ updateById(model) { return this.collection.updateOne({ _id: model._id, }, model); } validate(model) { if (!this.validator || typeof this.validator.isValid !== 'function') { return ModelState.valid(); } return this.validator.isValid(model); } } module.exports = BaseData;
Move urlWithExtension to the global common Remove from content common as it overwrites the global common defined by the user
const config = { common: { outputDir: 'public', styles: [], scripts: [], urlWithExtension: false, }, template: { common: { path: 'templates', // Path where the templates are }, pug: { pretty: true, }, }, file: { html: {}, json: {}, markdown: {}, yaml: {}, }, asset: { active: [], common: { path: 'assets', // path to assets }, styles: { postcss: { plugins: { prod: [{ name: 'cssnano' }], dev: [], }, }, }, scripts: {}, fonts: {}, images: { minify: {}, }, }, content: { active: [], common: { path: 'content', // path to content htmlmin: { removeAttributeQuotes: true, collapseWhitespace: true, }, }, pages: {}, posts: { urlFormat: '_blog/${year}/${month}/${date}/', // eslint-disable-line }, }, decorator: { active: [], common: {}, sitemap: {}, tags: {}, pagination: {}, }, }; module.exports = config;
const config = { common: { outputDir: 'public', styles: [], scripts: [], }, template: { common: { path: 'templates', // Path where the templates are }, pug: { pretty: true, }, }, file: { html: {}, json: {}, markdown: {}, yaml: {}, }, asset: { active: [], common: { path: 'assets', // path to assets }, styles: { postcss: { plugins: { prod: [{ name: 'cssnano' }], dev: [], }, }, }, scripts: {}, fonts: {}, images: { minify: {}, }, }, content: { active: [], common: { path: 'content', // path to content urlWithExtension: false, htmlmin: { removeAttributeQuotes: true, collapseWhitespace: true, }, }, pages: {}, posts: { urlFormat: '_blog/${year}/${month}/${date}/', // eslint-disable-line }, }, decorator: { active: [], common: {}, sitemap: {}, tags: {}, pagination: {}, }, }; module.exports = config;
Stop stripping out the Server header from response from origins. Should overwrite this in a zuul filter if we don't want to use the Server header from origin, rather than removing it by default.
package com.netflix.zuul.util; import com.netflix.client.http.HttpResponse; import com.netflix.zuul.message.http.HttpRequestMessage; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * User: [email protected] * Date: 6/8/15 * Time: 11:50 AM */ public class ProxyUtils { public static boolean isValidRequestHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "content-length": case "transfer-encoding": return false; default: return true; } } public static boolean isValidResponseHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "keep-alive": case "content-length": case "transfer-encoding": return false; default: return true; } } @RunWith(MockitoJUnitRunner.class) public static class TestUnit { @Mock HttpResponse proxyResp; @Mock HttpRequestMessage request; @Test public void testIsValidResponseHeader() { Assert.assertTrue(isValidResponseHeader("test")); Assert.assertFalse(isValidResponseHeader("content-length")); Assert.assertFalse(isValidResponseHeader("connection")); } } }
package com.netflix.zuul.util; import com.netflix.client.http.HttpResponse; import com.netflix.zuul.message.http.HttpRequestMessage; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * User: [email protected] * Date: 6/8/15 * Time: 11:50 AM */ public class ProxyUtils { public static boolean isValidRequestHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "content-length": case "transfer-encoding": return false; default: return true; } } public static boolean isValidResponseHeader(String headerName) { switch (headerName.toLowerCase()) { case "connection": case "keep-alive": case "content-length": case "server": case "transfer-encoding": return false; default: return true; } } @RunWith(MockitoJUnitRunner.class) public static class TestUnit { @Mock HttpResponse proxyResp; @Mock HttpRequestMessage request; @Test public void testIsValidResponseHeader() { Assert.assertTrue(isValidResponseHeader("test")); Assert.assertFalse(isValidResponseHeader("content-length")); Assert.assertFalse(isValidResponseHeader("connection")); } } }
README.md exists but content is empty.
Downloads last month
32