text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Adjust FIJI script for applying CLAHE to a directory
#!/usr/bin/env jython from ij import IJ import os from mpicbg.ij.clahe import Flat from ij.process import ImageConverter # http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE) # http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD dir = "/usr/people/tmacrina/seungmount/research/Julimaps/datasets/AIBS_pilot_v1/0_raw/" blocksize = 63 histogram_bins = 255 maximum_slope = 3 mask = "*None*" composite = False mask = None # files = os.listdir(dir) # files.sort() # for file in files: # if file.endswith(".tif") fn = os.path.join(dir, 'original.tif') imp = IJ.openImage(fn) output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif" imp = IJ.openImage(fn) Flat.getFastInstance().run( imp, blocksize, histogram_bins, maximum_slope, mask, composite ) ImageConverter(imp).convertToGray8() IJ.save(imp, output_fn)
#!/usr/bin/env jython from ij import IJ import os from mpicbg.ij.clahe import Flat from ij.process import ImageConverter # http://fiji.sc/wiki/index.php/Enhance_Local_Contrast_(CLAHE) # http://fiji.sc/cgi-bin/gitweb.cgi?p=mpicbg.git;a=blob;f=mpicbg/ij/clahe/PlugIn.java;h=663153764493547de560c08ee11f2e6b1e7e1a32;hb=HEAD dir = "/usr/people/tmacrina/Desktop/test/" blocksize = 50 histogram_bins = 128 maximum_slope = 3 mask = "*None*" composite = False mask = None files = os.listdir(dir) files.sort() for file in files: if file.endswith(".tif") fn = os.path.join(dir, file) imp = IJ.openImage(path) output_fn = os.path.splitext(fn)[0] + "_CLAHE_8bit.tif" imp = IJ.openImage(fn) Flat.getFastInstance().run( imp, blocksize, histogram_bins, maximum_slope, mask, composite ) ImageConverter(imp).convertToGray8() IJ.save(imp, output_fn)
Add support to define custom messages. Signed-off-by: crynobone <[email protected]>
<?php namespace Orchestra\Http; use Orchestra\Support\Traits\ValidationTrait; use Illuminate\Foundation\Http\FormRequest as Request; class FormRequest extends Request { use ValidationTrait; /** * Get validation rules. * * @return array */ public function getValidationRules() { return $this->container->call([$this, 'rules']); } /** * Get the validator instance for the request. * * @return \Illuminate\Validation\Validator */ protected function getValidatorInstance() { $this->setupValidationScenario(); $this->setupValidationParameters(); $this->validationFactory = $this->container->make('Illuminate\Contracts\Validation\Factory'); $this->validationDispatcher = $this->container->make('Illuminate\Contracts\Events\Dispatcher'); return $this->runValidation($this->all(), [], $this->messages()); } /** * Setup validation scenario based on request method. * * @return void */ protected function setupValidationScenario() { $current = $this->method(); $available = [ 'POST' => 'store', 'PUT' => 'update', 'DELETE' => 'destroy', ]; if (in_array($current, $available)) { $this->onValidationScenario($available[$current]); } } /** * Setup validation scenario based on request method. * * @return void */ protected function setupValidationParameters() { $parameters = $this->route()->parametersWithoutNulls(); $this->bindToValidation($parameters); } }
<?php namespace Orchestra\Http; use Orchestra\Support\Traits\ValidationTrait; use Illuminate\Foundation\Http\FormRequest as Request; class FormRequest extends Request { use ValidationTrait; /** * Get validation rules. * * @return array */ public function getValidationRules() { return $this->container->call([$this, 'rules']); } /** * Get the validator instance for the request. * * @return \Illuminate\Validation\Validator */ protected function getValidatorInstance() { $this->setupValidationScenario(); $this->setupValidationParameters(); $this->validationFactory = $this->container->make('Illuminate\Contracts\Validation\Factory'); $this->validationDispatcher = $this->container->make('Illuminate\Contracts\Events\Dispatcher'); return $this->runValidation($this->all()); } /** * Setup validation scenario based on request method. * * @return void */ protected function setupValidationScenario() { $current = $this->method(); $available = [ 'POST' => 'store', 'PUT' => 'update', 'DELETE' => 'destroy', ]; if (in_array($current, $available)) { $this->onValidationScenario($available[$current]); } } /** * Setup validation scenario based on request method. * * @return void */ protected function setupValidationParameters() { $parameters = $this->route()->parametersWithoutNulls(); $this->bindToValidation($parameters); } }
Change "Sklearn" to "Scikit-learn" in error message
""" Machine Learning module for NeuroImaging in python ================================================== See http://nisl.github.com for complete documentation. """ """ try: import numpy except ImportError: print 'Numpy could not be found, please install it properly to use nisl.' try: import scipy except ImportError: print 'Scipy could not be found, please install it properly to use nisl.' try: import sklearn except ImportError: print 'Scikit-learn could not be found, please install it properly to use nisl.' """ try: from numpy.testing import nosetester class NoseTester(nosetester.NoseTester): """ Subclass numpy's NoseTester to add doctests by default """ def test(self, label='fast', verbose=1, extra_argv=['--exe'], doctests=True, coverage=False): """Run the full test suite Examples -------- This will run the test suite and stop at the first failing example >>> from nisl import test >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP """ return super(NoseTester, self).test(label=label, verbose=verbose, extra_argv=extra_argv, doctests=doctests, coverage=coverage) test = NoseTester().test del nosetester except: pass __all__ = ['datasets'] __version__ = '2010'
""" Machine Learning module for NeuroImaging in python ================================================== See http://nisl.github.com for complete documentation. """ """ try: import numpy except ImportError: print 'Numpy could not be found, please install it properly to use nisl.' try: import scipy except ImportError: print 'Scipy could not be found, please install it properly to use nisl.' try: import sklearn except ImportError: print 'Sklearn could not be found, please install it properly to use nisl.' """ try: from numpy.testing import nosetester class NoseTester(nosetester.NoseTester): """ Subclass numpy's NoseTester to add doctests by default """ def test(self, label='fast', verbose=1, extra_argv=['--exe'], doctests=True, coverage=False): """Run the full test suite Examples -------- This will run the test suite and stop at the first failing example >>> from nisl import test >>> test(extra_argv=['--exe', '-sx']) #doctest: +SKIP """ return super(NoseTester, self).test(label=label, verbose=verbose, extra_argv=extra_argv, doctests=doctests, coverage=coverage) test = NoseTester().test del nosetester except: pass __all__ = ['datasets'] __version__ = '2010'
Use available base command service provider. Signed-off-by: crynobone <[email protected]>
<?php namespace Orchestra\View; use Orchestra\View\Console\DetectCommand; use Orchestra\View\Console\ActivateCommand; use Orchestra\View\Console\OptimizeCommand; use Orchestra\Support\Providers\CommandServiceProvider as ServiceProvider; class CommandServiceProvider extends ServiceProvider { /** * The commands to be registered. * * @var array */ protected $commands = [ 'Activate' => 'orchestra.view.command.activate', 'Detect' => 'orchestra.view.command.detect', 'Optimize' => 'orchestra.view.command.optimize' ]; /** * Register the service provider. * * @return void */ public function registerActivateCommand() { $this->app->singleton('orchestra.view.command.activate', function ($app) { $finder = $app['orchestra.theme.finder']; return new ActivateCommand($finder); }); } /** * Register the service provider. * * @return void */ public function registerDetectCommand() { $this->app->singleton('orchestra.view.command.detect', function ($app) { $finder = $app['orchestra.theme.finder']; return new DetectCommand($finder); }); } /** * Register the service provider. * * @return void */ public function registerOptimizeCommand() { $this->app->singleton('orchestra.view.command.optimize', function () { return new OptimizeCommand(); }); } }
<?php namespace Orchestra\View; use Illuminate\Support\ServiceProvider; use Orchestra\View\Console\DetectCommand; use Orchestra\View\Console\ActivateCommand; use Orchestra\View\Console\OptimizeCommand; class CommandServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('orchestra.view.command.activate', function ($app) { $finder = $app['orchestra.theme.finder']; return new ActivateCommand($finder); }); $this->app->singleton('orchestra.view.command.detect', function ($app) { $finder = $app['orchestra.theme.finder']; return new DetectCommand($finder); }); $this->app->singleton('orchestra.view.command.optimize', function () { return new OptimizeCommand(); }); $this->commands([ 'orchestra.view.command.activate', 'orchestra.view.command.detect', 'orchestra.view.command.optimize', ]); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return [ 'orchestra.view.command.activate', 'orchestra.view.command.detect', 'orchestra.view.command.optimize', ]; } }
Remove name unique constraint, move to email
const bcrypt = require('bcrypt') module.exports = function (sequelize, DataTypes) { const User = sequelize.define('User', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, name: { type: DataTypes.STRING, allowNull: false, validate: { max: 255, notEmpty: true } }, email: { unique: true, type: DataTypes.STRING, allowNull: false, validate: { isEmail: true }, roles: false }, hashedPassword: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true }, roles: false } }, { classMethods: { associate (models) { User.hasMany(models.Bikeshed) User.hasMany(models.Vote) }, hashPassword (password) { return new Promise((resolve, reject) => { bcrypt.hash(password, 8, (err, hash) => { err ? reject(err) : resolve(hash) }) }) }, comparePassword (password, hash) { return new Promise((resolve, reject) => { bcrypt.compare(password, hash, (err, res) => { err ? reject(err) : resolve(res) }) }) } } }) return User }
const bcrypt = require('bcrypt') module.exports = function (sequelize, DataTypes) { const User = sequelize.define('User', { id: { primaryKey: true, type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4 }, name: { unique: true, type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } }, email: { type: DataTypes.STRING, allowNull: false, validate: { isEmail: true }, roles: false }, hashedPassword: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true }, roles: false } }, { classMethods: { associate (models) { User.hasMany(models.Bikeshed) User.hasMany(models.Vote) }, hashPassword (password) { return new Promise((resolve, reject) => { bcrypt.hash(password, 8, (err, hash) => { err ? reject(err) : resolve(hash) }) }) }, comparePassword (password, hash) { return new Promise((resolve, reject) => { bcrypt.compare(password, hash, (err, res) => { err ? reject(err) : resolve(res) }) }) } } }) return User }
Sort for testing. Fix for test failures introduced in r3557. git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@3563 0d517254-b314-0410-acde-c619094fa49f
package edu.northwestern.bioinformatics.studycalendar.dao.reporting; import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao; import gov.nih.nci.cabig.ctms.domain.DomainObject; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.springframework.orm.hibernate3.HibernateCallback; import java.util.Collections; import java.util.List; /** * @author John Dzak */ public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> { @SuppressWarnings("unchecked") public List<R> search(final F filters) { return getHibernateTemplate().executeFind(new HibernateCallback() { @SuppressWarnings("unchecked") public Object doInHibernate(Session session) throws HibernateException { if (filters.isEmpty()) { logger.debug("No filters selected, skipping search: " + filters); return Collections.emptyList(); } else { Criteria criteria = session.createCriteria(domainClass()).addOrder(Order.asc("id")); filters.apply(session); return (List<R>) criteria.list(); } } }); } }
package edu.northwestern.bioinformatics.studycalendar.dao.reporting; import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao; import gov.nih.nci.cabig.ctms.domain.DomainObject; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.orm.hibernate3.HibernateCallback; import java.util.Collections; import java.util.List; /** * @author John Dzak */ public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> { @SuppressWarnings("unchecked") public List<R> search(final F filters) { return getHibernateTemplate().executeFind(new HibernateCallback() { @SuppressWarnings("unchecked") public Object doInHibernate(Session session) throws HibernateException { if (filters.isEmpty()) { logger.debug("No filters selected, skipping search: " + filters); return Collections.emptyList(); } else { Criteria criteria = session.createCriteria(domainClass()); filters.apply(session); return (List<R>) criteria.list(); } } }); } }
Add JS for close alerts
;(function($) { $(function(){ /*! -- @ Close alerts @ -- */ $('.alert .close').on('click',function(e){ e.preventDefault(); $(this).parent().fadeOut(500,function(){ $(this).remove(); }); }); /*! -- @ Modals @ -- */ /* Open modal */ $('button.modal-open').on('click',function(e){ e.preventDefault(); var modal = $(this).data('target'); if($('#'+modal).length) { $('body').addClass('opened-modal'); $('#'+modal).addClass('active'); } else { alert('ChuckCSS error : modal with attribute id="'+modal+'" is not defined!'); } }); /* Close modal */ $('.modal:not([data-disabled-overlay])') .find('.modal-overlay') .add('.modal .modal-close') .on('click',function(e) { if($(this).parent().hasClass('active')) $(this).parent().removeClass('active'); if(!$('.modal.active').length) $('body').removeClass('opened-modal'); }); }); })(jQuery);
;(function($) { /* @name : checkRadio @function : check or uncheck checkbox & radio inputs @params : no params */ function checkRadio() { if($('input[type="radio"], input[type="checkbox"]').length) { $('input[type="radio"], input[type="checkbox"]').each(function(i,el){ if($(this).is(':checked')) $(this).parent().addClass('checked'); // add .checked class to <label> else $(this).parent().removeClass('checked'); // remove .checked class to <label> }); } } $(function(){ /*! -- @ CHECK RADIO && CHECKBOX INPUTS @ -- */ if($('input[type="radio"], input[type="checkbox"]').length) { /* DOM ready : Check radio if already checked */ checkRadio(); $('input[type="radio"], input[type="checkbox"]').on('click',function(e){ checkRadio(); }); } /*! -- @ Close alerts @ -- */ $('.alert .close').on('click',function(e){ e.preventDefault(); $(this).parent().fadeOut(500,function(){ $(this).remove(); }); }); /*! -- @ Modals @ -- */ /* Open modal */ $('button.modal-open').on('click',function(e){ e.preventDefault(); var modal = $(this).data('target'); if($('#'+modal).length) { $('body').addClass('opened-modal'); $('#'+modal).addClass('active'); } else { alert('ChuckCSS error : modal with attribute id="'+modal+'" is not defined!'); } }); /* Close modal */ $('.modal:not([data-disabled-overlay])') .find('.modal-overlay') .add('.modal .modal-close') .on('click',function(e) { if($(this).parent().hasClass('active')) $(this).parent().removeClass('active'); if(!$('.modal.active').length) $('body').removeClass('opened-modal'); }); }); })(jQuery);
Add defaults to guild type playlist settings
package com.avairebot.orion.database.transformers; import com.avairebot.orion.contracts.database.transformers.Transformer; import com.avairebot.orion.database.collection.DataRow; import com.google.gson.Gson; public class GuildTypeTransformer extends Transformer { private static final Gson GSON = new Gson(); private String name = "Default"; private GuildTypeLimits limits = new GuildTypeLimits(); GuildTypeTransformer(DataRow data) { super(data); if (hasData()) { if (data.getString("type_name", null) != null) { name = data.getString("type_name"); } if (data.getString("type_limits", null) != null) { GuildTypeLimits typeLimits = GSON.fromJson(data.getString("type_limits"), GuildTypeLimits.class); if (typeLimits != null) { limits = typeLimits; } } } } public String getName() { return name; } public GuildTypeLimits getLimits() { return limits; } public class GuildTypeLimits { private GuildTypePlaylist playlist = new GuildTypePlaylist(); private int aliases = 20; public int getAliases() { return aliases; } public GuildTypePlaylist getPlaylist() { return playlist; } public class GuildTypePlaylist { private int lists = 5; private int songs = 30; public int getPlaylists() { return lists; } public int getSongs() { return songs; } } } }
package com.avairebot.orion.database.transformers; import com.avairebot.orion.contracts.database.transformers.Transformer; import com.avairebot.orion.database.collection.DataRow; import com.google.gson.Gson; public class GuildTypeTransformer extends Transformer { private static final Gson GSON = new Gson(); private String name = "Default"; private GuildTypeLimits limits = new GuildTypeLimits(); GuildTypeTransformer(DataRow data) { super(data); if (hasData()) { if (data.getString("type_name", null) != null) { name = data.getString("type_name"); } if (data.getString("type_limits", null) != null) { GuildTypeLimits typeLimits = GSON.fromJson(data.getString("type_limits"), GuildTypeLimits.class); if (typeLimits != null) { limits = typeLimits; } } } } public String getName() { return name; } public GuildTypeLimits getLimits() { return limits; } public class GuildTypeLimits { private GuildTypePlaylist playlist = new GuildTypePlaylist(); private int aliases = 20; public int getAliases() { return aliases; } public GuildTypePlaylist getPlaylist() { return playlist; } public class GuildTypePlaylist { private int lists; private int songs; public int getPlaylists() { return lists; } public int getSongs() { return songs; } } } }
Fix UI filters on Feature Flags page
hqDefine('toggle_ui/js/flags', [ 'jquery', 'knockout', 'reports/js/config.dataTables.bootstrap', 'hqwebapp/js/components.ko', // select toggle widget ], function ( $, ko, datatablesConfig ) { var dataTableElem = '.datatable'; var viewModel = { tagFilter: ko.observable(null), }; $.fn.dataTableExt.afnFiltering.push( function (oSettings, aData, iDataIndex) { if (viewModel.tagFilter() === 'all') { return true; } var tag = aData[0].replace(/\s+/g," ").replace(/<.*?>/g, "").replace(/^\d+ /, ""); if (viewModel.tagFilter() === "Solutions" && tag.includes("Solutions")) { return true; } return tag === viewModel.tagFilter(); } ); $('#table-filters').koApplyBindings(viewModel); var table = datatablesConfig.HQReportDataTables({ dataTableElem: dataTableElem, showAllRowsOption: true, includeFilter: true, }); table.render(); viewModel.tagFilter.subscribe(function (value) { table.datatable.fnDraw(); }); });
hqDefine('toggle_ui/js/flags', [ 'jquery', 'knockout', 'reports/js/config.dataTables.bootstrap', 'hqwebapp/js/components.ko', // select toggle widget ], function ( $, ko, datatablesConfig ) { var dataTableElem = '.datatable'; var viewModel = { tagFilter: ko.observable(null), }; $.fn.dataTableExt.afnFiltering.push( function (oSettings, aData, iDataIndex) { if (viewModel.tagFilter() === 'all') { return true; } var tag = aData[0].replace(/\n/g," ").replace(/<.*?>/g, ""); if (viewModel.tagFilter() === "Solutions" && tag.includes("Solutions")) { return true; } return tag === viewModel.tagFilter(); } ); $('#table-filters').koApplyBindings(viewModel); var table = datatablesConfig.HQReportDataTables({ dataTableElem: dataTableElem, showAllRowsOption: true, includeFilter: true, }); table.render(); viewModel.tagFilter.subscribe(function (value) { table.datatable.fnDraw(); }); });
Add conditional PDO statement for sqlsrv Add conditional check for PDO driver and added an edited PDO statement to address limit issue with sqlsrv PDO driver .
<?php /* * This file is part of Slim HTTP Basic Authentication middleware * * Copyright (c) 2013-2014 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-basic-auth * */ namespace Slim\Middleware\HttpBasicAuthentication; class PdoAuthenticator implements AuthenticatorInterface { private $options; public function __construct(array $options = array()) { /* Default options. */ $this->options = array( "table" => "users", "user" => "user", "hash" => "hash" ); if ($options) { $this->options = array_merge($this->options, $options); } } public function authenticate($user, $pass) { if($this->options["pdo"]->getAttribute(\PDO::ATTR_DRIVER_NAME) === "sqlsrv"){ $statement = $this->options["pdo"]->prepare( "SELECT top 1 * FROM {$this->options['table']} WHERE {$this->options['user']} = ?" ); }else{ $statement = $this->options["pdo"]->prepare( "SELECT * FROM {$this->options['table']} WHERE {$this->options['user']} = ? LIMIT 1" ); } $statement->execute(array($user)); if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) { return password_verify($pass, $user[$this->options["hash"]]); } return false; } }
<?php /* * This file is part of Slim HTTP Basic Authentication middleware * * Copyright (c) 2013-2014 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * https://github.com/tuupola/slim-basic-auth * */ namespace Slim\Middleware\HttpBasicAuthentication; class PdoAuthenticator implements AuthenticatorInterface { private $options; public function __construct(array $options = array()) { /* Default options. */ $this->options = array( "table" => "users", "user" => "user", "hash" => "hash" ); if ($options) { $this->options = array_merge($this->options, $options); } } public function authenticate($user, $pass) { $statement = $this->options["pdo"]->prepare( "SELECT * FROM {$this->options['table']} WHERE {$this->options['user']} = ? LIMIT 1" ); $statement->execute(array($user)); if ($user = $statement->fetch(\PDO::FETCH_ASSOC)) { return password_verify($pass, $user[$this->options["hash"]]); } return false; } }
Make calendar not editbale for actors
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered'), editable=False ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened'), editable=False ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True, editable=False) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
from django.utils.translation import ugettext_lazy as _ from django.db import models from django.db.models import DateTimeField, BooleanField, OneToOneField from agenda.models import Calendar class Actor(models.Model): """ An actor is an entity playing a role in your system. It can be anything that belongs to a user and interact during its workflow. """ class meta: abstract = True registered_on = DateTimeField(auto_now_add=True, help_text=_('When it was was registered') ) last_activity = DateTimeField(auto_now=True, help_text=_('The last time something happened') ) owned = BooleanField(default=False, help_text=_('Wether this actor is owned by at least one user') ) calendar = OneToOneField(Calendar, null=True, blank=True) def actor_after_save(sender, instance, created, **kwargs): """ Called to ensure the calendar is created for a given actor """ if created: print "eyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" cal = Calendar(name='%s' % instance.name) cal.save() instance.calendar = cal instance.save()
Quit with error code when log('throw') is called
var colors = require('colors'); var CargoLog = function () { var scope = this; this.verbose = false; return function (cargo) { scope.cargo = cargo; return scope.log; }; }; /** * Log to the console * @return null */ CargoLog.prototype.log = function () { var args = Array.prototype.slice.call(arguments); var color = 'blue'; if (['log', 'error', 'throw'].indexOf(args[0]) != -1) { var type = args.shift(); switch (type) { case 'error': color = 'yellow'; break; case 'throw': color = 'red'; break; } } args.unshift(colors[color]('[cargo]')); // if (this.verbose) console.log.apply(this, args); if (type && type == 'throw') { process.exit(1); } }; /** * Log an error to the console * @return null */ CargoLog.prototype.error = function () { var text = Array.prototype.slice.call(arguments); text.unshift('error'); this.log.apply(this, text); }; /** * Throw an error with the given message and halt execution * @return null */ CargoLog.prototype.throw = function () { var text = Array.prototype.slice.call(arguments); text.unshift('throw'); this.log.apply(this, text); process.exit(1); }; module.exports = new CargoLog;
var colors = require('colors'); var CargoLog = function () { var scope = this; this.verbose = false; return function (cargo) { scope.cargo = cargo; return scope.log; }; }; /** * Log to the console * @return null */ CargoLog.prototype.log = function () { var args = Array.prototype.slice.call(arguments); var color = 'blue'; if (['log', 'error', 'throw'].indexOf(args[0]) != -1) { var type = args.shift(); switch (type) { case 'error': color = 'yellow'; break; case 'throw': color = 'red'; break; } } args.unshift(colors[color]('[cargo]')); // if (this.verbose) console.log.apply(this, args); }; /** * Log an error to the console * @return null */ CargoLog.prototype.error = function () { var text = Array.prototype.slice.call(arguments); text.unshift('error'); this.log.apply(this, text); }; /** * Throw an error with the given message and halt execution * @return null */ CargoLog.prototype.throw = function () { var text = Array.prototype.slice.call(arguments); text.unshift('throw'); this.log.apply(this, text); process.exit(1); }; module.exports = new CargoLog;
Add comma after array item
<?php namespace Hackzilla\Bundle\TicketBundle\TwigExtension; use Symfony\Component\DependencyInjection\ContainerInterface; class TicketGlobalExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface { /** * @var \Symfony\Component\DependencyInjection\ContainerInterface */ protected $container; /** * @param \Symfony\Component\DependencyInjection\ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * @return array */ public function getGlobals() { return [ 'hackzilla_ticket' => [ 'templates' => [ 'index' => $this->container->getParameter('hackzilla_ticket.templates.index'), 'new' => $this->container->getParameter('hackzilla_ticket.templates.new'), 'show' => $this->container->getParameter('hackzilla_ticket.templates.show'), 'show_attachment' => $this->container->getParameter('hackzilla_ticket.templates.show_attachment'), 'prototype' => $this->container->getParameter('hackzilla_ticket.templates.prototype'), 'macros' => $this->container->getParameter('hackzilla_ticket.templates.macros'), ], ], ]; } /** * @return string */ public function getName() { return 'ticketGlobal'; } }
<?php namespace Hackzilla\Bundle\TicketBundle\TwigExtension; use Symfony\Component\DependencyInjection\ContainerInterface; class TicketGlobalExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface { /** * @var \Symfony\Component\DependencyInjection\ContainerInterface */ protected $container; /** * @param \Symfony\Component\DependencyInjection\ContainerInterface $container */ public function __construct(ContainerInterface $container) { $this->container = $container; } /** * @return array */ public function getGlobals() { return [ 'hackzilla_ticket' => [ 'templates' => [ 'index' => $this->container->getParameter('hackzilla_ticket.templates.index'), 'new' => $this->container->getParameter('hackzilla_ticket.templates.new'), 'show' => $this->container->getParameter('hackzilla_ticket.templates.show'), 'show_attachment' => $this->container->getParameter('hackzilla_ticket.templates.show_attachment'), 'prototype' => $this->container->getParameter('hackzilla_ticket.templates.prototype'), 'macros' => $this->container->getParameter('hackzilla_ticket.templates.macros'), ], ] ]; } /** * @return string */ public function getName() { return 'ticketGlobal'; } }
Add build as available environment
"""Create IAM Instance Profiles, Roles, Users, and Groups.""" import argparse import logging from .create_iam import create_iam_resources LOG = logging.getLogger(__name__) def main(): """Command to create IAM Instance Profiles, Roles, Users, and Groups.""" logging.basicConfig() parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument('-d', '--debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='Set DEBUG output') parser.add_argument('-e', '--env', choices=('build', 'dev', 'stage', 'prod'), default='dev', help='Deploy environment') parser.add_argument('-a', '--app', default='testapp', help='Spinnaker Application name') args = parser.parse_args() LOG.setLevel(args.debug) logging.getLogger(__package__).setLevel(args.debug) vars(args).pop('debug') assert create_iam_resources(env=args.env, app=args.app) if __name__ == '__main__': main()
"""Create IAM Instance Profiles, Roles, Users, and Groups.""" import argparse import logging from .create_iam import create_iam_resources LOG = logging.getLogger(__name__) def main(): """Command to create IAM Instance Profiles, Roles, Users, and Groups.""" logging.basicConfig() parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument('-d', '--debug', action='store_const', const=logging.DEBUG, default=logging.INFO, help='Set DEBUG output') parser.add_argument('-e', '--env', choices=('dev', 'stage', 'prod'), default='dev', help='Deploy environment') parser.add_argument('-a', '--app', default='testapp', help='Spinnaker Application name') args = parser.parse_args() LOG.setLevel(args.debug) logging.getLogger(__package__).setLevel(args.debug) vars(args).pop('debug') assert create_iam_resources(env=args.env, app=args.app) if __name__ == '__main__': main()
Fix title comment on Italian locale js
/** * Italian translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["it-IT"] = { font_styles: { normal: "Testo normale", h1: "Titolo 1", h2: "Titolo 2" }, emphasis: { bold: "Grassetto", italic: "Corsivo", underline: "Sottolineato" }, lists: { unordered: "Lista non ordinata", ordered: "Lista ordinata", outdent: "Elimina rientro", indent: "Aggiungi rientro" }, link: { insert: "Inserisci link", cancel: "Annulla" }, image: { insert: "Inserisci immagine", cancel: "Annulla" }, html: { edit: "Modifica HTML" }, colours: { black: "Nero", silver: "Argento", gray: "Grigio", maroon: "Marrone", red: "Rosso", purple: "Viola", green: "Verde", olive: "Oliva", navy: "Blu Marino", blue: "Blu", orange: "Arancio" } }; }(jQuery));
/** * Uruguayan spanish translation for bootstrap-wysihtml5 */ (function($){ $.fn.wysihtml5.locale["it-IT"] = { font_styles: { normal: "Testo normale", h1: "Titolo 1", h2: "Titolo 2" }, emphasis: { bold: "Grassetto", italic: "Corsivo", underline: "Sottolineato" }, lists: { unordered: "Lista non ordinata", ordered: "Lista ordinata", outdent: "Elimina rientro", indent: "Aggiungi rientro" }, link: { insert: "Inserisci link", cancel: "Annulla" }, image: { insert: "Inserisci immagine", cancel: "Annulla" }, html: { edit: "Modifica HTML" }, colours: { black: "Nero", silver: "Argento", gray: "Grigio", maroon: "Marrone", red: "Rosso", purple: "Viola", green: "Verde", olive: "Oliva", navy: "Blu Marino", blue: "Blu", orange: "Arancio" } }; }(jQuery));
Add a logging statement in TimestampProvider
package com.thinkaurelius.titan.diskstorage.util; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractTimestampProvider implements TimestampProvider { private static final Logger log = LoggerFactory.getLogger(AbstractTimestampProvider.class); @Override public long sleepUntil(final long time, final TimeUnit unit, final Logger log) throws InterruptedException { // All long variables are times in parameter unit long now; while ((now = unit.convert(getTime(), getUnit())) <= time) { final long delta = time - now; /* * TimeUnit#sleep(long) internally preserves the nanoseconds parts * of the argument, if applicable, and passes both milliseconds and * nanoseconds parts into Thread#sleep(long, long) */ if (log.isDebugEnabled()) { log.debug("Sleeping: now={} targettime={} delta={} (unit={})", new Object[] { now, time, delta, unit }); } unit.sleep(delta); } return now; } @Override public long sleepUntil(final long time, final TimeUnit unit) throws InterruptedException { return sleepUntil(time, unit, log); } @Override public String toString() { return "TimestampProvider[" + getUnit() + "]"; } }
package com.thinkaurelius.titan.diskstorage.util; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractTimestampProvider implements TimestampProvider { private static final Logger log = LoggerFactory.getLogger(AbstractTimestampProvider.class); @Override public long sleepUntil(final long time, final TimeUnit unit, final Logger log) throws InterruptedException { // All long variables are times in parameter unit long now; while ((now = unit.convert(getTime(), getUnit())) <= time) { final long delta = time - now; /* * TimeUnit#sleep(long) internally preserves the nanoseconds parts * of the argument, if applicable, and passes both milliseconds and * nanoseconds parts into Thread#sleep(long, long) */ // if (log.isDebugEnabled()) { // log.error("Sleeping: now={} targettime={} delta={} (unit={})", // new Object[] { now, time, delta, unit }); // } unit.sleep(delta); } return now; } @Override public long sleepUntil(final long time, final TimeUnit unit) throws InterruptedException { return sleepUntil(time, unit, log); } @Override public String toString() { return "TimestampProvider[" + getUnit() + "]"; } }
Add exception for unregistred IDs
/** * Jatabase * * @author Gabriel Jacinto <[email protected]> * @license MIT License * @package jatabase */ 'use strict'; var utils = require('../utils'); module.exports = function (Model) { return function (where) { let db = require(Model.file), collection = db[Model.collection]; if (typeof where == 'object') { if (!utils.object.size(where)) { collection = []; } else { if (Model._validateFields(where)) { if (!collection.length) { return false; } let equals = []; for (let k in collection) { if (collection.hasOwnProperty(k)) { if (utils.object.propertiesEqualsTo(collection[k], where)) { equals.push(k); } } } let newCollection = []; for (let k in collection) { if (collection.hasOwnProperty(k)) { if (!utils.array.contains(equals, k)) { newCollection.push(collection[k]); } } } collection = newCollection; } } } else { let index; for (let k in collection) { if (collection[k].id == where) { index = k; } } if (typeof index === 'undefined') { throw Error('Record with ID "' + where + '" was not found'); } collection.splice(index, 1); } Model._saveModificationOnKey(Model.collection, collection); } };
/** * Jatabase * * @author Gabriel Jacinto <[email protected]> * @license MIT License * @package jatabase */ 'use strict'; var utils = require('../utils'); module.exports = function (Model) { return function (where) { let db = require(Model.file), collection = db[Model.collection]; if (typeof where == 'object') { if (!utils.object.size(where)) { collection = []; } else { if (Model._validateFields(where)) { if (!collection.length) { return false; } let equals = []; for (let k in collection) { if (collection.hasOwnProperty(k)) { if (utils.object.propertiesEqualsTo(collection[k], where)) { equals.push(k); } } } let newCollection = []; for (let k in collection) { if (collection.hasOwnProperty(k)) { if (!utils.array.contains(equals, k)) { newCollection.push(collection[k]); } } } collection = newCollection; } } } else { let index; for (let k in collection) { if (collection[k].id == where) { index = k; } } if (typeof index === 'undefined') { return false; } collection.splice(index, 1); } Model._saveModificationOnKey(Model.collection, collection); } };
Remove more SSL verification (ugh)
<?php namespace Scat\Service; class Ordure { public $url; public $key; public $static_url; public function __construct(Config $config) { $this->url= $config->get('ordure.url'); $this->key= $config->get('ordure.key'); $this->static_url= $config->get('ordure.static_url'); } public function markOrderShipped($sale_uuid) { $url= $this->url . '/sale/' . $sale_uuid . '/set-status'; $client= new \GuzzleHttp\Client(); $res= $client->request('POST', $url, [ 'verify' => false, # XXX no SSL verification 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', ], 'form_params' => [ 'key' => $this->key, 'status' => 'shipped' ] ]); // XXX do something with $res? } public function grabImage($url, $extra= []) { $client= new \GuzzleHttp\Client(); $res= $client->request('POST', $this->url . '/~grab-image', [ 'verify' => false, # XXX no SSL verification 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', ], 'form_params' => array_merge([ 'key' => $this->key, 'url' => $url, ], $extra) ]); return json_decode($res->getBody()); } }
<?php namespace Scat\Service; class Ordure { public $url; public $key; public $static_url; public function __construct(Config $config) { $this->url= $config->get('ordure.url'); $this->key= $config->get('ordure.key'); $this->static_url= $config->get('ordure.static_url'); } public function markOrderShipped($sale_uuid) { $url= $this->url . '/sale/' . $sale_uuid . '/set-status'; $client= new \GuzzleHttp\Client(); $res= $client->request('POST', $url, [ 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', ], 'form_params' => [ 'key' => $this->key, 'status' => 'shipped' ] ]); // XXX do something with $res? } public function grabImage($url, $extra= []) { $client= new \GuzzleHttp\Client(); $res= $client->request('POST', $this->url . '/~grab-image', [ 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest', ], 'form_params' => array_merge([ 'key' => $this->key, 'url' => $url, ], $extra) ]); return json_decode($res->getBody()); } }
Return name instead of unicode in autocomplete API
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': i.name, }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
import json from django.http import HttpResponse from django.views.generic import View from django.views.generic.detail import SingleObjectMixin from tx_highered.models import Institution class ApiView(View): def get(self, request, *args, **kwargs): data = self.get_content_data() content = json.dumps(data) return HttpResponse(content, content_type='application/json') class EnrollmentApiView(SingleObjectMixin, ApiView): model = Institution def get_content_data(self): self.object = self.get_object() race_data = [] for enrollment in self.object.enrollment.all(): race_data.extend(enrollment.race_data()) return race_data class ReportView(SingleObjectMixin, ApiView): model = Institution report_name = None def get_content_data(self): self.object = self.get_object() return_data = [] for obj in getattr(self.object, self.report_name).all(): return_data.append(obj.__json__()) return return_data class AutocompleteApiView(ApiView): def get_content_data(self): data = [] for i in Institution.objects.all(): data.append({ 'uri': i.get_absolute_url(), 'name': unicode(i), }) return data enrollment_api = EnrollmentApiView.as_view() autocomplete_api = AutocompleteApiView.as_view()
Fix IllegalStateException if we recreate Activities We do not need to unregister `WifiBroadcastReceiver` if some Activities still need to monitor Wi-Fi.
package cl.monsoon.s1next.widget; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; public final class AppActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { /** * Forked from http://stackoverflow.com/a/13809991 */ private int visibleCount; private WifiBroadcastReceiver mWifiBroadcastReceiver; private int mNeedMonitorWifiActivityCount; public AppActivityLifecycleCallbacks(Context context) { mWifiBroadcastReceiver = new WifiBroadcastReceiver(context); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {} @Override public void onActivityStarted(Activity activity) { visibleCount++; } @Override public void onActivityResumed(Activity activity) { if (activity instanceof WifiBroadcastReceiver.NeedMonitorWifi) { if (mNeedMonitorWifiActivityCount == 0) { mWifiBroadcastReceiver.registerIfNeeded(); } mNeedMonitorWifiActivityCount++; } } @Override public void onActivityPaused(Activity activity) { if (activity instanceof WifiBroadcastReceiver.NeedMonitorWifi) { mNeedMonitorWifiActivityCount--; if (mNeedMonitorWifiActivityCount == 0) { mWifiBroadcastReceiver.unregisterIfNeeded(); } } } @Override public void onActivityStopped(Activity activity) { visibleCount--; } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} @Override public void onActivityDestroyed(Activity activity) {} public boolean isAppVisible() { return visibleCount > 0; } }
package cl.monsoon.s1next.widget; import android.app.Activity; import android.app.Application; import android.content.Context; import android.os.Bundle; public final class AppActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { /** * Forked from http://stackoverflow.com/a/13809991 */ private int visibleCount; private WifiBroadcastReceiver mWifiBroadcastReceiver; public AppActivityLifecycleCallbacks(Context context) { mWifiBroadcastReceiver = new WifiBroadcastReceiver(context); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {} @Override public void onActivityStarted(Activity activity) { visibleCount++; } @Override public void onActivityResumed(Activity activity) { if (activity instanceof WifiBroadcastReceiver.NeedMonitorWifi) { mWifiBroadcastReceiver.registerIfNeeded(); } } @Override public void onActivityPaused(Activity activity) { if (activity instanceof WifiBroadcastReceiver.NeedMonitorWifi) { mWifiBroadcastReceiver.unregisterIfNeeded(); } } @Override public void onActivityStopped(Activity activity) { visibleCount--; } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {} @Override public void onActivityDestroyed(Activity activity) {} public boolean isAppVisible() { return visibleCount > 0; } }
Add bundles to the kernel
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
Use options resolver defaults instead of normalizer in form types.
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2016, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UserBundle\Form\Type\User; use Darvin\UserBundle\Entity\BaseUser; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * User entity form type */ class UserEntityType extends AbstractType { /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'class' => BaseUser::class, 'roles' => [], 'query_builder' => function (Options $options) { /** @var \Doctrine\ORM\EntityManager $em */ $em = $options['em']; /** @var \Darvin\UserBundle\Repository\UserRepository $repository */ $repository = $em->getRepository($options['class']); $roles = $options['roles']; return !empty($roles) ? $repository->getByRolesBuilder($roles) : $repository->getAllBuilder(); }, ]) ->setAllowedTypes('roles', 'array'); } /** * {@inheritdoc} */ public function getParent() { return EntityType::class; } }
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2016, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\UserBundle\Form\Type\User; use Darvin\UserBundle\Entity\BaseUser; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; /** * User entity form type */ class UserEntityType extends AbstractType { /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults([ 'class' => BaseUser::class, 'roles' => [], ]) ->setAllowedTypes('roles', 'array') ->setNormalizer('query_builder', function (Options $options) { /** @var \Doctrine\ORM\EntityManager $em */ $em = $options['em']; /** @var \Darvin\UserBundle\Repository\UserRepository $repository */ $repository = $em->getRepository($options['class']); $roles = $options['roles']; return !empty($roles) ? $repository->getByRolesBuilder($roles) : $repository->getAllBuilder(); }); } /** * {@inheritdoc} */ public function getParent() { return EntityType::class; } }
docs(project): Fix module docstring for url config
# pylint: disable=C0111 """All available endpoints of the chaospizza web project.""" from django.conf import settings from django.conf.urls import include, url # from django.conf.urls.static import static from django.contrib import admin from django.http import HttpResponse # from django.views.generic import TemplateView from django.views import defaults as default_views def home(request): """Django view which returns simple hello world text.""" print(request) return HttpResponse("hi") urlpatterns = [ url(r'^$', home), url(r'^admin/', admin.site.urls), url(r'^orders/', include('orders.urls')), url(r'^menus/', include('menus.urls')), ] if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
"""All available endpoints of the chaospizza web project.""" # pylint: disable=C0111 from django.conf import settings from django.conf.urls import include, url # from django.conf.urls.static import static from django.contrib import admin from django.http import HttpResponse # from django.views.generic import TemplateView from django.views import defaults as default_views def home(request): """Django view which returns simple hello world text.""" print(request) return HttpResponse("hi") urlpatterns = [ url(r'^$', home), url(r'^admin/', admin.site.urls), url(r'^orders/', include('orders.urls')), url(r'^menus/', include('menus.urls')), ] if settings.DEBUG: # This allows the error pages to be debugged during development, just visit # these url in browser to see how these error pages look like. urlpatterns += [ url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), url(r'^500/$', default_views.server_error), ] if 'debug_toolbar' in settings.INSTALLED_APPS: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
Change direct message warning to match upstream
import React from 'react'; import Motion from 'flavours/glitch/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { defineMessages, FormattedMessage } from 'react-intl'; // This is the spring used with our motion. const motionSpring = spring(1, { damping: 35, stiffness: 400 }); // Messages. const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be sent to all the mentioned users.', id: 'compose_form.direct_message_warning', }, learn_more: { defaultMessage: 'Learn more', id: 'compose_form.direct_message_warning_learn_more' } }); // The component. export default function ComposerDirectWarning () { return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75, }} style={{ opacity: motionSpring, scaleX: motionSpring, scaleY: motionSpring, }} > {({ opacity, scaleX, scaleY }) => ( <div className='composer--warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})`, }} > <span> <FormattedMessage {...messages.disclaimer} /> <a href='/terms' target='_blank'><FormattedMessage {...messages.learn_more} /></a> </span> </div> )} </Motion> ); } ComposerDirectWarning.propTypes = {};
import React from 'react'; import Motion from 'flavours/glitch/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { defineMessages, FormattedMessage } from 'react-intl'; // This is the spring used with our motion. const motionSpring = spring(1, { damping: 35, stiffness: 400 }); // Messages. const messages = defineMessages({ disclaimer: { defaultMessage: 'This toot will only be sent to all the mentioned users. However, the operators of your instance and any receiving instances may see this message.', id: 'compose_form.direct_message_warning', }, }); // The component. export default function ComposerDirectWarning () { return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75, }} style={{ opacity: motionSpring, scaleX: motionSpring, scaleY: motionSpring, }} > {({ opacity, scaleX, scaleY }) => ( <div className='composer--warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})`, }} > <FormattedMessage {...messages.disclaimer} /> </div> )} </Motion> ); } ComposerDirectWarning.propTypes = {};
Use Process(array) instead of Process(string)
<?php declare(strict_types=1); namespace Marein\Nchan\Tests\TestServer; use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener implements TestListener { use TestListenerDefaultImplementation; /** * @var string */ private $suiteName; /** * @var string */ private $socket; /** * @var string */ private $documentRoot; /** * PhpUnitStartServerListener constructor. * * @param string $suiteName * @param string $socket * @param string $documentRoot */ public function __construct(string $suiteName, string $socket, string $documentRoot) { $this->suiteName = $suiteName; $this->socket = $socket; $this->documentRoot = $documentRoot; } /** * @inheritdoc */ public function startTestSuite(TestSuite $suite): void { if ($suite->getName() === $this->suiteName) { $process = new Process( [ 'php', '-S', $this->socket, $this->documentRoot ] ); $process->start(); // Wait for the server. sleep(1); } } }
<?php declare(strict_types=1); namespace Marein\Nchan\Tests\TestServer; use PHPUnit\Framework\TestListener; use PHPUnit\Framework\TestListenerDefaultImplementation; use PHPUnit\Framework\TestSuite; use Symfony\Component\Process\Process; final class PhpUnitStartServerListener implements TestListener { use TestListenerDefaultImplementation; /** * @var string */ private $suiteName; /** * @var string */ private $socket; /** * @var string */ private $documentRoot; /** * PhpUnitStartServerListener constructor. * * @param string $suiteName * @param string $socket * @param string $documentRoot */ public function __construct(string $suiteName, string $socket, string $documentRoot) { $this->suiteName = $suiteName; $this->socket = $socket; $this->documentRoot = $documentRoot; } /** * @inheritdoc */ public function startTestSuite(TestSuite $suite): void { if ($suite->getName() === $this->suiteName) { $process = new Process( sprintf( 'php -S %s %s', $this->socket, $this->documentRoot ) ); $process->start(); // Wait for the server. sleep(1); } } }
Simplify database query when looking up an alias
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .models import ShortURLAlias from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL, including available Google Analytics parameters. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters utm_params = {'utm_source': redirect.key, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.long_url, utm_params) return HttpResponsePermanentRedirect(url)
from __future__ import unicode_literals import base32_crockford import logging from django.db.models import F from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.shortcuts import get_object_or_404 from django.utils.timezone import now from .models import ShortURL from .models import ShortURLAlias from .utils import add_query_params logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL, including available Google Analytics parameters. """ try: alias = ShortURLAlias.objects.select_related().get(alias=key.lower()) key_id = alias.redirect.id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.filter(pk=key_id).update(hits=F('hits') + 1, last_used=now()) # Inject Google campaign parameters utm_params = {'utm_source': redirect.key, 'utm_campaign': redirect.campaign, 'utm_content': redirect.content, 'utm_medium': redirect.medium} url = add_query_params(redirect.long_url, utm_params) return HttpResponsePermanentRedirect(url)
Add test for schema generation on nested objects.
var schemaGenerator = require("./schema-generator.js"); describe("Schema Generation", function(){ it("Knows that strings should use the string Editor", function(){ var data = { greeting: "hi" }; var schema = schemaGenerator.generateSchema(data); expect(schema.greeting.editor).toBe("string"); }); it("Knows that numbers should use the number Editor", function(){ var data = { age: 57 }; var schema = schemaGenerator.generateSchema(data); expect(schema.age.editor).toBe("number"); }); it("Can generate a schema for objects", function(){ var data = { owner: { name: "Patricia" } } var schema = schemaGenerator.generateSchema(data); expect(schema).toEqual({ owner: { editor: "object", title: "Owner", properties: { name: { editor: "string", title: "Name" } } } } ); }) it("Can generate a schema for nested objects", function(){ var data = { owner: { address: { city: "Paris" } } } var schema = schemaGenerator.generateSchema(data); expect(schema).toEqual({ owner: { editor: "object", title: "Owner", properties: { address: { editor: "object", title: "Address", properties: { city: { editor: "string", title: "City" } } } } } } ); }) })
var schemaGenerator = require("./schema-generator.js"); describe("Schema Generation", function(){ it("Knows that strings should use the string Editor", function(){ var data = { greeting: "hi" }; var schema = schemaGenerator.generateSchema(data); expect(schema.greeting.editor).toBe("string"); }); it("Knows that numbers should use the number Editor", function(){ var data = { age: 57 }; var schema = schemaGenerator.generateSchema(data); expect(schema.age.editor).toBe("number"); }); it("Can generate a schema for objects", function(){ var data = { owner: { name: "Patricia" } } var schema = schemaGenerator.generateSchema(data); expect(schema).toEqual({ owner: { editor: "object", title: "Owner", properties: { name: { editor: "string", title: "Name" } } } } ); }) })
Add moon (Q405) to the list of globes Change-Id: I2dd9f87fcb1d748bff94328575f8439dc36035e3
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', 'test': 'test.wikidata.org', } def scriptpath(self, code): if code == 'client': return '' return super(Family, self).scriptpath(code) def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return (None, None) else: if code == 'wikidata': return ('wikidata', 'wikidata') elif code == 'test': return ('test', 'wikidata') else: return ('repo', 'wikidata') def globes(self, code): """Supported globes for Coordinate datatype""" return {'earth': 'http://www.wikidata.org/entity/Q2', 'moon': 'http://www.wikidata.org/entity/Q405'}
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The wikidata family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikidata' self.langs = { 'wikidata': 'www.wikidata.org', 'repo': 'wikidata-test-repo.wikimedia.de', 'client': 'wikidata-test-client.wikimedia.de', 'test': 'test.wikidata.org', } def scriptpath(self, code): if code == 'client': return '' return super(Family, self).scriptpath(code) def shared_data_repository(self, code, transcluded=False): """Always return a repository tupe. This enables testing whether the site opject is the repository itself, see Site.is_data_repository() """ if transcluded: return (None, None) else: if code == 'wikidata': return ('wikidata', 'wikidata') elif code == 'test': return ('test', 'wikidata') else: return ('repo', 'wikidata') def globes(self, code): """Supported globes for Coordinate datatype""" return {'earth': 'http://www.wikidata.org/entity/Q2'}
Add square brackets [] to list of special characters that are not escaped
<?php namespace { if (!function_exists('mb_parse_url')) { /** * UTF-8 aware parse_url() replacement. * * Taken from php.net manual comments {@link http://php.net/manual/en/function.parse-url.php#114817} * * @param string $url The URL to parse * @param integer $component Specify one of PHP_URL_SCHEME, PHP_URL_HOST, * PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or * PHP_URL_FRAGMENT to retrieve just a specific URL component as a string * (except when PHP_URL_PORT is given, in which case the return value will * be an integer). * @return mixed See parse_url documentation {@link http://us1.php.net/parse_url} */ function mb_parse_url($url, $component = -1) { $enc_url = preg_replace_callback( '%[^:/@?&=#\[\]]+%usD', function ($matches) { return urlencode($matches[0]); }, $url ); $parts = parse_url($enc_url, $component); if ($parts === false) { return $parts; } if (is_array($parts)) { foreach ($parts as $name => $value) { $parts[$name] = urldecode($value); } } else { $parts = urldecode($parts); } return $parts; } } }
<?php namespace { if (!function_exists('mb_parse_url')) { /** * UTF-8 aware parse_url() replacement. * * Taken from php.net manual comments {@link http://php.net/manual/en/function.parse-url.php#114817} * * @param string $url The URL to parse * @param integer $component Specify one of PHP_URL_SCHEME, PHP_URL_HOST, * PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or * PHP_URL_FRAGMENT to retrieve just a specific URL component as a string * (except when PHP_URL_PORT is given, in which case the return value will * be an integer). * @return mixed See parse_url documentation {@link http://us1.php.net/parse_url} */ function mb_parse_url($url, $component = -1) { $enc_url = preg_replace_callback( '%[^:/@?&=#]+%usD', function ($matches) { return urlencode($matches[0]); }, $url ); $parts = parse_url($enc_url, $component); if ($parts === false) { return $parts; } if (is_array($parts)) { foreach ($parts as $name => $value) { $parts[$name] = urldecode($value); } } else { $parts = urldecode($parts); } return $parts; } } }
Create prompt if no config file found
const fs = require('fs'), inquirer = require('inquirer'); const configFilePath = process.env.HOME + '/.gitauthors.json', authors = loadConfig(), choices = createChoices(authors); if (authors) { inquirer.prompt([ { name: 'q1', message: 'Which author details would you like to use with this repository?', type: 'list', choices } ]).then(console.log).catch(console.error); } else { console.log('No authors found!') inquirer.prompt([ { name: 'createConfig', message: 'Would you like to create a new authors config file?', type: 'confirm', default: true } ]).then(answers => { if (answers.createConfig) { console.log('TODO: Show prompts for creating config...'); } }).catch(console.error); } function loadConfig() { if (fs.existsSync(configFilePath)) { return JSON.parse(fs.readFileSync(configFilePath)); } return false; } function createChoices(authors) { let choices; if (authors) { choices = authors.map(author => { if (typeof author.email !== 'string') { throw new Error('Expected type string for email') } if (typeof author.name !== 'string') { throw new Error('Expected type string for name') } return { name: author.alias || `${author.name} <${author.email}>`, value: { email: author.email, name: author.name } }; }).concat( [ new inquirer.Separator(), 'Add new author...', 'Remove author...' ] ); } return choices; }
const fs = require('fs'), inquirer = require('inquirer'); const configFilePath = process.env.HOME + '/.gitauthors.json', authors = loadConfig(), choices = createChoices(authors); if (authors) { inquirer.prompt([ { name: 'q1', message: 'Which author details would you like to use with this repository?', type: 'list', choices } ]).then(console.log).catch(console.error); } else { console.log('No authors defined.'); } function loadConfig() { if (fs.existsSync(configFilePath)) { return JSON.parse(fs.readFileSync(configFilePath)); } else { console.log('No config file found'); } } function createChoices(authors) { let choices; if (authors) { choices = authors.map(author => { if (typeof author.email !== 'string') { throw new Error('Expected type string for email') } if (typeof author.name !== 'string') { throw new Error('Expected type string for name') } return { name: author.alias || `${author.name} <${author.email}>`, value: { email: author.email, name: author.name } }; }).concat( [ new inquirer.Separator(), 'Add new author...', 'Remove author...' ] ); } return choices; }
Fix big preventing some JS from executing
<?php if (!$_SKIP_HEADER) {?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <?php require_once(VIEW_DIR.'/_core/header_meta.php');?> <!--[if lte IE 8]><script src="assets/css/ie/html5shiv.js"></script><![endif]--> <?php require_once(VIEW_DIR.'/_core/header_css.php');?> <!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie/v8.css" /><![endif]--> <!--[if lte IE 8]><script src="assets/css/ie/respond.min.js"></script><![endif]--> <script type="text/javascript" nonce="29af2i"> // this special function can only be declared here var ValidateSubmit = { isSubmitted: false, submit: function() { if (ValidateSubmit.isSubmitted) { return false; } ValidateSubmit.isSubmitted = true; $("input[type=submit]").attr("disabled", "disabled"); form.submit(); }, END: null }; </script> </head> <?php }?>
<?php if (!$_SKIP_HEADER) {?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <?php require_once(VIEW_DIR.'/_core/header_meta.php');?> <!--[if lte IE 8]><script src="assets/css/ie/html5shiv.js"></script><![endif]--> <?php require_once(VIEW_DIR.'/_core/header_css.php');?> <!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie/v8.css" /><![endif]--> <!--[if lte IE 8]><script src="assets/css/ie/respond.min.js"></script><![endif]--> <script type="text/javascript"> // this special function can only be declared here var ValidateSubmit = { isSubmitted: false, submit: function() { if (ValidateSubmit.isSubmitted) { return false; } ValidateSubmit.isSubmitted = true; $("input[type=submit]").attr("disabled", "disabled"); form.submit(); }, END: null }; </script> </head> <?php }?>
Fix logins on VK and FB
module.exports = { title: 'Andrey Prokopyuk', summary: [ "Hello! My name is Andrey. I'm a developer in", '<a href="https://yandex.com" target="_blank">Yandex</a>,', 'working on Search Engine Result Page' ].join(' '), socialNetworks: [ { title: 'GitHub', login: 'Andre-487', url: 'https://github.com/Andre-487' }, { title: 'Twitter', login: 'Andre_487', url: 'https://twitter.com/Andre_487' }, { title: 'Facebook', login: 'andre487', url: 'https://www.facebook.com/profile.php?id=100001722691597' }, { title: 'Instagram', login: 'andre_487', url: 'https://instagram.com/andre_487' }, { title: 'VK', login: 'andre487', url: 'https://vk.com/andre487' }, { title: 'Leprosorium', login: 'Andre_487', url: 'https://leprosorium.ru/users/Andre_487' } ] };
module.exports = { title: 'Andrey Prokopyuk', summary: [ "Hello! My name is Andrey. I'm a developer in", '<a href="https://yandex.com" target="_blank">Yandex</a>,', 'working on Search Engine Result Page' ].join(' '), socialNetworks: [ { title: 'GitHub', login: 'Andre-487', url: 'https://github.com/Andre-487' }, { title: 'Twitter', login: 'Andre_487', url: 'https://twitter.com/Andre_487' }, { title: 'Facebook', login: 'andre.487', url: 'https://www.facebook.com/andre.487' }, { title: 'Instagram', login: 'andre_487', url: 'https://instagram.com/andre_487' }, { title: 'VK', login: 'andre_dm', url: 'https://vk.com/andre_dm' }, { title: 'Leprosorium', login: 'Andre_487', url: 'https://leprosorium.ru/users/Andre_487' } ] };
Make attendance report verify the correct right. Addresses issue #24.
package org.kumoricon.site.report.attendees; import com.vaadin.navigator.View; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; import com.vaadin.ui.Label; import org.kumoricon.site.report.ReportView; import org.kumoricon.site.BaseView; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; @ViewScope @SpringView(name = AttendeeReportView.VIEW_NAME) public class AttendeeReportView extends BaseView implements View, ReportView { public static final String VIEW_NAME = "attendeeReport"; public static final String REQUIRED_RIGHT = "view_attendance_report"; @Autowired private AttendeeReportPresenter handler; private Button refresh = new Button("Refresh"); private Label data = new Label(); @PostConstruct public void init() { addComponent(refresh); refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this)); addComponent(data); data.setContentMode(ContentMode.HTML); handler.fetchReportData(this); setExpandRatio(data, 1f); data.setSizeFull(); data.setWidthUndefined(); } @Override public void afterSuccessfulFetch(String data) { this.data.setValue(data); } public String getRequiredRight() { return REQUIRED_RIGHT; } }
package org.kumoricon.site.report.attendees; import com.vaadin.navigator.View; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; import com.vaadin.ui.Label; import org.kumoricon.site.report.ReportView; import org.kumoricon.site.BaseView; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; @ViewScope @SpringView(name = AttendeeReportView.VIEW_NAME) public class AttendeeReportView extends BaseView implements View, ReportView { public static final String VIEW_NAME = "attendeeReport"; public static final String REQUIRED_RIGHT = "view_attendee_report"; @Autowired private AttendeeReportPresenter handler; private Button refresh = new Button("Refresh"); private Label data = new Label(); @PostConstruct public void init() { addComponent(refresh); refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this)); addComponent(data); data.setContentMode(ContentMode.HTML); handler.fetchReportData(this); setExpandRatio(data, 1f); data.setSizeFull(); data.setWidthUndefined(); } @Override public void afterSuccessfulFetch(String data) { this.data.setValue(data); } public String getRequiredRight() { return REQUIRED_RIGHT; } }
Fix python 2.6 default string formatting
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in iter(d.items()): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{name}.json'.format(name=name)) if os.path.isfile(self.json_path): return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
import imp import json import os import sys class Dot(dict): def __init__(self, d): super(dict, self).__init__() for k, v in iter(d.items()): if isinstance(v, dict): self[k] = Dot(v) else: self[k] = v def __getattr__(self, attr): try: return self[attr] except KeyError: raise AttributeError("'{}'".format(attr)) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ class SempaiLoader(object): def find_module(self, name, path=None): for d in sys.path: self.json_path = os.path.join(d, '{}.json'.format(name)) if os.path.isfile(self.json_path): return self return None def load_module(self, name): mod = imp.new_module(name) mod.__file__ = self.json_path mod.__loader__ = self try: with open(self.json_path) as f: d = json.load(f) except ValueError: raise ImportError( '"{}" does not contain valid json.'.format(self.json_path)) except: raise ImportError( 'Could not open "{}".'.format(self.json_path)) mod.__dict__.update(d) for k, i in mod.__dict__.items(): if isinstance(i, dict): mod.__dict__[k] = Dot(i) return mod sys.meta_path.append(SempaiLoader())
Refactor code to improve readability
<?php function mergeKeys( $config, $configLocal ) { if ( !is_array( $config ) ) { return $configLocal; } foreach ( $config as $key => $value ) { if ( isset( $configLocal[ $key ] ) ) { $config[ $key ] = mergeKeys( $config[ $key ], $configLocal[ $key ] ); } } return $config; } function getBase() { $protocol = 'http'; if ( !empty( $_SERVER[ 'HTTPS' ] ) && $_SERVER[ 'HTTPS' ] == 'on' ) { $protocol .= 's'; } // All scripts are called by index.php so SCRIPT_NAME always points to index.php $relativePath = dirname( $_SERVER[ 'SCRIPT_NAME' ] ); if ( substr( $relativePath, -1 ) != '/' ) { $relativePath .= '/'; } return $protocol . '://' . $_SERVER[ 'HTTP_HOST' ] . $relativePath; } function getConfig( $env ) { $config = require 'config/config.php'; if ( file_exists( 'config/config-local.php' ) ) { $configLocal = require 'config/config-local.php'; $config = mergeKeys( $config, $configLocal ); } $config = $config[ $env ]; $config[ 'root' ] = getcwd(); $config[ 'base' ] = getBase(); return $config; } ?>
<?php function mergeKeys( $config, $configLocal ) { if ( !is_array( $config ) ) { return $configLocal; } foreach ( $config as $key => $value ) { if ( isset( $configLocal[ $key ] ) ) { $config[ $key ] = mergeKeys( $config[ $key ], $configLocal[ $key ] ); } } return $config; } function getBase() { $protocol = 'http'; if ( !empty( $_SERVER[ 'HTTPS' ] ) && $_SERVER[ 'HTTPS' ] == 'on' ) { $protocol .= 's'; } $base = $protocol . '://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'SCRIPT_NAME' ] ); if ( substr( $config[ 'base' ], -1 ) != '/' ) { $base .= '/'; } return $base; } function getConfig( $env ) { $config = require 'config/config.php'; if ( file_exists( 'config/config-local.php' ) ) { $configLocal = require 'config/config-local.php'; $config = mergeKeys( $config, $configLocal ); } $config = $config[ $env ]; $config[ 'root' ] = getcwd(); $config[ 'base' ] = getBase(); return $config; } ?>
Remove redundant type parameter from custom assertion assertMismatch.
package com.mistraltech.smog.examples.utils; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public final class MatcherTestUtils { private MatcherTestUtils() { } public static void assertMismatch(Object input, Matcher<?> matcher, String descriptionOfMismatch) { assertFalse(matcher.matches(input)); Description actualDescriptionOfMismatch = new StringDescription(); matcher.describeMismatch(input, actualDescriptionOfMismatch); assertEquals(singleToDoubleQuotes(descriptionOfMismatch), actualDescriptionOfMismatch.toString()); } public static void assertMismatch(Object input, Matcher<?> matcher, Pattern descriptionOfMismatch) { assertFalse(matcher.matches(input)); Description actualDescriptionOfMismatch = new StringDescription(); matcher.describeMismatch(input, actualDescriptionOfMismatch); String actualDescriptionText = actualDescriptionOfMismatch.toString(); boolean result = descriptionOfMismatch.matcher(actualDescriptionText).matches(); assertTrue("matching: " + descriptionOfMismatch.pattern() + " against: " + actualDescriptionText, result); } public static void assertDescription(Matcher<?> matcher, String descriptionOfExpected) { Description actualDescriptionOfExpected = new StringDescription().appendDescriptionOf(matcher); assertEquals(singleToDoubleQuotes(descriptionOfExpected), actualDescriptionOfExpected.toString()); } private static String singleToDoubleQuotes(String text) { return text.replace('\'', '"'); } }
package com.mistraltech.smog.examples.utils; import java.util.regex.Pattern; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.StringDescription; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public final class MatcherTestUtils { private MatcherTestUtils() { } public static void assertMismatch(Object input, Matcher<?> matcher, String descriptionOfMismatch) { assertFalse(matcher.matches(input)); Description actualDescriptionOfMismatch = new StringDescription(); matcher.describeMismatch(input, actualDescriptionOfMismatch); assertEquals(singleToDoubleQuotes(descriptionOfMismatch), actualDescriptionOfMismatch.toString()); } public static <T> void assertMismatch(Object input, Matcher<?> matcher, Pattern descriptionOfMismatch) { assertFalse(matcher.matches(input)); Description actualDescriptionOfMismatch = new StringDescription(); matcher.describeMismatch(input, actualDescriptionOfMismatch); String actualDescriptionText = actualDescriptionOfMismatch.toString(); boolean result = descriptionOfMismatch.matcher(actualDescriptionText).matches(); assertTrue("matching: " + descriptionOfMismatch.pattern() + " against: " + actualDescriptionText, result); } public static void assertDescription(Matcher<?> matcher, String descriptionOfExpected) { Description actualDescriptionOfExpected = new StringDescription().appendDescriptionOf(matcher); assertEquals(singleToDoubleQuotes(descriptionOfExpected), actualDescriptionOfExpected.toString()); } private static String singleToDoubleQuotes(String text) { return text.replace('\'', '"'); } }
Fix regression with deep linking
import window from 'global'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; // this component renders an iframe, which gets updates via post-messages export class IFrame extends Component { iframe = null; componentDidMount() { const { id } = this.props; this.iframe = window.document.getElementById(id); } shouldComponentUpdate(nextProps) { const { scale, src } = this.props; return scale !== nextProps.scale || src !== nextProps.src; } componentDidUpdate(prevProps) { const { scale } = this.props; if (scale !== prevProps.scale) { this.setIframeBodyStyle({ width: `${scale * 100}%`, height: `${scale * 100}%`, transform: `scale(${1 / scale})`, transformOrigin: 'top left', }); } } setIframeBodyStyle(style) { return Object.assign(this.iframe.contentDocument.body.style, style); } render() { const { id, title, src, allowFullScreen, scale, ...rest } = this.props; return ( <iframe scrolling="yes" id={id} title={title} src={src} allowFullScreen={allowFullScreen} {...rest} /> ); } } IFrame.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, src: PropTypes.string.isRequired, allowFullScreen: PropTypes.bool.isRequired, scale: PropTypes.number.isRequired, };
import window from 'global'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; // this component renders an iframe, which gets updates via post-messages export class IFrame extends Component { iframe = null; componentDidMount() { const { id } = this.props; this.iframe = window.document.getElementById(id); } shouldComponentUpdate(nextProps) { const { scale } = this.props; return scale !== nextProps.scale; } componentDidUpdate(prevProps) { const { scale } = this.props; if (scale !== prevProps.scale) { this.setIframeBodyStyle({ width: `${scale * 100}%`, height: `${scale * 100}%`, transform: `scale(${1 / scale})`, transformOrigin: 'top left', }); } } setIframeBodyStyle(style) { return Object.assign(this.iframe.contentDocument.body.style, style); } render() { const { id, title, src, allowFullScreen, scale, ...rest } = this.props; return ( <iframe scrolling="yes" id={id} title={title} src={src} allowFullScreen={allowFullScreen} {...rest} /> ); } } IFrame.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, src: PropTypes.string.isRequired, allowFullScreen: PropTypes.bool.isRequired, scale: PropTypes.number.isRequired, };
Fix some tests that required Object instances due to 'to equal', and now esprima uses other classes.
/*global describe, it*/ var expect = require('./unexpected-with-plugins').clone(); var parseExpression = require('../lib/parseExpression'); describe('parseExpression', function () { expect.addAssertion('to parse as', function (expect, subject, value) { expect(parseExpression(subject), 'to exhaustively satisfy', value); }); it('should parse a number', function () { expect(2, 'to parse as', { type: 'Literal', value: 2, raw: '2' }); }); it('should parse a string', function () { expect('"foo"', 'to parse as', { type: 'Literal', value: 'foo', raw: '"foo"' }); }); it('should parse an identifier string', function () { expect('foo', 'to parse as', { type: 'Identifier', name: 'foo' }); }); it('should parse a binary operation', function () { expect('4 + 8', 'to parse as', { type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 4, raw: '4' }, right: { type: 'Literal', value: 8, raw: '8' } }); }); });
/*global describe, it*/ var expect = require('./unexpected-with-plugins').clone(); var parseExpression = require('../lib/parseExpression'); describe('parseExpression', function () { expect.addAssertion('to parse as', function (expect, subject, value) { expect(parseExpression(subject), 'to equal', value); }); it('should parse a number', function () { expect(2, 'to parse as', { type: 'Literal', value: 2, raw: '2' }); }); it('should parse a string', function () { expect('"foo"', 'to parse as', { type: 'Literal', value: 'foo', raw: '"foo"' }); }); it('should parse an identifier string', function () { expect('foo', 'to parse as', { type: 'Identifier', name: 'foo' }); }); it('should parse a binary operation', function () { expect('4 + 8', 'to parse as', { type: 'BinaryExpression', operator: '+', left: { type: 'Literal', value: 4, raw: '4' }, right: { type: 'Literal', value: 8, raw: '8' } }); }); });
Revert "temporary fix for lightbox interruption of animation" This reverts commit 8d55ec105855a6c48a9aaea6509a7dc59fdd3240.
// page refresh always brings user to top of page $(window).on('beforeunload', function() { $(window).scrollTop(0); }); // scroll animation window.addEventListener('scroll', function() { // something to support older browsers var scroll = window.requestAnimationFrame || function(callback){ window.setTimeout(callback, 1000/60)}; // elements to show on scroll var elementsToShow = document.querySelectorAll('.show-on-scroll'); // determine visibility function isElementInViewport(el) { // special bonus for those using jQuery if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } var rect = el.getBoundingClientRect(); return ( (rect.top <= 0 && rect.bottom >= 0) || (rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) && rect.top <= (window.innerHeight || document.documentElement.clientHeight)) || (rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)) ); } // loop through elements for animation function loop() { elementsToShow.forEach(function (element) { if (isElementInViewport(element)) { element.classList.add('is-visible'); } else { element.classList.remove('is-visible'); } }); scroll(loop); } loop(); });
// page refresh always brings user to top of page $(window).on('beforeunload', function() { $(window).scrollTop(0); }); // scroll animation window.addEventListener('scroll', function() { // something to support older browsers var scroll = window.requestAnimationFrame || function(callback){ window.setTimeout(callback, 1000/60)}; // elements to show on scroll var elementsToShow = document.querySelectorAll('.show-on-scroll'); // determine visibility function isElementInViewport(el) { // special bonus for those using jQuery if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } var rect = el.getBoundingClientRect(); return ( (rect.top <= 0 && rect.bottom >= 0) || (rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) && rect.top <= (window.innerHeight || document.documentElement.clientHeight)) || (rect.top >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)) ); } var modal = document.getElementById('myModalMenu'); var modalIsVisible = window.getComputedStyle(modal, null).getPropertyValue('display'); // loop through elements for animation function loop() { elementsToShow.forEach(function (element) { if (modalIsVisible == 'none') { if (isElementInViewport(element)) { element.classList.add('is-visible'); } else { element.classList.remove('is-visible'); } } else { element.classList.add('is-visible'); } }); scroll(loop); } loop(); });
Call wraps on the restoring_chdir decorator.
import os from functools import wraps def restoring_chdir(fn): @wraps(fn) def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """ The Base for all Builders. Defines the API for subclasses. """ @restoring_chdir def force(self, version): """ An optional step to force a build even when nothing has changed. """ print "Forcing a build by touching files" os.chdir(version.project.conf_dir(version.slug)) os.system('touch * && touch */*') def clean(self, version): """ Clean up the version so it's ready for usage. This is used to add RTD specific stuff to Sphinx, and to implement whitelists on projects as well. It is guaranteed to be called before your project is built. """ raise NotImplementedError def build(self, version): """ Do the actual building of the documentation. """ raise NotImplementedError def move(self, version): """ Move the documentation from it's generated place to its final home. This needs to understand both a single server dev environment, as well as a multi-server environment. """ raise NotImplementedError
import os def restoring_chdir(fn): def decorator(*args, **kw): try: path = os.getcwd() return fn(*args, **kw) finally: os.chdir(path) return decorator class BaseBuilder(object): """ The Base for all Builders. Defines the API for subclasses. """ @restoring_chdir def force(self, version): """ An optional step to force a build even when nothing has changed. """ print "Forcing a build by touching files" os.chdir(version.project.conf_dir(version.slug)) os.system('touch * && touch */*') def clean(self, version): """ Clean up the version so it's ready for usage. This is used to add RTD specific stuff to Sphinx, and to implement whitelists on projects as well. It is guaranteed to be called before your project is built. """ raise NotImplementedError def build(self, version): """ Do the actual building of the documentation. """ raise NotImplementedError def move(self, version): """ Move the documentation from it's generated place to its final home. This needs to understand both a single server dev environment, as well as a multi-server environment. """ raise NotImplementedError
Update syntax to work with elixir version 3 / Laravel 5.1 - reference: https://github.com/laravel/elixir/releases/tag/3.0.0 - tested: in homestead with `gulp`, passed ps Need to use this for our site, this will really help us with our IE fixes, thanks!
var gulp = require('gulp'); var bless = require('gulp-bless'); var notify = require('gulp-notify'); var path = require('path'); var Elixir = require('laravel-elixir'); var Task = Elixir.Task; Elixir.extend('bless', function(src, outputDir, options) { src = src || './public/css/**/*.css'; if (typeof outputDir == 'object') { options = outputDir; outputDir = './public/blessed'; } else if (outputDir == undefined) { outputDir = './public/blessed'; options = {}; } else { options = options || {}; } var onError = function(err) { notify.onError({ title: 'Laravel Bless', subtitle: 'Bless failed.', message: '<%= error.message %>', icon: path.join(__dirname, '../laravel-elixir/icons/fail.png') })(err); this.emit('end'); }; new Task('bless', function() { return gulp.src(src) .pipe(bless(options)) .pipe(gulp.dest(outputDir)) .on('error', onError) .pipe(notify({ title: 'Laravel Bless', message: 'Blessed CSS', icon: path.join(__dirname, '../laravel-elixir/icons/pass.png'), onLast: true })); }) .watch('./app/**'); });
var gulp = require('gulp'); var bless = require('gulp-bless'); var notify = require('gulp-notify'); var elixir = require('laravel-elixir'); var path = require('path'); elixir.extend('bless', function(src, outputDir, options) { src = src || './public/css/**/*.css'; if (typeof outputDir == 'object') { options = outputDir; outputDir = './public/blessed'; } else if (outputDir == undefined) { outputDir = './public/blessed'; options = {}; } else { options = options || {}; } var onError = function(err) { notify.onError({ title: 'Laravel Bless', subtitle: 'Bless failed.', message: '<%= error.message %>', icon: path.join(__dirname, '../laravel-elixir/icons/fail.png') })(err); this.emit('end'); }; gulp.task('bless', function() { return gulp.src(src) .pipe(bless(options)) .pipe(gulp.dest(outputDir)) .on('error', onError) .pipe(notify({ title: 'Laravel Bless', message: 'Blessed CSS', icon: path.join(__dirname, '../laravel-elixir/icons/pass.png'), onLast: true })); }); this.registerWatcher('bless', src); return this.queueTask('bless'); });
Update to use the static Brain.init()
import logging import os from brain import Brain from cmdparse import Command log = logging.getLogger("hal") class InitCommand(Command): def __init__(self): Command.__init__(self, "init", summary="Initialize a new brain") self.add_option("", "--force", action="store_true") self.add_option("", "--order", type="int", default=5) def run(self, options, args): filename = "hal.brain" if os.path.exists(filename): if options.force: os.remove(filename) else: log.error("%s already exists!", filename) return Brain.init(filename, options.order) class CloneCommand(Command): def __init__(self): Command.__init__(self, "clone", summary="Clone a MegaHAL brain") def run(self, options, args): if len(args) != 1: log.error("usage: clone <MegaHAL brain>") return if os.path.exists("hal.brain"): log.error("hal.brain already exists") return megahal_brain = args[0] Brain.init("hal.brain") b.clone(megahal_brain)
import logging import os import brain from cmdparse import Command log = logging.getLogger("hal") class InitCommand(Command): def __init__(self): Command.__init__(self, "init", summary="Initialize a new brain") self.add_option("", "--force", action="store_true") self.add_option("", "--order", type="int", default=5) def run(self, options, args): filename = "hal.brain" if os.path.exists(filename): if options.force: os.remove(filename) else: log.error("%s already exists!", filename) return b = brain.Brain(filename) b.init(order) class CloneCommand(Command): def __init__(self): Command.__init__(self, "clone", summary="Clone a MegaHAL brain") def run(self, options, args): if len(args) != 1: log.error("usage: clone <MegaHAL brain>") return if os.path.exists("hal.brain"): log.error("hal.brain already exists") return megahal_brain = args[0] b = brain.Brain("hal.brain") b.init() b.clone(megahal_brain)
Implement ftp_site MKDIR command for g4/storage - refactor
<?php namespace G4\Storage\Ftp; class Directory { private $connection; private $directoryPath; private $pathParts; private $useFtpSiteCommand; public function __construct($connection, $filePath, $useFtpSiteCommand = false) { $this->connection = $connection; $this->directoryPath = dirname($filePath); $this->pathParts = array_filter(explode('/', $this->directoryPath)); // foo/bar/bat $this->useFtpSiteCommand = $useFtpSiteCommand; } public function create() { if($this->useFtpSiteCommand) { ftp_site($this->connection, "MKDIR $this->directoryPath"); return; } $pathPart = ''; if(!$this->exists($this->directoryPath)) { foreach($this->pathParts as $part){ $pathPart .= '/' . $part; if(!$this->exists($pathPart)){ ftp_mkdir($this->connection, $pathPart); } } } } private function exists($directoryPath) { $list = ftp_nlist($this->connection, dirname($directoryPath)); return is_array($list) && in_array($directoryPath, $list); } }
<?php namespace G4\Storage\Ftp; class Directory { private $connection; private $directoryPath; private $pathParts; private $useFtpSiteCommand; public function __construct($connection, $filePath, $useFtpSiteCommand = false) { $this->connection = $connection; $this->directoryPath = dirname($filePath); $this->pathParts = array_filter(explode('/', $this->directoryPath)); // foo/bar/bat $this->useFtpSiteCommand = $useFtpSiteCommand; } public function create() { if($this->useFtpSiteCommand) { ftp_site($this->connection, "MKDIR $this->directoryPath"); return $this; } $pathPart = ''; if(!$this->exists($this->directoryPath)) { foreach($this->pathParts as $part){ $pathPart .= '/' . $part; if(!$this->exists($pathPart)){ ftp_mkdir($this->connection, $pathPart); } } } } private function exists($directoryPath) { $list = ftp_nlist($this->connection, dirname($directoryPath)); return is_array($list) && in_array($directoryPath, $list); } }
Update suggest + fetch tags methods to return arrays - prev was using `Set` but it cannot be simply serialized to a primitive to send over the web ext interscript messaging API
import index from './' import { keyGen, removeKeyType } from './util' /** * @param {string} [query=''] Plaintext query string to match against start of tag names. * eg. 'wo' would match 'work', 'women' (assuming both these tags exist). * @param {number} [limit=10] Max number of suggestions to return. * @returns {Promise<string[]>} Resolves to an array of matching tags, if any, of length 0 - `limit`. */ const suggestTags = (query = '', limit = 10) => new Promise((resolve, reject) => { const results = [] // Start searching from the tag matching the query const startKey = keyGen.tag(query) index.db .createReadStream({ gte: startKey, lte: `${startKey}\uffff`, values: false, limit, }) .on('data', tagKey => results.push(removeKeyType(tagKey))) .on('error', reject) .on('end', () => resolve(results)) }) /** * @param {string} pageId The ID of the page to fetch associated tags for. * @returns {Promise<string[]>} Resolves to an array of tags associated with `pageId` - will be empty if none. */ export const fetchTagsForPage = pageId => index .get(pageId, { asBuffer: false }) .then(({ tags = [] }) => [...tags].map(removeKeyType)) .catch(error => []) export default suggestTags
import index from './' import { keyGen, removeKeyType } from './util' /** * @param {string} [query=''] Plaintext query string to match against start of tag names. * eg. 'wo' would match 'work', 'women' (assuming both these tags exist). * @param {number} [limit=10] Max number of suggestions to return. * @returns {Promise<Set<string>>} Resolves to a Set of matching tags, if any, of size 0 - `limit`. */ const suggestTags = (query = '', limit = 10) => new Promise((resolve, reject) => { const results = new Set() // Start searching from the tag matching the query const startKey = keyGen.tag(query) index.db .createReadStream({ gte: startKey, lte: `${startKey}\uffff`, values: false, limit, }) .on('data', tagKey => results.add(removeKeyType(tagKey))) .on('error', reject) .on('end', () => resolve(results)) }) /** * @param {string} pageId The ID of the page to fetch associated tags for. * @returns {Promise<Set<string>>} Resolves to a Set of tags associated with `pageId` - will be empty if none. */ export const fetchTagsForPage = pageId => index .get(pageId, { asBuffer: false }) .then(({ tags = [] }) => new Set([...tags].map(removeKeyType))) .catch(error => new Set()) export default suggestTags
Remove Singletone Test of FileModel
package model; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; import static org.junit.Assert.*; /** * Created by Elliad on 2016-05-08. */ public class FileModelTest { @Test public void fileReadTest() { ArrayList<String> testArraylist = new ArrayList<String>(); testArraylist.add("asdf\n"); testArraylist.add("asdf"); assertTrue(FileModel.getModel().readFile("A.txt")); assertEquals(FileModel.getModel().getStringArrayList(),testArraylist); } @Test public void fileWriteTest() { assertTrue(FileModel.getModel().writeFile("AA.txt")); ArrayList<String> testArraylist = new ArrayList<String>(); try(Scanner in = new Scanner(new FileReader("AA.txt"))) { String tempString = ""; while(in.hasNext()) { tempString = in.next(); //임시 텍스트에 개행을 제외한 한 줄을 불러온다 if(in.hasNext()) tempString +="\n"; //다음 줄이 없을 때는 개행을 추가하지 않는다. testArraylist.add(tempString); } } catch (FileNotFoundException e) { e.printStackTrace(); } assertEquals(FileModel.getModel().getStringArrayList(),testArraylist); } }
package model; import org.junit.Test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; import static org.junit.Assert.*; /** * Created by Elliad on 2016-05-08. */ public class FileModelTest { @Test public void singletonTest() { assertNotNull(FileModel.getModel()); } @Test public void fileReadTest() { ArrayList<String> testArraylist = new ArrayList<String>(); testArraylist.add("asdf\n"); testArraylist.add("asdf"); assertTrue(FileModel.getModel().readFile("A.txt")); assertEquals(FileModel.getModel().getStringArrayList(),testArraylist); } @Test public void fileWriteTest() { assertTrue(FileModel.getModel().writeFile("AA.txt")); ArrayList<String> testArraylist = new ArrayList<String>(); try(Scanner in = new Scanner(new FileReader("AA.txt"))) { String tempString = ""; while(in.hasNext()) { tempString = in.next(); //임시 텍스트에 개행을 제외한 한 줄을 불러온다 if(in.hasNext()) tempString +="\n"; //다음 줄이 없을 때는 개행을 추가하지 않는다. testArraylist.add(tempString); } } catch (FileNotFoundException e) { e.printStackTrace(); } assertEquals(FileModel.getModel().getStringArrayList(),testArraylist); } }
Replace for loop with foreach
<?php namespace BinSoul\Net\Mqtt; /** * Matches a topic filter with an actual topic. * * @author Alin Eugen Deac <[email protected]> */ class TopicMatcher { /** * Check if the given topic matches the filter. * * @param string $filter e.g. A/B/+, A/B/# * @param string $topic e.g. A/B/C, A/B/foo/bar/baz * * @return bool true if topic matches the pattern */ public function matches($filter, $topic) { // Created by Steffen (https://github.com/kernelguy) $tokens = explode('/', $filter); $parts = []; foreach ($tokens as $index => $token) { switch ($token) { case '+': $parts[] = '[^/#\+]*'; break; case '#': if ($index === 0) { $parts[] = '[^\+\$]*'; } else { $parts[] = '[^\+]*'; } break; default: $parts[] = str_replace('+', '\+', $token); break; } } $regex = implode('/', $parts); $regex = str_replace('$', '\$', $regex); $regex = ';^'.$regex.'$;'; return preg_match($regex, $topic) === 1; } }
<?php namespace BinSoul\Net\Mqtt; /** * Matches a topic filter with an actual topic. * * @author Alin Eugen Deac <[email protected]> */ class TopicMatcher { /** * Check if the given topic matches the filter. * * @param string $filter e.g. A/B/+, A/B/# * @param string $topic e.g. A/B/C, A/B/foo/bar/baz * * @return bool true if topic matches the pattern */ public function matches($filter, $topic) { // Created by Steffen (https://github.com/kernelguy) $tokens = explode('/', $filter); $parts = []; for ($i = 0, $count = count($tokens); $i < $count; ++$i) { $token = $tokens[$i]; switch ($token) { case '+': $parts[] = '[^/#\+]*'; break; case '#': if ($i === 0) { $parts[] = '[^\+\$]*'; } else { $parts[] = '[^\+]*'; } break; default: $parts[] = str_replace('+', '\+', $token); break; } } $regex = implode('/', $parts); $regex = str_replace('$', '\$', $regex); $regex = ';^'.$regex.'$;'; return preg_match($regex, $topic) === 1; } }
Set up Travis test environment (cont. 3) Autowatch didn't help. Seeing if `singleRun = true` causes it to stop after running the tests.
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, customLaunchers: { ChromeHeadless: { base: 'Chrome', flags: [ '--headless', '--disable-gpu', '--remote-debugging-port=9222', '--no-sandbox' ] } }, browsers: ['Chrome'], singleRun: false }; if (process.env.TRAVIS) { configuration.singleRun = true; configuration.browsers = ['ChromeHeadless']; } config.set(configuration); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { var configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, customLaunchers: { ChromeHeadless: { base: 'Chrome', flags: [ '--headless', '--disable-gpu', '--remote-debugging-port=9222', '--no-sandbox' ] } }, browsers: ['Chrome'], singleRun: false }; if (process.env.TRAVIS) { configuration.autoWatch = false; configuration.browsers = ['ChromeHeadless']; } config.set(configuration); };
Include campaign overview page in nav
<nav class="navigation -white -floating"> <a class="navigation__logo" href="/"><span>DoSomething.org</span></a> <div class="navigation__menu"> @if (Auth::user()) <ul class="navigation__primary"> <li> <a href="/campaigns"> <strong class="navigation__title">Campaign Overview</strong> </a> </li> <li> <a href="#"> <strong class="navigation__title">Two Fish</strong> </a> </li> <li> <a href="#"> <strong class="navigation__title">Three Fish</strong> </a> </li> </ul> <ul class="navigation__secondary"> <li> <a href="/logout">Log Out</a> </li> </ul> @endif </div> </nav>
<nav class="navigation -white -floating"> <a class="navigation__logo" href="/"><span>DoSomething.org</span></a> <div class="navigation__menu"> @if (Auth::user()) <ul class="navigation__primary"> <li> <a href="#"> <strong class="navigation__title">One Fish</strong> </a> </li> <li> <a href="#"> <strong class="navigation__title">Two Fish</strong> </a> </li> <li> <a href="#"> <strong class="navigation__title">Three Fish</strong> </a> </li> </ul> <ul class="navigation__secondary"> <li> <a href="/logout">Log Out</a> </li> </ul> @endif </div> </nav>
Add missing space for curly. NOTE: Last commit comment was truncated from typo, basically was a fix for Firefox and an escaping bug with window.location.hash.
function uriSync(method, model, options) { var resp = null, S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }, guid = function() { return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, URI = { parse: function() { var hash = window.location.href.split("#")[1] || "", json = decodeURIComponent(hash), data = {}; try { data = json ? JSON.parse(json) : {}; } catch(e) {} return data; }, stringify: function(data) { return encodeURIComponent(JSON.stringify(data)); } }; var data = URI.parse() || {}; switch (method) { case "read": resp = model.id ? data[model.id] || {} : data; break; case "create": if (!model.id) { model.set('id', guid()); } resp = data[model.id] = model; window.location.hash = URI.stringify(data); break; case "update": resp = data[model.id] = model; window.location.hash = URI.stringify(data); break; case "delete": delete data[model.id]; window.location.hash = URI.stringify(data); break; } if (resp) { options.success(resp); } else { options.error("Record not found"); } }
function uriSync(method, model, options) { var resp = null, S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }, guid = function() { return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }, URI = { parse: function(){ var hash = window.location.href.split("#")[1] || "", json = decodeURIComponent(hash), data = {}; try { data = json ? JSON.parse(json) : {}; } catch(e) {} return data; }, stringify: function(data) { return encodeURIComponent(JSON.stringify(data)); } }; var data = URI.parse() || {}; switch (method) { case "read": resp = model.id ? data[model.id] || {} : data; break; case "create": if (!model.id) { model.set('id', guid()); } resp = data[model.id] = model; window.location.hash = URI.stringify(data); break; case "update": resp = data[model.id] = model; window.location.hash = URI.stringify(data); break; case "delete": delete data[model.id]; window.location.hash = URI.stringify(data); break; } if (resp) { options.success(resp); } else { options.error("Record not found"); } }
Switch condition order to support PHP 8
<?php declare(strict_types=1); namespace Invoker\ParameterResolver; use ReflectionFunctionAbstract; use ReflectionNamedType; /** * Inject entries using type-hints. * * Tries to match type-hints with the parameters provided. */ class TypeHintResolver implements ParameterResolver { public function getParameters( ReflectionFunctionAbstract $reflection, array $providedParameters, array $resolvedParameters ): array { $parameters = $reflection->getParameters(); // Skip parameters already resolved if (! empty($resolvedParameters)) { $parameters = array_diff_key($parameters, $resolvedParameters); } foreach ($parameters as $index => $parameter) { $parameterType = $parameter->getType(); if (! $parameterType) { // No type continue; } if (! $parameterType instanceof ReflectionNamedType) { // Union types are not supported continue; } if ($parameterType->isBuiltin()) { // Primitive types are not supported continue; } $parameterClass = $parameterType->getName(); if ($parameterClass === 'self') { $parameterClass = $parameter->getDeclaringClass()->getName(); } if (array_key_exists($parameterClass, $providedParameters)) { $resolvedParameters[$index] = $providedParameters[$parameterClass]; } } return $resolvedParameters; } }
<?php declare(strict_types=1); namespace Invoker\ParameterResolver; use ReflectionFunctionAbstract; use ReflectionNamedType; /** * Inject entries using type-hints. * * Tries to match type-hints with the parameters provided. */ class TypeHintResolver implements ParameterResolver { public function getParameters( ReflectionFunctionAbstract $reflection, array $providedParameters, array $resolvedParameters ): array { $parameters = $reflection->getParameters(); // Skip parameters already resolved if (! empty($resolvedParameters)) { $parameters = array_diff_key($parameters, $resolvedParameters); } foreach ($parameters as $index => $parameter) { $parameterType = $parameter->getType(); if (! $parameterType) { // No type continue; } if ($parameterType->isBuiltin()) { // Primitive types are not supported continue; } if (! $parameterType instanceof ReflectionNamedType) { // Union types are not supported continue; } $parameterClass = $parameterType->getName(); if ($parameterClass === 'self') { $parameterClass = $parameter->getDeclaringClass()->getName(); } if (array_key_exists($parameterClass, $providedParameters)) { $resolvedParameters[$index] = $providedParameters[$parameterClass]; } } return $resolvedParameters; } }
Fix a python3 import .
try: from urllib.request import urlopen except ImportError: from urllib import urlopen import datetime import multiprocessing from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.core.management.base import BaseCommand, CommandError from core.models import URL, Cron def request_url(url): urlopen("http://{0}{1}".format( Site.objects.get_current().domain, reverse("run_fn", kwargs={"slug": url.slug}) )) class Command(BaseCommand): help = "Run the url scripts" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(multiprocessing.cpu_count()) today = int(datetime.date.today().strftime("%s")) now = datetime.datetime.now() curr_time = int(now.strftime("%s")) - now.second mins_passed = int((curr_time - today) / 60.0) intervals = Cron.objects.filter(interval__lte=mins_passed)\ .values_list('interval', flat=True).\ order_by('interval').distinct() for interval in intervals: if mins_passed % interval == 0 or settings.DEBUG: for cron in Cron.objects.filter(interval=interval): url = cron.url pool.apply_async(request_url, (url, )) pool.close() pool.join()
import urllib import datetime import multiprocessing from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.core.management.base import BaseCommand, CommandError from core.models import URL, Cron def request_url(url): urllib.urlopen("http://{0}{1}".format( Site.objects.get_current().domain, reverse("run_fn", kwargs={"slug": url.slug}) )) class Command(BaseCommand): help = "Run the url scripts" can_import_settings = True def handle(self, *args, **options): pool = multiprocessing.Pool(multiprocessing.cpu_count()) today = int(datetime.date.today().strftime("%s")) now = datetime.datetime.now() curr_time = int(now.strftime("%s")) - now.second mins_passed = int((curr_time - today) / 60.0) intervals = Cron.objects.filter(interval__lte=mins_passed)\ .values_list('interval', flat=True).\ order_by('interval').distinct() request = "" for interval in intervals: if mins_passed % interval == 0 or settings.DEBUG: for cron in Cron.objects.filter(interval=interval): url = cron.url pool.apply_async(request_url, (url, )) pool.close() pool.join()
fix: Add missing semicolon in crawler controller
<?php namespace Mini\Model\TypeCrawler; use \Mini\Model\TypeCrawler\Storage\StorageFactory; //TODO disable crawlers if the type is disabled in the DB. class TypeCrawlerController { /** @var array */ private $crawlers; /** @var StorageFactory */ private $storage; function __construct(StorageFactory $storageFactory) { $this->crawlers = array(); $this->storage = $storageFactory; $this->registerCrawler('ModBot'); $this->registerCrawler('Pajbot'); $this->registerCrawler('DeepBot'); $this->registerCrawler('FrankerFaceZ.php'); } private function getClassName(string $crawler): string { return '\\Mini\\Model\\TypeCrawler\\'.$crawler; } public function registerCrawler(string $crawler) { $crawler = $this->getClassName($crawler); $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type)); } public function crawl(int $type): array { foreach($this->crawlers as $c) { if($c::$type == $type) { $crawler = $c; break; } } return $crawler->crawl(); } public function triggerCrawl(): array { $ret = array(); foreach($this->crawlers as $crawler) { try { $crawlResult = $crawler->crawl(); } catch(Exception $e) { continue; } $ret = array_merge($ret, $crawlResult); } return $ret; } }
<?php namespace Mini\Model\TypeCrawler; use \Mini\Model\TypeCrawler\Storage\StorageFactory; //TODO disable crawlers if the type is disabled in the DB. class TypeCrawlerController { /** @var array */ private $crawlers; /** @var StorageFactory */ private $storage; function __construct(StorageFactory $storageFactory) { $this->crawlers = array(); $this->storage = $storageFactory; $this->registerCrawler('ModBot'); $this->registerCrawler('Pajbot'); $this->registerCrawler('DeepBot'); $this->registerCrawler('FrankerFaceZ.php') } private function getClassName(string $crawler): string { return '\\Mini\\Model\\TypeCrawler\\'.$crawler; } public function registerCrawler(string $crawler) { $crawler = $this->getClassName($crawler); $this->crawlers[] = new $crawler($this->storage->getStorage($crawler::$type)); } public function crawl(int $type): array { foreach($this->crawlers as $c) { if($c::$type == $type) { $crawler = $c; break; } } return $crawler->crawl(); } public function triggerCrawl(): array { $ret = array(); foreach($this->crawlers as $crawler) { try { $crawlResult = $crawler->crawl(); } catch(Exception $e) { continue; } $ret = array_merge($ret, $crawlResult); } return $ret; } }
Make the delay longer so that test passes more consistently.
define(["pat-masonry"], function(pattern) { describe("pat-masonry", function() { beforeEach(function() { $("<div/>", {id: "lab"}).appendTo(document.body); }); afterEach(function() { $("#lab").remove(); }); it("Sets class masonry-ready on the element after masonry has finished", function() { var $msnry; runs(function () { $("#lab").html( "<div class='pat-masonry'>" + " <div class='item'>" + " <img src='http://i.imgur.com/6Lo8oun.jpg'>"+ " </div>" + " <div class='item'>" + " <img src='http://i.imgur.com/HDSAMFl.jpg'>"+ " </div>" + "</div>"); $msnry = $("#lab .pat-masonry"); expect($msnry.hasClass("masonry-ready")).toBeFalsy(); pattern.init($msnry); }); waits(600); runs(function () { expect($msnry.hasClass("masonry-ready")).toBeTruthy(); }); }); }); });
define(["pat-masonry"], function(pattern) { describe("pat-masonry", function() { beforeEach(function() { $("<div/>", {id: "lab"}).appendTo(document.body); }); afterEach(function() { $("#lab").remove(); }); it("Sets class masonry-ready on the element after masonry has finished", function() { $("#lab").html( "<div class='pat-masonry'>" + " <div class='item'>" + " <img src='http://i.imgur.com/6Lo8oun.jpg'>"+ " </div>" + " <div class='item'>" + " <img src='http://i.imgur.com/HDSAMFl.jpg'>"+ " </div>" + "</div>"); var $msnry = $("#lab .pat-masonry"); expect($msnry.hasClass("masonry-ready")).toBeFalsy(); runs(function () { pattern.init($msnry); }); waits(300); runs(function () { expect($msnry.hasClass("masonry-ready")).toBeTruthy(); }); }); }); });
Set max-age=0 for CacheControl on profile image S3 uploads
const s3 = require('aws-sdk').S3; const s3Bucket = require('../../../config')('/aws/s3Bucket'); const logger = require('../../lib/logger'); module.exports = () => ({ uploadImageStream(stream, key) { const contentType = (stream.hapi && stream.hapi.headers['content-type']) ? stream.hapi.headers['content-type'] : 'application/octet-stream'; const filename = key; const bucket = new s3({ params: { Bucket: s3Bucket } }); return bucket.upload({ Body: stream, Key: filename, ContentType: contentType, CacheControl: 'max-age=0' }) .promise() .then(data => data.Location) .catch(error => { const trace = new Error(error); logger.error(trace); throw error; }); }, deleteImage(filename) { const bucket = new s3({ params: { Bucket: s3Bucket } }); return new Promise((resolve, reject) => { bucket.deleteObject({ Key: filename }) .send((err, data) => { if (err) { reject(err); } else { resolve(filename); } }); }) .catch((error) => { const trace = new Error(error); logger.error(trace); throw error; }); }, }); module.exports['@singleton'] = true; module.exports['@require'] = [];
const s3 = require('aws-sdk').S3; const s3Bucket = require('../../../config')('/aws/s3Bucket'); const logger = require('../../lib/logger'); module.exports = () => ({ uploadImageStream(stream, key) { const contentType = (stream.hapi && stream.hapi.headers['content-type']) ? stream.hapi.headers['content-type'] : 'application/octet-stream'; const filename = key; const bucket = new s3({ params: { Bucket: s3Bucket } }); return bucket.upload({ Body: stream, Key: filename, ContentType: contentType }) .promise() .then(data => data.Location) .catch(error => { const trace = new Error(error); logger.error(trace); throw error; }); }, deleteImage(filename) { const bucket = new s3({ params: { Bucket: s3Bucket } }); return new Promise((resolve, reject) => { bucket.deleteObject({ Key: filename }) .send((err, data) => { if (err) { reject(err); } else { resolve(filename); } }); }) .catch((error) => { const trace = new Error(error); logger.error(trace); throw error; }); }, }); module.exports['@singleton'] = true; module.exports['@require'] = [];
Make some change in the annotation
<?php namespace AppBundle\Model; use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation\Type; /** * Class EmployeesResponse * @package AppBundle\Model * @ExclusionPolicy("all") */ class EmployeesResponse { /** * @var Array[] * @Type("array<AppBundle\Entity\Employee>") * @Expose */ protected $employees; /** * @var int * * @Type("integer") * @Accessor(getter="getCount") * @Expose */ protected $count; /** * @var int * * @Type("integer") * @Expose */ protected $totalCount; /** * @return mixed */ public function getEmployees() { return $this->employees; } /** * @param mixed $employees */ public function setEmployees($employees) { $this->employees = $employees; } /** * @return int */ public function getCount() { return count($this->getEmployees()); } /** * @return int */ public function getTotalCount() { return $this->totalCount; } /** * @param $totalCount * @return EmployeesResponse */ public function setTotalCount($totalCount) { $this->totalCount = $totalCount; return $this; } }
<?php namespace AppBundle\Model; use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\ExclusionPolicy; use JMS\Serializer\Annotation\Expose; use JMS\Serializer\Annotation\Type; /** * Class EmployeesResponse * @package AppBundle\Model * @ExclusionPolicy("all") */ class EmployeesResponse { /** * @var Array[] * @Type("array<AppBundle\Entity\Employee>") * @Expose */ protected $employees; /** * @var int * * @Type("integer") * @Accessor(getter="getCount") * @Expose */ protected $count; /** * @var int * * @Type("integer") * @Expose */ protected $totalCount; /** * @return mixed */ public function getEmployees() { return $this->employees; } /** * @param mixed $employees */ public function setEmployees($employees) { $this->employees = $employees; } /** * @return int */ public function getCount() { return count($this->getEmployees()); } /** * @return int */ public function getTotalCount() { return $this->totalCount; } /** * @param $totalCount * @return PerformancesResponse */ public function setTotalCount($totalCount) { $this->totalCount = $totalCount; return $this; } }
Print everything out in csv and use tableau to do calculation
import os from utils import Reader import code import sys def extract_authors(tweets): for t in tweets: if t.is_post(): actor = t.actor() print '"{}","{}","{}","{}",{},{}'.format(actor['id'], actor['link'], actor['preferredUsername'], actor['displayName'], 1, 0) elif t.is_share(): original_tweet = t.data['object'] actor = original_tweet['actor'] print '"{}","{}","{}","{}",{},{}'.format(actor['id'], actor['link'], actor['preferredUsername'], actor['displayName'], 0, 1) else: print 'Neither post nor share:', t.id() if __name__ == '__main__': # coding=utf-8 reload(sys) sys.setdefaultencoding('utf-8') working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: extract_authors(Reader.read_file(f)) # code.interact(local=dict(globals(), **locals()))
import os from utils import Reader import code import sys author_dict = dict() def extract_authors(tweets): # code.interact(local=dict(globals(), **locals())) for t in tweets: if t.is_post(): actor = t.actor() create_key(actor['id']) increment_author(actor, t.is_post()) elif t.is_share(): original_tweet = t.data['object'] actor = original_tweet['actor'] create_key(actor['id']) increment_author(actor, t.is_post()) else: print 'Neither post nor share:', t.id() def increment_author(actor, is_post): dict_value = author_dict[actor['id']] dict_value[0] = actor['link'] dict_value[1] = actor['preferredUsername'] dict_value[2] = actor['displayName'] if is_post: dict_value[3] += 1 else: dict_value[4] += 1 def create_key(actor_id): if actor_id not in author_dict.keys(): # link, username, display_name, post, post that gotten shared default_value = ['', '', '', 0, 0] author_dict[actor_id] = default_value def print_all(): for k in author_dict.keys(): value = author_dict[k] print '"{}","{}","{}","{}",{},{}'.format(k, value[0], value[1], value[2], value[3], value[4]) if __name__ == '__main__': # coding=utf-8 reload(sys) sys.setdefaultencoding('utf-8') working_directory = os.getcwd() files = Reader.read_directory(working_directory) for f in files: extract_authors(Reader.read_file(f)) print_all() # code.interact(local=dict(globals(), **locals()))
Fix race condition in detumbling experiment test In detumbling experiment test, experiment was commanded to run for 4 hours. After that OBC time was advanced also by 4 hours, however it was not enough as during next mission loop OBC time was few milliseconds before scheduled experiment end.
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4, minutes=1).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4, minutes=1)) self.system.obc.wait_for_experiment(None, 20)
from datetime import timedelta, datetime import telecommand from obc.experiments import ExperimentType from system import auto_power_on from tests.base import BaseTest from utils import TestEvent class TestExperimentDetumbling(BaseTest): @auto_power_on(auto_power_on=False) def __init__(self, *args, **kwargs): super(TestExperimentDetumbling, self).__init__(*args, **kwargs) def _start(self): e = TestEvent() def on_reset(_): e.set() self.system.comm.on_hardware_reset = on_reset self.system.obc.power_on(clean_state=True) self.system.obc.wait_to_start() e.wait_for_change(1) def test_should_perform_experiment(self): self._start() start_time = datetime.now() self.system.rtc.set_response_time(start_time) self.system.comm.put_frame(telecommand.PerformDetumblingExperiment(duration=timedelta(hours=4))) self.system.obc.wait_for_experiment(ExperimentType.Detumbling, 40) self.system.obc.advance_time(timedelta(hours=4).total_seconds() * 1000) self.system.rtc.set_response_time(start_time + timedelta(hours=4)) self.system.obc.wait_for_experiment(None, 20)
Remove legacy check from diskreport migration
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Diskreport extends Migration { public function up() { $capsule = new Capsule(); $capsule::schema()->create('diskreport', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->bigInteger('TotalSize'); $table->bigInteger('FreeSpace'); $table->bigInteger('Percentage'); $table->string('SMARTStatus'); $table->string('VolumeType'); $table->string('media_type'); $table->string('BusProtocol'); $table->integer('Internal'); $table->string('MountPoint'); $table->string('VolumeName'); $table->integer('CoreStorageEncrypted'); $table->string('timestamp'); $table->index('serial_number', 'diskreport_serial_number'); $table->index('MountPoint', 'diskreport_MountPoint'); $table->index('media_type', 'diskreport_media_type'); $table->index('VolumeName', 'diskreport_VolumeName'); $table->index('VolumeType', 'diskreport_VolumeType'); // $table->timestamps(); }); } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('diskreport'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Capsule\Manager as Capsule; class Diskreport extends Migration { public function up() { $capsule = new Capsule(); $legacy_migration_version = $capsule::table('migration') ->where('table_name', '=', 'diskreport') ->first(['version']); if ($legacy_migration_version && $legacy_migration_version->version === 3) { // No need to run this migration } else { $capsule::schema()->create('diskreport', function (Blueprint $table) { $table->increments('id'); $table->string('serial_number'); $table->bigInteger('TotalSize'); $table->bigInteger('FreeSpace'); $table->bigInteger('Percentage'); $table->string('SMARTStatus'); $table->string('VolumeType'); $table->string('media_type'); $table->string('BusProtocol'); $table->integer('Internal'); $table->string('MountPoint'); $table->string('VolumeName'); $table->integer('CoreStorageEncrypted'); $table->string('timestamp'); $table->index('serial_number', 'diskreport_serial_number'); $table->index('MountPoint', 'diskreport_MountPoint'); $table->index('media_type', 'diskreport_media_type'); $table->index('VolumeName', 'diskreport_VolumeName'); $table->index('VolumeType', 'diskreport_VolumeType'); // $table->timestamps(); }); } } public function down() { $capsule = new Capsule(); $capsule::schema()->dropIfExists('diskreport'); } }
Fix Style CI unused import
<?php declare(strict_types=1); namespace Tests; use App\Commands\FakeDefaultCommand; use App\Commands\FakeFooCommand; use App\HiddenCommands\FakeHiddenCommand; use App\OtherCommands\FakeOtherCommand; use Illuminate\Support\Facades\Artisan; final class LoadConfigurationsTest extends TestCase { public function testThatApplicationConfigurationIsAvailable(): void { $this->assertSame('Application', Artisan::getName()); $this->assertSame('Test version', $this->app->version()); $this->assertEquals($this->app->environment(), 'development'); } public function testAddCommands(): void { $commands = [ FakeDefaultCommand::class, FakeFooCommand::class, FakeOtherCommand::class, FakeHiddenCommand::class, ]; $appCommands = collect(Artisan::all()) ->map( function ($command) { return get_class($command); } ) ->toArray(); foreach ($commands as $command) { $this->assertContains($command, $appCommands); } } public function testHideCommands(): void { $this->assertTrue(Artisan::all()['fake:hidden']->isHidden()); } public function testRemoveCommands(): void { $this->assertArrayNotHasKey('fake:removed', Artisan::all()); } }
<?php declare(strict_types=1); namespace Tests; use App\Commands\FakeDefaultCommand; use App\Commands\FakeFooCommand; use App\HiddenCommands\FakeHiddenCommand; use App\OtherCommands\FakeOtherCommand; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; final class LoadConfigurationsTest extends TestCase { public function testThatApplicationConfigurationIsAvailable(): void { $this->assertSame('Application', Artisan::getName()); $this->assertSame('Test version', $this->app->version()); $this->assertEquals($this->app->environment(), 'development'); } public function testAddCommands(): void { $commands = [ FakeDefaultCommand::class, FakeFooCommand::class, FakeOtherCommand::class, FakeHiddenCommand::class, ]; $appCommands = collect(Artisan::all()) ->map( function ($command) { return get_class($command); } ) ->toArray(); foreach ($commands as $command) { $this->assertContains($command, $appCommands); } } public function testHideCommands(): void { $this->assertTrue(Artisan::all()['fake:hidden']->isHidden()); } public function testRemoveCommands(): void { $this->assertArrayNotHasKey('fake:removed', Artisan::all()); } }
Handle topics with zero elements
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() resp = req.get('http://localhost:5000/api/topic/{}'.format(topic))\ data = resp.json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res elif resp.ok and not items: return else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
from datetime import datetime import requests as req from pymongo import MongoClient from pypocketexplore.config import MONGO_URI from time import sleep def extract_topic_items(topic): db = MongoClient(MONGO_URI).get_default_database() data = req.get('http://localhost:5000/api/topic/{}'.format(topic)).json() related_topics = data.get('related_topics') items = data.get('items') if items: res = db['items'].insert(items) db['topics'].update_many({'topic': topic}, {'$set': {'topic': topic, 'is_scraped': True, 'datetime_scraped': datetime.utcnow(), 'queued': True}}, upsert=True) for related_topic in related_topics: req.get('http://localhost:5000/api/topic/{}?async=true'.format(related_topic)).json() print("Rate limit! Going to sleep for 2 mins!") sleep(2 * 60) print("Wakey wakey eggs and bakey!") return res else: raise Exception if __name__ == '__main__': extract_topic_items('finance')
Change test method name to better match
import unittest from collections import namedtuple # TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort # of ugliness. from jarvis import convert_file_to_json, get_tags JarvisSettings = namedtuple('JarvisSettings', ['tags_directory']) class TestJarvis(unittest.TestCase): def setUp(self): with open('fixtures/test_log.md', 'r') as f: self.test_log = f.read() self.js = JarvisSettings('fixtures/tags') def test_convert_file_to_json(self): try: j = convert_file_to_json(self.test_log) # Version 0.2.0 expected_keys = sorted(['version', 'created', 'body', 'tags', 'occurred', 'author']) actual_keys = sorted(j.keys()) self.assertListEqual(expected_keys, actual_keys) except Exception as e: self.fail("Unexpected error while parsing test_log") def test_get_tags(self): expected_tags = ['TestA', 'TestB&C'] actual_tags = get_tags(self.js) self.assertListEqual(expected_tags, actual_tags) if __name__ == "__main__": """ To run: export PYTHONPATH="$HOME/oz/workspace/Jarvis/bin" python -m unittest test_jarvis.py """ unittest.main()
import unittest from collections import namedtuple # TODO: Move this code to a module so we don't depend on PYTHONPATH and that sort # of ugliness. from jarvis import convert_file_to_json, get_tags JarvisSettings = namedtuple('JarvisSettings', ['tags_directory']) class TestJarvis(unittest.TestCase): def setUp(self): with open('fixtures/test_log.md', 'r') as f: self.test_log = f.read() self.js = JarvisSettings('fixtures/tags') def test_convert_log(self): try: j = convert_file_to_json(self.test_log) # Version 0.2.0 expected_keys = sorted(['version', 'created', 'body', 'tags', 'occurred', 'author']) actual_keys = sorted(j.keys()) self.assertListEqual(expected_keys, actual_keys) except Exception as e: self.fail("Unexpected error while parsing test_log") def test_get_tags(self): expected_tags = ['TestA', 'TestB&C'] actual_tags = get_tags(self.js) self.assertListEqual(expected_tags, actual_tags) if __name__ == "__main__": """ To run: export PYTHONPATH="$HOME/oz/workspace/Jarvis/bin" python -m unittest test_jarvis.py """ unittest.main()
Allow PiSense readings to be toggled on/off
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.25 class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger self.sensor = sensor self.recording = False self.logger.log(DEVICE, "running", 1) def read(self): values = {} if self.recording: for reading in self.sensor.get_data(): values[reading[1]] = reading[2] self.logger.log(DEVICE, reading[1], reading[2], reading[0]) display.show_properties(values, self.sensor.get_properties()) else: values["recording"] = False display.show_properties(values) return True def record(self): self.recording = not self.recording if self.recording: self.logger.log(DEVICE, "recording", 1) else: self.logger.log(DEVICE, "recording", 0) return True def quit(self): self.logger.log(DEVICE, "running", 0) return False with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger: # setup display display = Display("PiSense", "[r]ecord [q]uit") # setup key handlers handler = Handler(display, logger, sensor) dispatcher.add("r", handler, "record") dispatcher.add("q", handler, "quit") # start processing key presses while True: if dispatcher.can_process_key(): if not dispatcher.process_key(): break else: handler.read() time.sleep(DELAY)
#!/usr/bin/env python3 from Sensor import SenseController from KeyDispatcher import KeyDispatcher from Display import Display from DataLogger import SQLiteLogger import time DEVICE = "PiSense" DELAY = 0.0 class Handler: def __init__(self, display, logger, sensor): self.display = display self.logger = logger self.sensor = sensor self.logger.log(DEVICE, "running", 1) def read(self): values = {} for reading in self.sensor.get_data(): values[reading[1]] = reading[2] self.logger.log(DEVICE, reading[1], reading[2], reading[0]) display.show_properties(values, self.sensor.get_properties()) return True def quit(self): self.logger.log(DEVICE, "running", 0) return False with SenseController() as sensor, KeyDispatcher() as dispatcher, SQLiteLogger() as logger: # setup display display = Display("PiSense") # setup key handlers handler = Handler(display, logger, sensor) dispatcher.add("q", handler, "quit") # start processing key presses while True: if dispatcher.can_process_key(): if not dispatcher.process_key(): break else: handler.read() time.sleep(DELAY)
Add vendor directory to dist
var gulp = require('gulp'); var clean = require('gulp-clean'); var zip = require('gulp-zip'); var bases = { root: 'dist/' }; var paths = [ 'core/**', '!core/data', '!core/data/**/*', '!core/logs/**/*.txt', '!core/logs/**/*.pdf', '!core/logs/**/*.html', '!core/tests', '!core/tests/**/*', 'admin/**', '!admin/api/config', '!admin/api/config/**/*', 'boxoffice/**', '!boxoffice/api/config', '!boxoffice/api/config/**/*', 'customer/**', '!customer/api/config', '!customer/api/config/**/*', 'printer/**', '!printer/api/config', '!printer/api/config/**/*', 'scanner/**', '!scanner/api/config', '!scanner/api/config/**/*', 'vendor/**' ]; gulp.task('clean', function() { return gulp.src(bases.root) .pipe(clean({})); }); gulp.task('collect', function() { return gulp.src(paths, { base: './', dot: true }) .pipe(gulp.dest(bases.root)); }); gulp.task('zip', function() { return gulp.src(bases.root + '**') .pipe(zip('ticketbox-server-php.zip')) .pipe(gulp.dest(bases.root)); }); gulp.task('default', gulp.series('clean', 'collect', 'zip'));
var gulp = require('gulp'); var clean = require('gulp-clean'); var zip = require('gulp-zip'); var bases = { root: 'dist/' }; var paths = [ 'core/**', '!core/data', '!core/data/**/*', '!core/logs/**/*.txt', '!core/logs/**/*.pdf', '!core/logs/**/*.html', '!core/tests', '!core/tests/**/*', 'admin/**', '!admin/api/config', '!admin/api/config/**/*', 'boxoffice/**', '!boxoffice/api/config', '!boxoffice/api/config/**/*', 'customer/**', '!customer/api/config', '!customer/api/config/**/*', 'scanner/**', '!scanner/api/config', '!scanner/api/config/**/*', 'printer/**', '!printer/api/config', '!printer/api/config/**/*' ]; gulp.task('clean', function() { return gulp.src(bases.root) .pipe(clean({})); }); gulp.task('collect', function() { return gulp.src(paths, { base: './', dot: true }) .pipe(gulp.dest(bases.root)); }); gulp.task('zip', function() { return gulp.src(bases.root + '**') .pipe(zip('ticketbox-server-php.zip')) .pipe(gulp.dest(bases.root)); }); gulp.task('default', gulp.series('clean', 'collect', 'zip'));
Make sure that the error code is returned properly
from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest raise SystemExit(pytest.main(self.test_args)) setup( name='Flask-Pushrod', version='0.1-dev', url='http://github.com/dontcare4free/flask-pushrod', license='MIT', author='Nullable', author_email='[email protected]', description='An API microframework based on the idea of that the UI is just yet another endpoint', packages=['flask_pushrod', 'flask_pushrod.renderers'], zip_safe=False, platforms='any', install_requires=[ 'Werkzeug>=0.7', 'Flask>=0.9', ], tests_require=[ 'pytest>=2.2.4', ], cmdclass={'test': PyTest}, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest pytest.main(self.test_args) setup( name='Flask-Pushrod', version='0.1-dev', url='http://github.com/dontcare4free/flask-pushrod', license='MIT', author='Nullable', author_email='[email protected]', description='An API microframework based on the idea of that the UI is just yet another endpoint', packages=['flask_pushrod', 'flask_pushrod.renderers'], zip_safe=False, platforms='any', install_requires=[ 'Werkzeug>=0.7', 'Flask>=0.9', ], tests_require=[ 'pytest>=2.2.4', ], cmdclass={'test': PyTest}, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules', ], )
Clarify that self_chosen_courses == enrolled Fixes #75.
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_courses = forms.ModelMultipleChoiceField( label=_('Skriv inn fagene du tar nå'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autocomplete', attrs = { 'data-placeholder': _('Tast inn fagkode eller fagnavn'), # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) ) def __init__(self, *args, **kwargs): super(OptionsForm, self).__init__(*args, **kwargs) self.fields['self_chosen_courses'].help_text = _( 'Tast inn fagkode eller fagnavn for å legge til et nytt fag\ på hjemmesiden din.' ) class Meta: model = Options # The fields are further restricted in .admin.py fields = ('__all__')
from django import forms from django.utils.translation import ugettext_lazy as _ from dal import autocomplete from .models import Course, Options class OptionsForm(forms.ModelForm): """ A form solely used for autocompleting Courses in the admin, using django-autocomplete-light, """ self_chosen_courses = forms.ModelMultipleChoiceField( label=_('Skriv inn dine fag'), queryset=Course.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='semesterpage-course-autocomplete', attrs = { 'data-placeholder': _('Tast inn fagkode eller fagnavn'), # Only trigger autocompletion after 3 characters have been typed 'data-minimum-input-length': 3, }, ) ) def __init__(self, *args, **kwargs): super(OptionsForm, self).__init__(*args, **kwargs) self.fields['self_chosen_courses'].help_text = _( 'Tast inn fagkode eller fagnavn for å legge til et nytt fag\ på hjemmesiden din.' ) class Meta: model = Options # The fields are further restricted in .admin.py fields = ('__all__')
Fix ExpressionNode names that changed in django 1.5
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.BITAND: lambda x, y: x & y, ExpressionNode.BITOR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): return self.entity[qn(self.cols[node][1])]
from django.db.models.sql.expressions import SQLEvaluator from django.db.models.expressions import ExpressionNode OPERATION_MAP = { ExpressionNode.ADD: lambda x, y: x + y, ExpressionNode.SUB: lambda x, y: x - y, ExpressionNode.MUL: lambda x, y: x * y, ExpressionNode.DIV: lambda x, y: x / y, ExpressionNode.MOD: lambda x, y: x % y, ExpressionNode.AND: lambda x, y: x & y, ExpressionNode.OR: lambda x, y: x | y, } class ExpressionEvaluator(SQLEvaluator): def __init__(self, expression, query, entity, allow_joins=True): super(ExpressionEvaluator, self).__init__(expression, query, allow_joins) self.entity = entity ################################################## # Vistor methods for final expression evaluation # ################################################## def evaluate_node(self, node, qn, connection): values = [] for child in node.children: if hasattr(child, 'evaluate'): value = child.evaluate(self, qn, connection) else: value = child if value is not None: values.append(value) return OPERATION_MAP[node.connector](*values) def evaluate_leaf(self, node, qn, connection): return self.entity[qn(self.cols[node][1])]
Add a fancy log mode.
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path, "log") if not os.path.isdir(logdir): log("logger: creating log directory:", logdir) os.makedirs(logdir) logfile = os.path.join(logdir, "messages") else: logfile = os.path.join(analysis_path, "messages") # log a message to messages files (and to stdout by default) def log(*args, quiet=False, fancy=False): global logbuf # timestamp now = datetime.now() timestamp = str(now) + ": " # assemble message line msg = [] for a in args: msg.append(str(a)) if not fancy: logbuf.append(timestamp + " ".join(msg)) else: logbuf.append("") logbuf.append("############################################################################") logbuf.append("### " + timestamp + " ".join(msg)) logbuf.append("############################################################################") logbuf.append("") if logfile: # flush log buffer f = open(logfile, "a") for line in logbuf: f.write(line) f.write("\n") f.close() logbuf = [] if not quiet: print(*msg) # log quietly (log to file, but not to stdout) def qlog(*args): log(*args, quiet=True)
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path, "log") if not os.path.isdir(logdir): log("logger: creating log directory:", logdir) os.makedirs(logdir) logfile = os.path.join(logdir, "messages") else: logfile = os.path.join(analysis_path, "messages") # log a message to messages files (and to stdout by default) def log(*args, quiet=False): global logbuf # timestamp now = datetime.now() timestamp = str(now) + ": " # assemble message line msg = [] for a in args: msg.append(str(a)) logbuf.append(timestamp + " ".join(msg)) if logfile: # flush log buffer f = open(logfile, "a") for line in logbuf: f.write(line) f.write("\n") f.close() logbuf = [] if not quiet: print(*msg) # log quietly (log to file, but not to stdout) def qlog(*args): log(*args, quiet=True)
Make compilable under Java 1.5.
package org.junit.experimental.categories; import java.util.ArrayList; import java.util.List; import org.junit.internal.Classes; import org.junit.runner.FilterFactory; import org.junit.runner.FilterFactoryParams; import org.junit.runner.manipulation.Filter; /** * Implementation of FilterFactory for Category filtering. */ abstract class CategoryFilterFactory implements FilterFactory { /** * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given a * {@link FilterFactoryParams} argument. * * @param params Parameters needed to create the {@link Filter} * @throws FilterNotCreatedException */ public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e); } } /** * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given an array of classes. * * @param categories Category classes. */ protected abstract Filter createFilter(Class<?>... categories); private Class<?>[] parseCategories(String categories) throws ClassNotFoundException { List<Class<?>> categoryClasses = new ArrayList<Class<?>>(); for (String category : categories.split(",")) { Class<?> categoryClass = Classes.getClass(category); categoryClasses.add(categoryClass); } return categoryClasses.toArray(new Class[]{}); } }
package org.junit.experimental.categories; import java.util.ArrayList; import java.util.List; import org.junit.internal.Classes; import org.junit.runner.FilterFactory; import org.junit.runner.FilterFactoryParams; import org.junit.runner.manipulation.Filter; /** * Implementation of FilterFactory for Category filtering. */ abstract class CategoryFilterFactory implements FilterFactory { /** * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given a * {@link FilterFactoryParams} argument. * * @param params Parameters needed to create the {@link Filter} * @throws FilterNotCreatedException */ @Override public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e); } } /** * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given an array of classes. * * @param categories Category classes. */ protected abstract Filter createFilter(Class<?>... categories); private Class<?>[] parseCategories(String categories) throws ClassNotFoundException { List<Class<?>> categoryClasses = new ArrayList<Class<?>>(); for (String category : categories.split(",")) { Class<?> categoryClass = Classes.getClass(category); categoryClasses.add(categoryClass); } return categoryClasses.toArray(new Class[]{}); } }
Debug thing pushing to adw..
(function () { 'use strict'; angular .module('dpDataSelection') .component('dpDataSelectionFormatter', { bindings: { variables: '<', formatter: '@', useInline: '<' }, templateUrl: 'modules/data-selection/components/formatter/formatter.html', controller: DpDataSelectionFormatterController, controllerAs: 'vm' }); DpDataSelectionFormatterController.$inject = ['$filter']; function DpDataSelectionFormatterController ($filter) { let vm = this, variablesObj = {}; if (vm.formatter) { if (vm.variables.length === 1) { // Just pass the value (String) when there is only one variable vm.formattedValue = $filter(vm.formatter)(vm.variables[0].value); } else { // Pass all variables as an Object if there are more variables vm.variables.forEach(({key, value}) => variablesObj[key] = value); vm.formattedValue = $filter(vm.formatter)(variablesObj); } } else { // If there is no formatter; concatenate all values vm.formattedValue = vm.variables.map(variable => { return variable.value; }).join(' '); } console.log(formattedValue); } })();
(function () { 'use strict'; angular .module('dpDataSelection') .component('dpDataSelectionFormatter', { bindings: { variables: '<', formatter: '@', useInline: '<' }, templateUrl: 'modules/data-selection/components/formatter/formatter.html', controller: DpDataSelectionFormatterController, controllerAs: 'vm' }); DpDataSelectionFormatterController.$inject = ['$filter']; function DpDataSelectionFormatterController ($filter) { let vm = this, variablesObj = {}; if (vm.formatter) { if (vm.variables.length === 1) { // Just pass the value (String) when there is only one variable vm.formattedValue = $filter(vm.formatter)(vm.variables[0].value); } else { // Pass all variables as an Object if there are more variables vm.variables.forEach(({key, value}) => variablesObj[key] = value); vm.formattedValue = $filter(vm.formatter)(variablesObj); } } else { // If there is no formatter; concatenate all values vm.formattedValue = vm.variables.map(variable => { return variable.value; }).join(' '); } } })();
Move labels to api for future translation
'use strict'; var D3 = require('d3'); var Queries = require('../../helpers/queries'); var Utils = require('../../helpers/utils'); var OverviewParser = require('../../helpers/overview_parser'); exports.showPage = { handler: function(request, reply) { return reply.view('performance/overview'); } }; exports.getData = { handler: function(request, reply) { var sequelize = request.server.plugins.sequelize.db.sequelize; var region_code = request.query.region_code; var role = request.auth.credentials.role; var queryString = Queries.overviewPerformance(region_code, role); sequelize.query(queryString, { type: sequelize.QueryTypes.SELECT }).then(function(rows) { var final_dict; if (role === 'block') { final_dict = OverviewParser.block(rows); } if (role === 'district') { final_dict = OverviewParser.district(rows); } final_dict.config = { role: role, headers: ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'], labels: [ 'Muster roll closure to muster roll entry', 'Muster roll entry to wage list generation', 'Wage list generation to wage list signing', 'Wage list signing to FTO generation', 'FTO generation to first signature', 'First signature to second signature', 'Second signature to processed by bank', ], }; reply(final_dict); }); } };
'use strict'; var D3 = require('d3'); var Queries = require('../../helpers/queries'); var Utils = require('../../helpers/utils'); var OverviewParser = require('../../helpers/overview_parser'); exports.showPage = { handler: function(request, reply) { return reply.view('performance/overview'); } }; exports.getData = { handler: function(request, reply) { var sequelize = request.server.plugins.sequelize.db.sequelize; var region_code = request.query.region_code; var role = request.auth.credentials.role; var queryString = Queries.overviewPerformance(region_code, role); sequelize.query(queryString, { type: sequelize.QueryTypes.SELECT }).then(function(rows) { var final_dict; if (role === 'block') { final_dict = OverviewParser.block(rows); } if (role === 'district') { final_dict = OverviewParser.district(rows); } final_dict.config = { 'headers': ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'], 'role': role, }; reply(final_dict); }); } };
Update to work with new Geostore API
define([ 'Class', 'uri', 'bluebird', 'map/services/DataService' ], function(Class, UriTemplate, Promise, ds) { 'use strict'; var GET_REQUEST_ID = 'GeostoreService:get', SAVE_REQUEST_ID = 'GeostoreService:save'; var URL = window.gfw.config.GFW_API_HOST + '/geostore/{id}'; var GeostoreService = Class.extend({ get: function(id) { return new Promise(function(resolve, reject) { var url = new UriTemplate(URL).fillFromObject({id: id}); ds.define(GET_REQUEST_ID, { cache: {type: 'persist', duration: 1, unit: 'days'}, url: url, type: 'GET' }); var requestConfig = { resourceId: GET_REQUEST_ID, success: resolve }; ds.request(requestConfig); }); }, save: function(geojson) { return new Promise(function(resolve, reject) { var url = new UriTemplate(URL).fillFromObject({}); ds.define(SAVE_REQUEST_ID, { url: url, type: 'POST' }); var requestConfig = { resourceId: SAVE_REQUEST_ID, data: JSON.stringify(geojson), success: function(response) { resolve(response.id); }, error: reject }; ds.request(requestConfig); }); } }); return new GeostoreService(); });
define([ 'Class', 'uri', 'bluebird', 'map/services/DataService' ], function(Class, UriTemplate, Promise, ds) { 'use strict'; var GET_REQUEST_ID = 'GeostoreService:get', SAVE_REQUEST_ID = 'GeostoreService:save'; var URL = window.gfw.config.GFW_API_HOST + '/geostore/{id}'; var GeostoreService = Class.extend({ get: function(id) { return new Promise(function(resolve, reject) { var url = new UriTemplate(URL).fillFromObject({id: id}); ds.define(GET_REQUEST_ID, { cache: {type: 'persist', duration: 1, unit: 'days'}, url: url, type: 'GET' }); var requestConfig = { resourceId: GET_REQUEST_ID, success: resolve }; ds.request(requestConfig); }); }, save: function(geojson) { return new Promise(function(resolve, reject) { var url = new UriTemplate(URL).fillFromObject({}); ds.define(SAVE_REQUEST_ID, { url: url, type: 'POST' }); var params = { geojson: geojson }; var requestConfig = { resourceId: SAVE_REQUEST_ID, data: JSON.stringify(params), success: function(response) { resolve(response.id); }, error: reject }; ds.request(requestConfig); }); } }); return new GeostoreService(); });
Add missing comma in apimanagement mapper
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Paged Report records list representation. */ class RequestReportCollection extends Array { /** * Create a RequestReportCollection. * @member {number} [count] Total record count number across all pages. */ constructor() { super(); } /** * Defines the metadata of RequestReportCollection * * @returns {object} metadata of RequestReportCollection * */ mapper() { return { required: false, serializedName: 'RequestReportCollection', type: { name: 'Composite', className: 'RequestReportCollection', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'RequestReportRecordContractElementType', type: { name: 'Composite', className: 'RequestReportRecordContract' } } } }, count: { required: false, serializedName: 'count', type: { name: 'Number' } } } } }; } } module.exports = RequestReportCollection;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Paged Report records list representation. */ class RequestReportCollection extends Array { /** * Create a RequestReportCollection. * @member {number} [count] Total record count number across all pages. */ constructor() { super(); } /** * Defines the metadata of RequestReportCollection * * @returns {object} metadata of RequestReportCollection * */ mapper() { return { required: false, serializedName: 'RequestReportCollection', type: { name: 'Composite', className: 'RequestReportCollection', modelProperties: { value: { required: false, serializedName: '', type: { name: 'Sequence', element: { required: false, serializedName: 'RequestReportRecordContractElementType', type: { name: 'Composite', className: 'RequestReportRecordContract' } } } } count: { required: false, serializedName: 'count', type: { name: 'Number' } } } } }; } } module.exports = RequestReportCollection;
Allow to pass other things that string in args
<?php namespace DICIT; class ReferenceResolver { const CONTAINER_REFERENCE = '$container'; /** * * @var Container */ private $container; public function __construct(Container $container) { $this->container = $container; } public function resolve($reference) { if ($reference === static::CONTAINER_REFERENCE) { return $this->container; } if (!is_string($reference)) { return $reference; } $prefix = substr($reference, 0, 1); switch ($prefix) { case '@' : return $this->container->get(substr($reference, 1)); case '%' : return $this->container->getParameter(substr($reference, 1)); default : return $reference; } } public function resolveMany(array $references) { $convertedParameters = array(); foreach ($references as $reference) { $convertedValue = $this->resolve($reference); $convertedParameters[] = $convertedValue; } return $convertedParameters; } }
<?php namespace DICIT; class ReferenceResolver { const CONTAINER_REFERENCE = '$container'; /** * * @var Container */ private $container; public function __construct(Container $container) { $this->container = $container; } public function resolve($reference) { if ($reference === static::CONTAINER_REFERENCE) { return $this->container; } $prefix = substr($reference, 0, 1); switch ($prefix) { case '@' : $toReturn = $this->container->get(substr($reference, 1)); break; case '%' : $toReturn = $this->container->getParameter(substr($reference, 1)); break; default : $toReturn = $reference; break; } return $toReturn; } public function resolveMany(array $references) { $convertedParameters = array(); foreach ($references as $reference) { $convertedValue = $this->resolve($reference); $convertedParameters[] = $convertedValue; } return $convertedParameters; } }
Update geocoder interface to reflect that geocoders can send back results that destinations of type Rectangle or Cartesian3
/*global define*/ define([ './defineProperties', './DeveloperError' ], function( defineProperties, DeveloperError) { 'use strict'; /** * @typedef {Object} GeocoderResult * @property {String} displayName The display name for a location * @property {Rectangle|Cartesian3} destination The bounding box for a location */ /** * Provides geocoding through an external service. This type describes an interface and * is not intended to be used. * @alias GeocoderService * @constructor * * @see BingMapsGeocoderService */ function GeocoderService () { /** * Indicates whether this geocoding service is to be used for autocomplete. * * @type {boolean} * @default false */ this.autoComplete = false; } defineProperties(GeocoderService.prototype, { /** * The name of this service to be displayed next to suggestions * in case more than one geocoder is in use * @type {String} * */ displayName : { get : DeveloperError.throwInstantiationError } }); /** * @function * * @param {String} query The query to be sent to the geocoder service * @returns {Promise<GeocoderResult[]>} */ GeocoderService.prototype.geocode = DeveloperError.throwInstantiationError; return GeocoderService; });
/*global define*/ define([ './defineProperties', './DeveloperError' ], function( defineProperties, DeveloperError) { 'use strict'; /** * @typedef {Object} GeocoderResult * @property {String} displayName The display name for a location * @property {Rectangle} rectangle The bounding box for a location */ /** * Provides geocoding through an external service. This type describes an interface and * is not intended to be used. * @alias GeocoderService * @constructor * * @see BingMapsGeocoderService */ function GeocoderService () { /** * Indicates whether this geocoding service is to be used for autocomplete. * * @type {boolean} * @default false */ this.autoComplete = false; } defineProperties(GeocoderService.prototype, { /** * The name of this service to be displayed next to suggestions * in case more than one geocoder is in use * @type {String} * */ displayName : { get : DeveloperError.throwInstantiationError } }); /** * @function * * @param {String} query The query to be sent to the geocoder service * @returns {Promise<GeocoderResult[]>} */ GeocoderService.prototype.geocode = DeveloperError.throwInstantiationError; return GeocoderService; });
Fix name field change & deprecated sf3.4
<?php /** * @author: Gabriel BONDAZ <[email protected]> * @license: MIT */ namespace IDCI\Bundle\ExtraFormBundle\Form; use IDCI\Bundle\ExtraFormBundle\Form\Type\TagsType; use IDCI\Bundle\ExtraFormBundle\Model\ConfiguredType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ConfiguredTypeType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('blockPrefix') ->add('description') ->add('tags', TagsType::class, array( 'required' => false, 'url' => '/api/configured-extra-form-types-tags.json', )) ->add('configuration') ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults(array( 'data_class' => ConfiguredType::class, )) ; } /** * {@inheritdoc} * * @deprecated */ public function setDefaultOptions(OptionsResolver $resolver) { $this->configureOptions($resolver); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'idci_extraform_configured_type_type'; } }
<?php /** * @author: Gabriel BONDAZ <[email protected]> * @license: MIT */ namespace IDCI\Bundle\ExtraFormBundle\Form; use IDCI\Bundle\ExtraFormBundle\Model\ConfiguredType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ConfiguredTypeType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name') ->add('description') ->add('tags', 'extra_form_tags', array( 'required' => false, 'url' => '/api/configured-extra-form-types-tags.json', )) ->add('configuration') ; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefaults(array( 'data_class' => ConfiguredType::class, )) ; } /** * {@inheritdoc} * * @deprecated */ public function setDefaultOptions(OptionsResolver $resolver) { $this->configureOptions($resolver); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'idci_extraform_configured_type_type'; } }
Change priority of output converters
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <[email protected]> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace Imbo\Image\OutputConverter; /** * Basic output converter that supports gif/png/jpg. * * @author Mats Lindh <[email protected]> * @package Image\OutputConverters */ class Basic implements OutputConverterInterface { public function getSupportedFormatsWithCallbacks() { return [ [ 'mime' => 'image/jpeg', 'extension' => ['jpg', 'jpeg'], 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/png', 'extension' => 'png', 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/gif', 'extension' => 'gif', 'callback' => [$this, 'convert'], ], ]; } public function convert($imagick, $image, $extension, $mime = null) { try { $imagick->setImageFormat($extension); } catch (ImagickException $e) { throw new OutputConversionException($e->getMessage(), 400, $e); } $image->hasBeenTransformed(true); } }
<?php /** * This file is part of the Imbo package * * (c) Christer Edvartsen <[email protected]> * * For the full copyright and license information, please view the LICENSE file that was * distributed with this source code. */ namespace Imbo\Image\OutputConverter; /** * Basic output converter that supports gif/png/jpg. * * @author Mats Lindh <[email protected]> * @package Image\OutputConverters */ class Basic implements OutputConverterInterface { public function getSupportedFormatsWithCallbacks() { return [ [ 'mime' => 'image/png', 'extension' => 'png', 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/jpeg', 'extension' => ['jpg', 'jpeg'], 'callback' => [$this, 'convert'], ], [ 'mime' => 'image/gif', 'extension' => 'gif', 'callback' => [$this, 'convert'], ], ]; } public function convert($imagick, $image, $extension, $mime = null) { try { $imagick->setImageFormat($extension); } catch (ImagickException $e) { throw new OutputConversionException($e->getMessage(), 400, $e); } } }
Clear message textbox after message is sent.
var CHAT_SERVER = "http://localhost:7000" var DEFAULT_USERNAME = "Guest"; $(document).ready(function(){ var socket = io.connect(CHAT_SERVER); socket.on('welcome', showGreetings); socket.on('message', showIncomingMessage); socket.on('info', showSystemInfo); addWaterMark(); sendButtonOnClick(); changeButtonOnClick(); function showGreetings(msg){ $("#title").text(msg['greetings']); } function showIncomingMessage(msg){ $("#messages").append("<div class='in-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function addWaterMark(){ $("#outgoing-message").watermark("Enter your message here"); } function sendButtonOnClick(){ $("#send").click(function(){ var msg = $("#outgoing-message").val(); showOutgoingMessage(msg); $("#outgoing-message").val(''); socket.emit('message', msg); }); } function showOutgoingMessage(msg){ $("#messages").append("<div class='out-message'>Me: " + msg + "</div>"); } function showSystemInfo(msg){ $("#messages").append("<div class='info-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function changeButtonOnClick(){ $("#change").click(function(){ var username = $("#username").val(); if(!username) username = DEFAULT_USERNAME; registerUsername(username); }); } function registerUsername(username){ socket.emit('user-join', username); } });
var CHAT_SERVER = "http://localhost:7000" var DEFAULT_USERNAME = "Guest"; $(document).ready(function(){ var socket = io.connect(CHAT_SERVER); socket.on('welcome', showGreetings); socket.on('message', showIncomingMessage); socket.on('info', showSystemInfo); addWaterMark(); sendButtonOnClick(); changeButtonOnClick(); function showGreetings(msg){ $("#title").text(msg['greetings']); } function showIncomingMessage(msg){ $("#messages").append("<div class='in-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function addWaterMark(){ $("#outgoing-message").watermark("Enter your message here"); } function sendButtonOnClick(){ $("#send").click(function(){ var msg = $("#outgoing-message").val(); showOutgoingMessage(msg); socket.emit('message', msg); }); } function showOutgoingMessage(msg){ $("#messages").append("<div class='out-message'>Me: " + msg + "</div>"); } function showSystemInfo(msg){ $("#messages").append("<div class='info-message'>" + msg['msgOwner'] + ": " + msg['msgContent'] + "</div>"); } function changeButtonOnClick(){ $("#change").click(function(){ var username = $("#username").val(); if(!username) username = DEFAULT_USERNAME; registerUsername(username); }); } function registerUsername(username){ socket.emit('user-join', username); } });
test: Use the correct option when dumping dependent libraries.
from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: pass else: try: binary = subprocess.check_output(["which", exe]).decode('utf8').strip() except: pass if binary is None: print( "Skipping scenario", context.scenario, "(executable %s not found)" % exe, file = sys.stderr ) context.scenario.skip("The executable '%s' is not present" % exe) else: print( "Found executable '%s' at '%s'" % (exe, binary), file = sys.stderr ) @then('{exe} is a static executable') def step_impl(ctx, exe): if sys.platform.lower().startswith('darwin'): context.scenario.skip("Static runtime linking is not supported on OS X") if sys.platform.startswith('win'): lines = subprocess.check_output(["dumpbin.exe", "/DEPENDENTS", exe]).decode('utf8').split('\r\n') for line in lines: if 'msvcrt' in line.lower(): assert False, 'Found MSVCRT: %s' % line else: out = subprocess.check_output(["file", exe]).decode('utf8') assert 'statically linked' in out, "Not a static executable: %s" % out
from __future__ import print_function import sys import subprocess import os @given('a system executable {exe}') def step_impl(context, exe): binary = None if sys.platform.startswith('win'): try: binary = subprocess.check_output(["where", exe]).decode('utf8').strip() except: pass else: try: binary = subprocess.check_output(["which", exe]).decode('utf8').strip() except: pass if binary is None: print( "Skipping scenario", context.scenario, "(executable %s not found)" % exe, file = sys.stderr ) context.scenario.skip("The executable '%s' is not present" % exe) else: print( "Found executable '%s' at '%s'" % (exe, binary), file = sys.stderr ) @then('{exe} is a static executable') def step_impl(ctx, exe): if sys.platform.lower().startswith('darwin'): context.scenario.skip("Static runtime linking is not supported on OS X") if sys.platform.startswith('win'): lines = subprocess.check_output(["dumpbin.exe", exe]).decode('utf8').split('\r\n') for line in lines: if 'msvcrt' in line.lower(): assert False, 'Found MSVCRT: %s' % line else: out = subprocess.check_output(["file", exe]).decode('utf8') assert 'statically linked' in out, "Not a static executable: %s" % out
Add coveralls to karma plugins list.
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.min.js', 'app/bower_components/angular-ui-router/release/angular-ui-router.min.js', 'app/bower_components/angular-resource/angular-resource.min.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/ng-table/dist/ng-table.min.js', 'app/bower_components/spin.js/spin.js', 'app/bower_components/angular-loading/angular-loading.min.js', 'app/search/**/*.js', 'app/services/**/*.js' ], preprocessors: { 'app/search/*.js': ['coverage', 'coveralls'], 'app/services/*.js': ['coverage', 'coveralls'] }, reporters: ['progress', 'coverage'], coverageReporter: { type: 'lcov', dir: 'coverage/' }, autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'coveralls', 'karma-coverage' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.min.js', 'app/bower_components/angular-ui-router/release/angular-ui-router.min.js', 'app/bower_components/angular-resource/angular-resource.min.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/bower_components/ng-table/dist/ng-table.min.js', 'app/bower_components/spin.js/spin.js', 'app/bower_components/angular-loading/angular-loading.min.js', 'app/search/**/*.js', 'app/services/**/*.js' ], preprocessors: { 'app/search/*.js': ['coverage', 'coveralls'], 'app/services/*.js': ['coverage', 'coveralls'] }, reporters: ['progress', 'coverage'], coverageReporter: { type: 'lcov', dir: 'coverage/' }, autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter', 'karma-coverage' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
Remove import from java.lang package
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.nelen_schuurmans.aquo; import org.apache.log4j.Logger; /** * * @author [email protected] */ public class Aquo { private static final Logger logger = Logger.getLogger(Aquo.class); private static String[] classNames = { "nl.nelen_schuurmans.aquo.CompartmentSynchronizer", "nl.nelen_schuurmans.aquo.MeasuringDeviceSynchronizer", "nl.nelen_schuurmans.aquo.MeasuringMethodSynchronizer", "nl.nelen_schuurmans.aquo.ParameterSynchronizer", "nl.nelen_schuurmans.aquo.ProcessingMethodSynchronizer", "nl.nelen_schuurmans.aquo.ReferenceFrameSynchronizer", "nl.nelen_schuurmans.aquo.UnitSynchronizer" }; public static void main(String[] args) { for (String className : classNames) { try { Object object = Class.forName(className).newInstance(); Synchronizer synchronizer = (Synchronizer) object; synchronizer.synchronize(); } catch (Exception ex) { logger.error(ex); } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.nelen_schuurmans.aquo; import java.lang.Class; import org.apache.log4j.Logger; /** * * @author [email protected] */ public class Aquo { private static final Logger logger = Logger.getLogger(Aquo.class); private static String[] classNames = { "nl.nelen_schuurmans.aquo.CompartmentSynchronizer", "nl.nelen_schuurmans.aquo.MeasuringDeviceSynchronizer", "nl.nelen_schuurmans.aquo.MeasuringMethodSynchronizer", "nl.nelen_schuurmans.aquo.ParameterSynchronizer", "nl.nelen_schuurmans.aquo.ProcessingMethodSynchronizer", "nl.nelen_schuurmans.aquo.ReferenceFrameSynchronizer", "nl.nelen_schuurmans.aquo.UnitSynchronizer" }; public static void main(String[] args) { for (String className : classNames) { try { Object object = Class.forName(className).newInstance(); Synchronizer synchronizer = (Synchronizer) object; synchronizer.synchronize(); } catch (Exception ex) { logger.error(ex); } } } }
Remove include header from entry view
@extends('admin.layout.master') @section('content') <table class="table table-hover"> <thead> <tr> <th>Created at</th> <th>Name</th> <th>Phone</th> <th>Email</th> <th>Video</th> <th>Article</th> <th>Photos</th> </tr> </thead> <tbody> @foreach ($entries as $entry) <tr> <td>{{ $entry->created_at->format('F d, Y h:ia') }}</td> <td>{{ $entry->name }}</td> <td>{{ $entry->phone }}</td> <td>{{ $entry->email }}</td> <td>{{ $entry->video }}</td> <td>{{ $entry->article['content'] }}</td> <td> @foreach ($entry->pictures as $picture) {{ $picture }} @endforeach </td> </tr> @endforeach </tbody> </table> @stop
@extends('admin.layout.master') @section('content') @include('admin.layout.header') <table class="table table-hover"> <thead> <tr> <th>Created at</th> <th>Name</th> <th>Phone</th> <th>Email</th> <th>Video</th> <th>Article</th> <th>Photos</th> </tr> </thead> <tbody> @foreach ($entries as $entry) <tr> <td>{{ $entry->created_at->format('F d, Y h:ia') }}</td> <td>{{ $entry->name }}</td> <td>{{ $entry->phone }}</td> <td>{{ $entry->email }}</td> <td>{{ $entry->video }}</td> <td>{{ $entry->article['content'] }}</td> <td> @foreach ($entry->pictures as $picture) {{ $picture }} @endforeach </td> </tr> @endforeach </tbody> </table> @stop
Change parameters of updateProjects service
<?php namespace AppBundle\API\Edit; use AppBundle\API\Webservice; use AppBundle\AppBundle; use AppBundle\Entity\FennecUser; use AppBundle\Entity\WebuserData; use AppBundle\Service\DBVersion; use Symfony\Component\HttpFoundation\ParameterBag; class UpdateProject { private $manager; /** * UpdateProject constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @inheritdoc */ public function execute($projectId, $biom, FennecUser $user = null) { if($biom === null || $project_id === null){ return array('error' => 'Missing parameter "biom" or "project_id"'); } if($user == null){ return array('error' => 'User not logged in'); } if($user === null){ return array('error' => 'Could not update project. Not found for user.'); } $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $projectId)); if($project === null){ return array('error' => 'Could not update project. Not found for user.'); } $project->setProject(json_decode($biom, true)); $this->manager->persist($project); $this->manager->flush(); return array('error' => null); } }
<?php namespace AppBundle\API\Edit; use AppBundle\API\Webservice; use AppBundle\AppBundle; use AppBundle\Entity\FennecUser; use AppBundle\Entity\WebuserData; use AppBundle\Service\DBVersion; use Symfony\Component\HttpFoundation\ParameterBag; class UpdateProject { private $manager; /** * UpdateProject constructor. * @param $dbversion */ public function __construct(DBVersion $dbversion) { $this->manager = $dbversion->getEntityManager(); } /** * @inheritdoc */ public function execute(FennecUser $user = null) { $project_id = $_REQUEST['project_id']; $biom = $_REQUEST['biom']; if($biom === null || $project_id === null){ return array('error' => 'Missing parameter "biom" or "project_id"'); } if($user == null){ return array('error' => 'User not logged in'); } if($user === null){ return array('error' => 'Could not update project. Not found for user.'); } $project = $this->manager->getRepository(WebuserData::class)->findOneBy(array('webuser' => $user, 'webuserDataId' => $project_id)); if($project === null){ return array('error' => 'Could not update project. Not found for user.'); } $project->setProject(json_decode($biom, true)); $this->manager->persist($project); $this->manager->flush(); return array('error' => null); } }
Update to newest snapshot, including a few changes stemming from this.
package dk.statsbiblioteket.medieplatform.newspaper.statistics; import java.util.Arrays; import java.util.List; import java.util.Properties; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent { private Logger log = LoggerFactory.getLogger(getClass()); private Properties properties; protected StatisticsRunnableComponent(Properties properties) { super(properties); this.properties = properties; } @Override public String getEventID() { return "Statistics_Generated"; } @Override public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception { log.info("Starting statistics generation for '{}'", batch.getFullID()); List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch), statisticGenerator, resultCollector); eventRunner.run(); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } }
package dk.statsbiblioteket.medieplatform.newspaper.statistics; import java.util.Arrays; import java.util.List; import java.util.Properties; import dk.statsbiblioteket.medieplatform.autonomous.Batch; import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector; import dk.statsbiblioteket.medieplatform.autonomous.TreeProcessorAbstractRunnableComponent; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.EventRunner; import dk.statsbiblioteket.medieplatform.autonomous.iterator.eventhandlers.TreeEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StatisticsRunnableComponent extends TreeProcessorAbstractRunnableComponent { private Logger log = LoggerFactory.getLogger(getClass()); private Properties properties; protected StatisticsRunnableComponent(Properties properties) { super(properties); this.properties = properties; } @Override public String getEventID() { return "Statistics_Generated"; } @Override public void doWorkOnBatch(Batch batch, ResultCollector resultCollector) throws Exception { log.info("Starting statistics generation for '{}'", batch.getFullID()); List<TreeEventHandler> statisticGenerator = Arrays.asList(new TreeEventHandler[] { new StatisticGenerator(batch, properties) }); EventRunner eventRunner = new EventRunner(createIterator(batch)); eventRunner.runEvents(statisticGenerator, resultCollector); log.info("Done generating statistics '{}', success: {}", batch.getFullID(), resultCollector.isSuccess()); } }
Disable more interaction with the map
import api from '../api'; import style from './style'; export default () => { let map = new google.maps.Map(document.getElementsByClassName('map')[0], { center: {lat: -34.397, lng: 150.644}, zoom: 3, disableDefaultUI: true, disableDoubleClickZoom: true, draggable: false, scrollwheel: false, styles: style, }); api.getDirections(locations.from, locations.to) .then(result => { let path = google.maps.geometry.encoding.decodePath(result); new google.maps.Polyline({ clickable: false, map: map, path: path, strokeColor: "#d80000", strokeWeight: 7, }); var center = new google.maps.LatLngBounds(); for (var i = 0; i < path.length; i++) { center.extend(path[i]); } $('.map').show(); $('.map-loading').hide(); google.maps.event.trigger(map, 'resize'); map.fitBounds(center); map.setZoom(5); }) .catch(() => { $('.map-container').hide(); }); };
import api from '../api'; import style from './style'; export default () => { let map = new google.maps.Map(document.getElementsByClassName('map')[0], { center: {lat: -34.397, lng: 150.644}, zoom: 3, disableDefaultUI: true, scrollwheel: false, styles: style, }); api.getDirections(locations.from, locations.to) .then(result => { let path = google.maps.geometry.encoding.decodePath(result); new google.maps.Polyline({ map: map, path: path, strokeColor: "#d80000", strokeWeight: 7, }); var center = new google.maps.LatLngBounds(); for (var i = 0; i < path.length; i++) { center.extend(path[i]); } $('.map').show(); $('.map-loading').hide(); google.maps.event.trigger(map, 'resize'); map.fitBounds(center); map.setZoom(5); }) .catch(() => { $('.map-container').hide(); }); };
Use Amplify to handle modal.andLoad and modal.onUnload
/* * Place copyright or other info here... */ (function(global, $){ // Define core var codiad = global.codiad, scripts= document.getElementsByTagName('script'), path = scripts[scripts.length-1].src.split('?')[0], curpath = path.split('/').slice(0, -1).join('/')+'/'; // Instantiates plugin $(function() { codiad.modalAnimations.init(); }); $.loadScript( curpath + 'jquery.transit.js' ); codiad.modalAnimations = { // Allows relative `this.path` linkage path: curpath, init: function() { var duration = 300; amplify.subscribe( 'modal.onLoad', function(){ $( "#modal" ).transit({ scale: 0, display: 'block', opacity: 0, perspective: '500px', rotateX: "90deg", duration: 0, }).transit({ scale: 1, opacity: 1, perspective: '1000px', rotateX: "0deg", duration: duration, easing: 'easeOutBack' }); return false; }); amplify.subscribe( 'modal.onUnload', function(){ $( "#modal" ).transit({ scale: 0, opacity: 0, perspective: '500px', rotateX: "90deg", duration: duration, }); return false; }); }, }; })(this, jQuery);
/* * Place copyright or other info here... */ (function(global, $){ // Define core var codiad = global.codiad, scripts= document.getElementsByTagName('script'), path = scripts[scripts.length-1].src.split('?')[0], curpath = path.split('/').slice(0, -1).join('/')+'/'; // Instantiates plugin $(function() { codiad.modalAnimations.init(); }); $.loadScript( curpath + 'jquery.transit.js' ); codiad.modalAnimations = { // Allows relative `this.path` linkage path: curpath, init: function() { var duration = 300; codiad.modal.onLoadAnimation = function(){ $( "#modal" ).transit({ scale: 0, display: 'block', opacity: 0, perspective: '500px', rotateX: "90deg", duration: 0, }).transit({ scale: 1, opacity: 1, perspective: '1000px', rotateX: "0deg", duration: duration, easing: 'easeOutBack' }); }; codiad.modal.onUnloadAnimation = function(){ $( "#modal" ).transit({ scale: 0, opacity: 0, perspective: '500px', rotateX: "90deg", duration: duration, }); }; }, }; })(this, jQuery);
Change help link to help.are.na
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Link from 'react/components/UserDropdown/components/Link'; const SmallLink = styled(Link).attrs({ f: 2, fontWeight: 'normal', })` `; export default class SecondaryLinks extends Component { static propTypes = { isPremium: PropTypes.bool.isRequired, } signOut = () => { window.localStorage.clear(); window.location.href = '/me/sign_out'; } render() { const { isPremium } = this.props; return ( <div> <SmallLink href="/settings"> Settings </SmallLink> <SmallLink href="/tools"> More tools </SmallLink> <SmallLink href="http://help.are.na"> Help / FAQs </SmallLink> <SmallLink href="/tools/send-invitation"> Send an invite </SmallLink> <SmallLink href="/about"> About </SmallLink> {!isPremium && <SmallLink color="state.premium" href="/pricing"> Premium features </SmallLink> } <SmallLink onClick={this.signOut}> Log Out </SmallLink> </div> ); } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import Link from 'react/components/UserDropdown/components/Link'; const SmallLink = styled(Link).attrs({ f: 2, fontWeight: 'normal', })` `; export default class SecondaryLinks extends Component { static propTypes = { isPremium: PropTypes.bool.isRequired, } signOut = () => { window.localStorage.clear(); window.location.href = '/me/sign_out'; } render() { const { isPremium } = this.props; return ( <div> <SmallLink href="/settings"> Settings </SmallLink> <SmallLink href="/tools"> More tools </SmallLink> <SmallLink href="/faqs"> Help / FAQs </SmallLink> <SmallLink href="/tools/send-invitation"> Send an invite </SmallLink> <SmallLink href="/about"> About </SmallLink> {!isPremium && <SmallLink color="state.premium" href="/pricing"> Premium features </SmallLink> } <SmallLink onClick={this.signOut}> Log Out </SmallLink> </div> ); } }
Add missing function getName to the interface
<?php /** * @author: Thomas Prelot <[email protected]> * @license: MIT */ namespace IDCI\Bundle\StepBundle\Step; use IDCI\Bundle\StepBundle\Step\StepInterface; interface StepInterface { /** * Get the configuration. * * @return array The configuration. */ public function getConfiguration(); /** * Set the configuration options. * * @param array $options The configuration options. * * @return StepInterface. */ public function setOptions($options); /** * Get the configuration options. * * @return array The configuration options. */ public function getOptions(); /** * Returns the step name. * * @return string The step name. */ public function getName(); /** * Returns a boolean to indicate That this step was define as a first step * * @return boolean. */ public function isFirst(); /** * Returns the step types used to construct the step. * * @return StepTypeInterface The step's type. */ public function getType(); /** * Returns the step data. * * @return array|null The step's data. */ public function getData(); /** * Returns the form pre step content. * * @return string|null The content. */ public function getPreStepContent(); /** * Returns the step data type mapping. * * @return array The data type mapping. */ public function getDataTypeMapping(); }
<?php /** * @author: Thomas Prelot <[email protected]> * @license: MIT */ namespace IDCI\Bundle\StepBundle\Step; use IDCI\Bundle\StepBundle\Step\StepInterface; interface StepInterface { /** * Get the configuration. * * @return array The configuration. */ public function getConfiguration(); /** * Set the configuration options. * * @param array $options The configuration options. * * @return StepInterface. */ public function setOptions($options); /** * Get the configuration options. * * @return array The configuration options. */ public function getOptions(); /** * Returns a boolean to indicate That this step was define as a first step * * @return boolean. */ public function isFirst(); /** * Returns the step types used to construct the step. * * @return StepTypeInterface The step's type. */ public function getType(); /** * Returns the step data. * * @return array|null The step's data. */ public function getData(); /** * Returns the form pre step content. * * @return string|null The content. */ public function getPreStepContent(); /** * Returns the step data type mapping. * * @return array The data tpe mapping. */ public function getDataTypeMapping(); }
Fix check on error when getting camera picture
Template.messageInput.events({ 'submit form': function (event, template) { event.preventDefault(); var messageInput = event.currentTarget.elements['message']; if (messageInput.value === "") return; Messages.insert({ createdAt: new Date(), author: Meteor.user().username, body: messageInput.value }); messageInput.value = ""; Session.set("autoScroll", true); scrollToBottom(); }, 'focus input[name="message"]': function () { if (Session.get("autoScroll")) { if (Meteor.isCordova) { // Give some time for the device to open keyboard... // Should be listening to keyboard events... Meteor.setTimeout(function () { scrollToBottom(); }, 200); } else { scrollToBottom(); } } }, 'click #login-welcome': function () { $("#login-sign-in-link").click(); }, 'click #take-picture': function () { MeteorCamera.getPicture({correctOrientation: true}, function (error, data) { if (!error) { Messages.insert({ createdAt: new Date(), author: Meteor.user().username, picture: resizeImage(data) }); } Session.set("autoScroll", true); }); } });
Template.messageInput.events({ 'submit form': function (event, template) { event.preventDefault(); var messageInput = event.currentTarget.elements['message']; if (messageInput.value === "") return; Messages.insert({ createdAt: new Date(), author: Meteor.user().username, body: messageInput.value }); messageInput.value = ""; Session.set("autoScroll", true); scrollToBottom(); }, 'focus input[name="message"]': function () { if (Session.get("autoScroll")) { if (Meteor.isCordova) { // Give some time for the device to open keyboard... // Should be listening to keyboard events... Meteor.setTimeout(function () { scrollToBottom(); }, 200); } else { scrollToBottom(); } } }, 'click #login-welcome': function () { $("#login-sign-in-link").click(); }, 'click #take-picture': function () { MeteorCamera.getPicture({correctOrientation: true}, function (error, data) { Messages.insert({ createdAt: new Date(), author: Meteor.user().username, picture: resizeImage(data) }) Session.set("autoScroll", true); }); } });
Check if extension is .js before prepending
"use strict"; var ConcatSource = require('webpack-sources/lib/ConcatSource'); var fs = require('fs'); class PrependPlugin { constructor(args) { if (typeof args !== 'object') { throw new TypeError('Argument "args" must be an object.'); } this.filePath = args.hasOwnProperty('filePath') ? args.filePath : null; } apply(compiler) { const prependFile = (compilation, fileName) => compilation.assets[fileName] = new ConcatSource( fs.readFileSync(this.filePath, 'utf8'), compilation.assets[fileName] ); const wrapChunks = (compilation, chunks) => chunks.forEach(chunk => { if (chunk.hasRuntime() && chunk.name) { chunk.files.forEach(fileName => { if (fileName.match(/\.js$/)) { prependFile(compilation, fileName) } }); } }); if (this.filePath) { compiler.plugin('compilation', compilation => compilation.plugin('optimize-chunk-assets', (chunks, done) => { wrapChunks(compilation, chunks); done(); }) ); } } } module.exports = PrependPlugin;
"use strict"; var ConcatSource = require('webpack-sources/lib/ConcatSource'); var fs = require('fs'); class PrependPlugin { constructor(args) { if (typeof args !== 'object') { throw new TypeError('Argument "args" must be an object.'); } this.filePath = args.hasOwnProperty('filePath') ? args.filePath : null; } apply(compiler) { const prependFile = (compilation, fileName) => compilation.assets[fileName] = new ConcatSource( fs.readFileSync(this.filePath, 'utf8'), compilation.assets[fileName] ); const wrapChunks = (compilation, chunks) => chunks.forEach(chunk => { if (chunk.hasRuntime() && chunk.name) { chunk.files.forEach(fileName => prependFile(compilation, fileName)); } }); if (this.filePath) { compiler.plugin('compilation', compilation => compilation.plugin('optimize-chunk-assets', (chunks, done) => { wrapChunks(compilation, chunks); done(); }) ); } } } module.exports = PrependPlugin;
Fix test See company details page
<?php namespace Test; use App\User; use App\Company; use TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyDetailsTest extends TestCase { use DatabaseTransactions; public function test_responds_404_if_id_does_not_exist() { $badId = '0'; $user = factory(User::class, 'admin')->create(); $this->actingAs($user) ->get('/company/'.$badId) ->see('errors.not-found') ->see('Not found.') ->assertResponseStatus(404); } public function test_company_details_can_be_seen() { $user = factory(User::class, 'admin')->create(); $user->companies()->save($company = factory(Company::class)->create()); $this->actingAs($user) ->get('/company/'.$company->id) ->see($company->id) ->assertResponseStatus(200); } public function test_company_details_of_other_user_can_be_seen() { $userOne = factory(User::class, 'admin')->create(); $userTwo = factory(User::class, 'admin')->create(); $userTwo->companies()->save($companyTwo = factory(Company::class)->create()); $this->actingAs($userOne) ->get('/company/'.$companyTwo->id) ->assertResponseStatus(200); } }
<?php namespace Test; use App\User; use App\Company; use TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CompanyDetailsTest extends TestCase { use DatabaseTransactions; public function test_responds_404_if_id_does_not_exist() { $badId = '0'; $user = factory(User::class, 'admin')->create(); $this->actingAs($user) ->get('/company/'.$badId) ->see('errors.not-found') ->see('Not found.') ->assertResponseStatus(404); } public function test_company_details_can_be_seen() { $user = factory(User::class, 'admin')->create(); $user->companies()->save($company = factory(Company::class)->create()); $this->actingAs($user) ->get('/company/'.$company->id) ->assertResponseStatus(200) ->see($company->id); } public function test_company_details_of_other_user_can_be_seen() { $userOne = factory(User::class, 'admin')->create(); $userTwo = factory(User::class, 'admin')->create(); $userTwo->companies()->save($companyTwo = factory(Company::class)->create()); $this->actingAs($userOne) ->get('/company/'.$companyTwo->id) ->assertResponseStatus(200); } }
Enforce requirement of email field on member invite
from __future__ import absolute_import from django import forms from django.db import transaction, IntegrityError from sentry.models import ( AuditLogEntry, AuditLogEntryEvent, OrganizationMember ) class InviteOrganizationMemberForm(forms.ModelForm): # override this to ensure the field is required email = forms.EmailField() class Meta: fields = ('email', 'role') model = OrganizationMember def save(self, actor, organization, ip_address): om = super(InviteOrganizationMemberForm, self).save(commit=False) om.organization = organization try: existing = OrganizationMember.objects.filter( organization=organization, user__email__iexact=om.email, )[0] except IndexError: pass else: return existing, False sid = transaction.savepoint(using='default') try: om.save() except IntegrityError: transaction.savepoint_rollback(sid, using='default') return OrganizationMember.objects.get( email__iexact=om.email, organization=organization, ), False transaction.savepoint_commit(sid, using='default') AuditLogEntry.objects.create( organization=organization, actor=actor, ip_address=ip_address, target_object=om.id, event=AuditLogEntryEvent.MEMBER_INVITE, data=om.get_audit_log_data(), ) om.send_invite_email() return om, True
from __future__ import absolute_import from django import forms from django.db import transaction, IntegrityError from sentry.models import ( AuditLogEntry, AuditLogEntryEvent, OrganizationMember ) class InviteOrganizationMemberForm(forms.ModelForm): class Meta: fields = ('email', 'role') model = OrganizationMember def save(self, actor, organization, ip_address): om = super(InviteOrganizationMemberForm, self).save(commit=False) om.organization = organization try: existing = OrganizationMember.objects.filter( organization=organization, user__email__iexact=om.email, )[0] except IndexError: pass else: return existing, False sid = transaction.savepoint(using='default') try: om.save() except IntegrityError: transaction.savepoint_rollback(sid, using='default') return OrganizationMember.objects.get( email__iexact=om.email, organization=organization, ), False transaction.savepoint_commit(sid, using='default') AuditLogEntry.objects.create( organization=organization, actor=actor, ip_address=ip_address, target_object=om.id, event=AuditLogEntryEvent.MEMBER_INVITE, data=om.get_audit_log_data(), ) om.send_invite_email() return om, True
Stop using weak references to keep track of subscribers It turns out that we don't actually reference them elsewhere in some cases where they're still needed, so the UI was pretty much completely non-functional in the emulator.
package com.alangpierce.lambdacalculusplayground.drag; import android.view.MotionEvent; import android.view.View; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import autovalue.shaded.com.google.common.common.collect.Maps; import rx.Observable; import rx.Subscriber; public class TouchObservableManagerImpl implements TouchObservableManager { private WeakHashMap<View, Observable<MotionEvent>> cachedEventObservables = new WeakHashMap<>(); @Override public Observable<MotionEvent> touchObservableForView(View view) { if (!cachedEventObservables.containsKey(view)) { final Set<Subscriber<? super MotionEvent>> subscribers = Collections.newSetFromMap( Maps.<Subscriber<? super MotionEvent>, Boolean>newConcurrentMap()); cachedEventObservables.put(view, Observable.create( (Observable.OnSubscribe<MotionEvent>) subscribers::add)); view.setOnTouchListener((v, event) -> { // Copy the list of subscribers first, since onNext might end up modifying the list. // TODO: Handle unsubscribe and actually unsubscribe when necessary. List<Subscriber<? super MotionEvent>> subscriberList = ImmutableList.copyOf(subscribers); for (Subscriber<? super MotionEvent> subscriber : subscriberList) { subscriber.onNext(event); } return true; }); } return cachedEventObservables.get(view); } }
package com.alangpierce.lambdacalculusplayground.drag; import android.view.MotionEvent; import android.view.View; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import rx.Observable; import rx.Subscriber; public class TouchObservableManagerImpl implements TouchObservableManager { private WeakHashMap<View, Observable<MotionEvent>> cachedEventObservables = new WeakHashMap<>(); @Override public Observable<MotionEvent> touchObservableForView(View view) { if (!cachedEventObservables.containsKey(view)) { final Map<Subscriber<? super MotionEvent>, Void> subscribers = Collections.synchronizedMap(new WeakHashMap<>()); cachedEventObservables.put( view, Observable.create(observer -> subscribers.put(observer, null))); view.setOnTouchListener((v, event) -> { // Copy the list of subscribers first, since onNext might end up modifying the list. // TODO: Handle unsubscribe and actually unsubscribe when necessary. List<Subscriber<? super MotionEvent>> subscriberList = ImmutableList.copyOf(subscribers.keySet()); for (Subscriber<? super MotionEvent> subscriber : subscriberList) { subscriber.onNext(event); } return true; }); } return cachedEventObservables.get(view); } }
Fix import issue in h5py.py
"""Objects for datasets serialized in HDF5 format (.h5).""" import warnings try: import h5py except ImportError: warnings.warn("Could not import h5py") from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix class HDF5Dataset(DenseDesignMatrix): """Dense dataset loaded from an HDF5 file.""" def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs): """ Loads data and labels from HDF5 file. Parameters ---------- filename: str HDF5 file name. X: str Key into HDF5 file for dataset design matrix. topo_view: str Key into HDF5 file for topological view of dataset. y: str Key into HDF5 file for dataset targets. kwargs: dict Keyword arguments passed to `DenseDesignMatrix`. """ with h5py.File(filename) as f: if X is not None: X = f[X][:] if topo_view is not None: topo_view = f[topo_view][:] if y is not None: y = f[y][:] super(HDF5Dataset, self).__init__(X=X, topo_view=topo_view, y=y, **kwargs)
"""Objects for datasets serialized in HDF5 format (.h5).""" import h5py from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix class HDF5Dataset(DenseDesignMatrix): """Dense dataset loaded from an HDF5 file.""" def __init__(self, filename, X=None, topo_view=None, y=None, **kwargs): """ Loads data and labels from HDF5 file. Parameters ---------- filename: str HDF5 file name. X: str Key into HDF5 file for dataset design matrix. topo_view: str Key into HDF5 file for topological view of dataset. y: str Key into HDF5 file for dataset targets. kwargs: dict Keyword arguments passed to `DenseDesignMatrix`. """ with h5py.File(filename) as f: if X is not None: X = f[X][:] if topo_view is not None: topo_view = f[topo_view][:] if y is not None: y = f[y][:] super(HDF5Dataset, self).__init__(X=X, topo_view=topo_view, y=y, **kwargs)
Fix bug for IE (firefox can deal with anonymous node for null, not ie) git-svn-id: 4cd2d1688610a87757c9f4de95975a674329c79f@740 b8ca103b-dd03-488c-9448-c80b36131af2
var XML = { serialize:function(el){ if(window.XMLSerializer) return (new XMLSerializer()).serializeToString(el); return el.xml; }, makesoup:function(xml_str){ return $n("div").set('html', xml_str);//.getFirst(); //dont <null><br/><box/></null> } }; function transformer_xslt(xsl_lnk){ this.xsl_xml = xsl_lnk; if(Browser.Engine.webkit){ // Safari do not support transformToFragment else var liste = this.xsl_xml.getElementsByTagName("output"); liste.item(0).setAttribute("method", "html"); } this.xsl_xml.resolveExternals = true; this.proc = false; this.out = function (xml_doc){ if(window.XSLTProcessor){ if(!this.proc){ //should cache this.proc here this.proc = new XSLTProcessor(); this.proc.importStylesheet(this.xsl_xml); } if(this.proc.transformToFragment) return this.proc.transformToFragment(xml_doc,document); } return XML.makesoup(xml_doc.transformNode(this.xsl_xml)); } }; function transformer_dummy(){ this.out = function(xml_doc){ var str = XML.serialize(xml_doc); var ret = XML.makesoup(str); return ret; } };
var XML = { serialize:function(el){ if(window.XMLSerializer) return (new XMLSerializer()).serializeToString(el); return el.xml; }, makesoup:function(xml_str){ return $n("div").set('html', xml_str).getFirst(); } }; function transformer_xslt(xsl_lnk){ this.xsl_xml = xsl_lnk; if(Browser.Engine.webkit){ // Safari do not support transformToFragment else var liste = this.xsl_xml.getElementsByTagName("output"); liste.item(0).setAttribute("method", "html"); } this.xsl_xml.resolveExternals = true; this.proc = false; this.out = function (xml_doc){ if(window.XSLTProcessor){ if(!this.proc){ //should cache this.proc here this.proc = new XSLTProcessor(); this.proc.importStylesheet(this.xsl_xml); } if(this.proc.transformToFragment) return this.proc.transformToFragment(xml_doc,document); } return XML.makesoup(xml_doc.transformNode(this.xsl_xml)); } }; function transformer_dummy(){ this.out = function(xml_doc){ var str = XML.serialize(xml_doc); var ret = XML.makesoup(str); return ret; } };
Add typescript tasks for conversion
var fs = require('fs'), gulp = require('gulp'), rename = require('gulp-rename'), browserify = require('gulp-browserify'), header = require('gulp-header'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), ts = require('gulp-typescript'); console.log(fs.readFileSync('./LICENSE', 'utf8')); var tsProject = ts.createProject('tsconfig.json'); gulp.task('browserify', function() { var tsResult = gulp.src('*.ts') .pipe(tsProject()) .js.pipe(browserify({ })). pipe(rename(function(path) { path.basename = 'neuralnetwork0'; })). pipe(header( '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n' )). pipe(gulp.dest('./dist')). pipe(rename(function(path) { path.basename = 'neuralnetwork0.min'; })). pipe(uglify()). pipe(header( '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n' )). pipe(gulp.dest('./dist')); }); // gulp.task('licensify', function() { // return gulp.src(['./LICENSE', './dist/neuralNet.js']). // pipe(concat('all.js')). // pipe(gulp.dest('./dist')) // }); gulp.task('type', function() { var tsResult = gulp.src('*.ts') .pipe(tsProject()); }); gulp.task('typetest', function() { gulp.watch('**/*.ts', ['type']); }); gulp.task('default', ['browserify']);
var fs = require('fs'), gulp = require('gulp'), rename = require('gulp-rename'), browserify = require('gulp-browserify'), header = require('gulp-header'), concat = require('gulp-concat'), uglify = require('gulp-uglify'); console.log(fs.readFileSync('./LICENSE', 'utf8')); gulp.task('browserify', function() { return gulp.src('./lib/browser.js'). pipe(browserify({ })). pipe(rename(function(path) { path.basename = 'neuralnetwork0'; })). pipe(header( '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n' )). pipe(gulp.dest('./dist')). pipe(rename(function(path) { path.basename = 'neuralnetwork0.min'; })). pipe(uglify()). pipe(header( '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n' )). pipe(gulp.dest('./dist')); }); // gulp.task('licensify', function() { // return gulp.src(['./LICENSE', './dist/neuralNet.js']). // pipe(concat('all.js')). // pipe(gulp.dest('./dist')) // }); gulp.task('default', ['browserify']);
Remove hiro timeline context in redis test
import unittest import datetime import hiro import redis from sifr.span import Minute, Day from sifr.storage import MemoryStorage, RedisStorage class RedisStorageTests(unittest.TestCase): def setUp(self): self.redis = redis.Redis() self.redis.flushall() def test_incr_simple_minute(self): span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(self.redis) storage.incr(span) storage.incr(span) self.assertEqual(storage.get(span), 2) def test_incr_unique_minute(self): red = redis.Redis() span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(red) storage.incr_unique(span, "1") storage.incr_unique(span, "1") storage.incr_unique(span, "2") self.assertEqual(storage.get_unique(span), 2) def test_tracker_minute(self): span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(self.redis) storage.track(span, "1", 3) storage.track(span, "1", 3) storage.track(span, "2", 3) storage.track(span, "3", 3) self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
import unittest import datetime import hiro import redis from sifr.span import Minute, Day from sifr.storage import MemoryStorage, RedisStorage class RedisStorageTests(unittest.TestCase): def setUp(self): self.redis = redis.Redis() self.redis.flushall() def test_incr_simple_minute(self): span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(self.redis) storage.incr(span) storage.incr(span) self.assertEqual(storage.get(span), 2) def test_incr_unique_minute(self): red = redis.Redis() span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(red) storage.incr_unique(span, "1") storage.incr_unique(span, "1") storage.incr_unique(span, "2") self.assertEqual(storage.get_unique(span), 2) def test_tracker_minute(self): with hiro.Timeline().freeze() as timeline: span = Minute(datetime.datetime.now(), ["minute_span"]) storage = RedisStorage(self.redis) storage.track(span, "1", 3) storage.track(span, "1", 3) storage.track(span, "2", 3) storage.track(span, "3", 3) self.assertEqual(storage.enumerate(span), set(["1", "2", "3"]))
Add starting date to habit model
package ca.antonious.habittracker.models; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * Created by George on 2016-09-01. */ public class Habit { private String id; private String name; private Date startDate; private List<Days> daysToComplete = new ArrayList<>(); private List<HabitCompletion> completions = new ArrayList<>(); public Habit() { setId(UUID.randomUUID().toString()); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public List<HabitCompletion> getCompletions() { return completions; } public void setCompletions(List<? extends HabitCompletion> completions) { this.completions.clear(); this.completions.addAll(completions); } public HabitCompletion getCompletion(String completionId) { for (HabitCompletion habitCompletion: getCompletions()) { if (completionId.equals(habitCompletion.getId())) { return habitCompletion; } } return null; } public List<Days> getDaysToComplete() { return daysToComplete; } public void setDaysToComplete(List<Days> daysToComplete) { this.daysToComplete = daysToComplete; } }
package ca.antonious.habittracker.models; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * Created by George on 2016-09-01. */ public class Habit { private String id; private String name; private List<Days> daysToComplete = new ArrayList<>(); private List<HabitCompletion> completions = new ArrayList<>(); public Habit() { setId(UUID.randomUUID().toString()); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<HabitCompletion> getCompletions() { return completions; } public void setCompletions(List<? extends HabitCompletion> completions) { this.completions.clear(); this.completions.addAll(completions); } public HabitCompletion getCompletion(String completionId) { for (HabitCompletion habitCompletion: getCompletions()) { if (completionId.equals(habitCompletion.getId())) { return habitCompletion; } } return null; } public List<Days> getDaysToComplete() { return daysToComplete; } public void setDaysToComplete(List<Days> daysToComplete) { this.daysToComplete = daysToComplete; } }
Fix decode bug in Process() failures
import subprocess as sub import logbook from piper.logging import SEPARATOR class Process(object): """ Helper class for running processes """ def __init__(self, ns, cmd, parent_key): self.ns = ns self.cmd = cmd self.popen = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') self.popen = sub.Popen( self.cmd.split(), stdout=sub.PIPE, stderr=sub.PIPE, ) def run(self): self.log.debug('Executing') if self.ns.dry_run is True: self.log.info('Not executing dry run.') self.success = True return while not self.popen.poll(): # TODO: Gracefully handle stderr as well line = self.popen.stdout.readline() if not line: break self.log.info(line.decode('utf-8').rstrip()) exit = self.popen.wait() self.log.debug('Exitcode {0}'.format(exit)) self.success = exit == 0 if not self.success: self.log.error(self.popen.stderr.read().decode('utf-8'))
import subprocess as sub import logbook from piper.logging import SEPARATOR class Process(object): """ Helper class for running processes """ def __init__(self, ns, cmd, parent_key): self.ns = ns self.cmd = cmd self.popen = None self.success = None self.log = logbook.Logger(parent_key + SEPARATOR + self.cmd) def setup(self): """ Setup the Popen object used in execution """ self.log.debug('Spawning process handler') self.popen = sub.Popen( self.cmd.split(), stdout=sub.PIPE, stderr=sub.PIPE, ) def run(self): self.log.debug('Executing') if self.ns.dry_run is True: self.log.info('Not executing dry run.') self.success = True return while not self.popen.poll(): # TODO: Gracefully handle stderr as well line = self.popen.stdout.readline() if not line: break self.log.info(line.decode('utf-8').rstrip()) exit = self.popen.wait() self.log.debug('Exitcode {0}'.format(exit)) self.success = exit == 0 if not self.success: self.log.error(self.popen.stderr.read())
Implement the reset function of the data collector
<?php namespace Common\DataCollector; use SpoonDatabase; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DatabaseDataCollector extends DataCollector { /** * @var SpoonDatabase */ private $database; public function __construct(SpoonDatabase $database) { $this->database = $database; } public function collect(Request $request, Response $response, \Exception $exception = null): void { $this->data = [ 'queries' => array_map( function (array $query) { $query['query_formatted'] = \SqlFormatter::format($query['query']); return $query; }, (array) $this->database->getQueries() ), 'queryCount' => count($this->database->getQueries()), ]; } public function getQueryCount(): int { return $this->data['queryCount'] ?? 0; } public function getQueries(): array { return $this->data['queries'] ?? []; } public function getName(): string { return 'database'; } public function reset() { $this->data = []; } }
<?php namespace Common\DataCollector; use SpoonDatabase; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class DatabaseDataCollector extends DataCollector { /** * @var SpoonDatabase */ private $database; public function __construct(SpoonDatabase $database) { $this->database = $database; } public function collect(Request $request, Response $response, \Exception $exception = null): void { $this->data = [ 'queries' => array_map( function (array $query) { $query['query_formatted'] = \SqlFormatter::format($query['query']); return $query; }, (array) $this->database->getQueries() ), 'queryCount' => count($this->database->getQueries()), ]; } public function getQueryCount(): int { return $this->data['queryCount']; } public function getQueries(): array { return $this->data['queries']; } public function getName(): string { return 'database'; } }
Fix for the sorted merge step git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4014 5fb7f6ec-07c1-534a-b4ca-9155e429e800
package org.pentaho.di.run.sortedmerge; import junit.framework.TestCase; import org.pentaho.di.core.Result; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.run.AllRunTests; import org.pentaho.di.run.TimedTransRunner; public class RunSortedMerge extends TestCase { public void test_SORTED_MERGE_00() { System.out.println(); System.out.println("SORTED MERGE"); System.out.println("=================="); } public void test_SORTED_MERGE_01_SIMPLE() throws Exception { TimedTransRunner timedTransRunner = new TimedTransRunner( "test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr", LogWriter.LOG_LEVEL_ERROR, AllRunTests.getOldTargetDatabase(), AllRunTests.getNewTargetDatabase(), 1000000 ); timedTransRunner.runOldAndNew(); be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult(); assertTrue(oldResult.getNrErrors()==0); Result newResult = timedTransRunner.getNewResult(); assertTrue(newResult.getNrErrors()==0); } }
package org.pentaho.di.run.sortedmerge; import junit.framework.TestCase; import org.pentaho.di.core.Result; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.run.AllRunTests; import org.pentaho.di.run.TimedTransRunner; public class RunSortedMerge extends TestCase { public void test_SORTED_MERGE_00() { System.out.println(); System.out.println("SORTED MERGE"); System.out.println("=================="); } public void test_SORTED_MERGE_01_SIMPLE() throws Exception { TimedTransRunner timedTransRunner = new TimedTransRunner( "test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr", LogWriter.LOG_LEVEL_ERROR, AllRunTests.getOldTargetDatabase(), AllRunTests.getNewTargetDatabase(), 1000 ); timedTransRunner.runOldAndNew(); be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult(); assertTrue(oldResult.getNrErrors()==0); Result newResult = timedTransRunner.getNewResult(); assertTrue(newResult.getNrErrors()==0); } }