text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Revert "Use namedtuple's getattr rather than indexing" This reverts commit 5c4f93207c1fbfe9b9a478082d5f039a9e5ba720.
# -*- coding: utf-8 -*- import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat[5] if stat[5] else stat[0], 'class': stat[2], 'jumbo': stat[1], 'dismiss': stat[3], 'extra': stat[6]} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
# -*- coding: utf-8 -*- import os import json import requests from flask import send_from_directory, Response, stream_with_context from framework.sessions import session from website.settings import EXTERNAL_EMBER_APPS, PROXY_EMBER_APPS, EXTERNAL_EMBER_SERVER_TIMEOUT ember_osf_web_dir = os.path.abspath(os.path.join(os.getcwd(), EXTERNAL_EMBER_APPS['ember_osf_web']['path'])) routes = [ '/quickfiles/', '/<uid>/quickfiles/' ] def use_ember_app(**kwargs): if PROXY_EMBER_APPS: resp = requests.get(EXTERNAL_EMBER_APPS['ember_osf_web']['server'], stream=True, timeout=EXTERNAL_EMBER_SERVER_TIMEOUT) resp = Response(stream_with_context(resp.iter_content()), resp.status_code) else: resp = send_from_directory(ember_osf_web_dir, 'index.html') if session.data.get('status'): status = [{'id': stat.id if stat.id else stat.message, 'class': stat.css_class, 'jumbo': stat.jumbotron, 'dismiss': stat.dismissible, 'extra': stat.extra} for stat in session.data['status']] resp.set_cookie('status', json.dumps(status)) return resp
Add an error check to make sure we have the authentication URL parameter
var _ = require('underscore'), underscoreDeepExtend = require('underscore-deep-extend'), async = require('async'), getSamlBody = require('./online/samlBody'), samlLogin = require('./online/samlLogin'), samlResponse = require('./online/samlResponse'), samlAssertionResponse = require('./online/samlAssertionResponse'), samlTokenToCookie = require('./online/samlTokenToCookie'), authenticatedRequestClient = require('./online/authenticatedRequestClient'), assert=require('assert'); _.mixin({ deepExtend: underscoreDeepExtend(_) }); module.exports = function(client, httpOpts, cb) { var waterfall = []; if (!client.FedAuth || !client.rtFa){ assert.ok(client.federatedAuthUrl, "Federated Auth URL is required when using onlinesaml"); waterfall.push(async.apply(getSamlBody, client, httpOpts, client.federatedAuthUrl, 'urn:federation:MicrosoftOnline', null)); waterfall.push(samlLogin); waterfall.push(samlAssertionResponse); waterfall.push(getSamlBody); waterfall.push(samlLogin); waterfall.push(samlResponse); waterfall.push(samlTokenToCookie); waterfall.push(authenticatedRequestClient); }else{ waterfall.push(async.apply(authenticatedRequestClient, client, httpOpts)); } return async.waterfall(waterfall, cb); };
var _ = require('underscore'), underscoreDeepExtend = require('underscore-deep-extend'), async = require('async'), getSamlBody = require('./online/samlBody'), samlLogin = require('./online/samlLogin'), samlResponse = require('./online/samlResponse'), samlAssertionResponse = require('./online/samlAssertionResponse'), samlTokenToCookie = require('./online/samlTokenToCookie'), authenticatedRequestClient = require('./online/authenticatedRequestClient'); _.mixin({ deepExtend: underscoreDeepExtend(_) }); module.exports = function(client, httpOpts, cb) { var waterfall = []; if (!client.FedAuth || !client.rtFa){ waterfall.push(async.apply(getSamlBody, client, httpOpts, client.federatedAuthUrl, 'urn:federation:MicrosoftOnline', null)); waterfall.push(samlLogin); waterfall.push(samlAssertionResponse); waterfall.push(getSamlBody); waterfall.push(samlLogin); waterfall.push(samlResponse); waterfall.push(samlTokenToCookie); waterfall.push(authenticatedRequestClient); }else{ waterfall.push(async.apply(authenticatedRequestClient, client, httpOpts)); } return async.waterfall(waterfall, cb); };
Allow model to be nullable.
<?php namespace Adldap\Laravel\Validation\Rules; use Adldap\Models\User; use Illuminate\Database\Eloquent\Model; abstract class Rule { /** * The LDAP user. * * @var User */ protected $user; /** * The Eloquent model. * * @var Model|null */ protected $model; /** * Constructor. * * @param User $user * @param Model|null $model */ public function __construct(User $user, Model $model = null) { $this->user = $user; $this->model = $model; } /** * Checks if the rule passes validation. * * @return bool */ abstract public function isValid(); }
<?php namespace Adldap\Laravel\Validation\Rules; use Adldap\Models\User; use Illuminate\Database\Eloquent\Model; abstract class Rule { /** * @var User */ protected $user; /** * @var Model */ protected $model; /** * Constructor. * * @param User $user * @param Model $model */ public function __construct(User $user, Model $model) { $this->user = $user; $this->model = $model; } /** * Checks if the rule passes validation. * * @return bool */ abstract public function isValid(); }
Use coverage summary rather than full coverage breakdown
var gulp = require('gulp'), tsc = require('gulp-tsc'), tape = require('gulp-tape'), tapSpec = require('tap-spec'), del = require('del'), runSequence = require('run-sequence'), istanbul = require('gulp-istanbul'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src('test/**/*.ts') .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:istanbul-hook", function () { return gulp.src('build-test/src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .pipe(istanbul.writeReports({ reporters: [ 'lcov', 'json', 'text-summary' ] })) .on('end', done); }); gulp.task("test", function (done) { runSequence('test:clean', 'test:build', 'test:istanbul-hook', 'test:run', done); });
var gulp = require('gulp'), tsc = require('gulp-tsc'), tape = require('gulp-tape'), tapSpec = require('tap-spec'), del = require('del'), runSequence = require('run-sequence'), istanbul = require('gulp-istanbul'); gulp.task("test:clean", function(done) { del(['build-test/**']).then(function(paths) { console.log("=====\nDeleted the following files:\n" + paths.join('\n')+ "\n====="); done(); }); }); gulp.task("test:build", function (done) { gulp.src('test/**/*.ts') .pipe(tsc()) .pipe(gulp.dest('build-test/')) .on('end', done); }); gulp.task("test:istanbul-hook", function () { return gulp.src('build-test/src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()); }); gulp.task("test:run", function (done) { gulp.src('build-test/test/**/*.test.js') .pipe(tape({ reporter: tapSpec() })) .pipe(istanbul.writeReports()) .on('end', done); }); gulp.task("test", function (done) { runSequence('test:clean', 'test:build', 'test:istanbul-hook', 'test:run', done); });
[2.0] Fix bug in detection of global Doctrine Cli Configuration finding the empty replacement configuration before the correct one. git-svn-id: 6d62a1918bfbe91cfb3198953e3056b244989dd5@7322 2b2ae520-0f61-44a6-8c59-7e116ffd6265
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = null; if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $configuration = ($configuration) ?: new \Doctrine\Common\Cli\Configuration(); $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
<?php require_once 'Doctrine/Common/ClassLoader.php'; $classLoader = new \Doctrine\Common\ClassLoader('Doctrine'); $classLoader->register(); $configFile = getcwd() . DIRECTORY_SEPARATOR . 'cli-config.php'; $configuration = new \Doctrine\Common\Cli\Configuration(); if (file_exists($configFile)) { if ( ! is_readable($configFile)) { trigger_error( 'Configuration file [' . $configFile . '] does not have read permission.', E_ERROR ); } require $configFile; foreach ($GLOBALS as $configCandidate) { if ($configCandidate instanceof \Doctrine\Common\Cli\Configuration) { $configuration = $configCandidate; break; } } } $cli = new \Doctrine\Common\Cli\CliController($configuration); $cli->run($_SERVER['argv']);
Set the view content based on the content in the response.
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Application * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Page Controller Class * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku_Server * @subpackage Application */ class ComApplicationControllerPage extends KControllerResource { protected function _initialize(KConfig $config) { $config->append(array( 'view' => 'page', 'toolbars' => array('menubar', $this->getIdentifier()->name), )); parent::_initialize($config); } protected function _actionGet(KCommandContext $context) { $this->getView()->content = $context->response->getContent(); return parent::_actionGet($context); } }
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Application * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Page Controller Class * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku_Server * @subpackage Application */ class ComApplicationControllerPage extends KControllerResource { protected function _initialize(KConfig $config) { $config->append(array( 'view' => 'page', 'toolbars' => array('menubar', $this->getIdentifier()->name), )); parent::_initialize($config); } }
Add top positioning to chevron and reformat with Prettify
//@flow import styled from "styled-components"; export const Svg = styled.svg.attrs({ className: "chevron__svg", viewBox: "0 0 24 24" })` ${({ theme, isActive, stateful }: { theme: Theme, isActive: boolean, stateful: boolean }): string => ` position: relative; height: ${theme.scale.s1(2)}; width: ${theme.scale.s1(2)}; top: ${theme.scale.s1(-9)}; padding-left: ${theme.scale.s8(-2)}; transform-origin: 60% 60%; will-change: transform fill; transition: all 0.2s ease-in-out; ${isActive && stateful ? ` fill: ${theme.effect.darken(0.2, theme.color.black)}; transform: rotate(180deg); ` : ``} `} `;
//@flow import styled from "styled-components"; export const Svg = styled.svg.attrs({ viewBox: "0 0 24 24" })` ${({ theme, isActive, stateful }: { theme: Theme, isActive: boolean, stateful: boolean }): string => ` position: relative; height: ${theme.scale.s1(2)}; width: ${theme.scale.s1(2)}; ${theme.utils.baseAdjust(6)} padding-left: ${theme.scale.s8(-2)}; transform-origin: 60% 60%; will-change: transform fill; transition: all 0.2s ease-in-out; ${isActive && stateful ? ` fill: ${theme.effect.darken(0.2, theme.color.black)}; transform: rotate(180deg); ` : ``} `} `;
Use PHP 5.4 short array syntax.
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'))); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
Fix copy with absolute paths
var fse = require("fs-extra"); function WebpackCopyAfterBuildPlugin(mappings) { this._mappings = mappings || {}; } WebpackCopyAfterBuildPlugin.prototype.apply = function(compiler) { var mappings = this._mappings; compiler.plugin("done", function(stats) { var statsJson = stats.toJson(); var chunks = statsJson.chunks; chunks.forEach(function(chunk) { var chunkName = chunk.names[0]; var mapping = mappings[chunkName]; if (mapping) { var devServer = compiler.options.devServer; var outputPath; if (devServer && devServer.contentBase) { outputPath = devServer.contentBase; } else { outputPath = compiler.options.output.path; } var chunkFilename = chunk.files[0]; var from = outputPath + "/" + chunkFilename; var to = outputPath + "/" + mapping; fse.copySync(from, to); } }); }); }; module.exports = WebpackCopyAfterBuildPlugin;
var fse = require("fs-extra"); function WebpackCopyAfterBuildPlugin(mappings) { this._mappings = mappings || {}; } WebpackCopyAfterBuildPlugin.prototype.apply = function(compiler) { var mappings = this._mappings; compiler.plugin("done", function(stats) { var statsJson = stats.toJson(); var chunks = statsJson.chunks; chunks.forEach(function(chunk) { var bundleName = chunk.names[0]; var mapping = mappings[bundleName]; if (mapping) { var devServer = compiler.options.devServer; var outputPath; if (devServer && devServer.contentBase) { outputPath = devServer.contentBase; } else { outputPath = compiler.options.output.path; } var webpackContext = compiler.options.context; var chunkHashFileName = chunk.files[0]; var from = webpackContext + "/" + outputPath + "/" + chunkHashFileName; var to = webpackContext + "/" + outputPath + "/" + mapping; fse.copySync(from, to); } }); }); }; module.exports = WebpackCopyAfterBuildPlugin;
Remove event listeners after transitioning away
import Ember from 'ember' import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin' const { get, set } = Ember export default Ember.Route.extend(Authenticated, { pageTitle: 'Media', toggleDropzone (event) { $('body').toggleClass('dz-open') }, actions: { uploadImage (file) { const properties = ['type', 'size', 'name'] var details = {} $('body').removeClass('dz-open') for (var property of properties) { details[property] = get(file, property) } const record = this.store.createRecord('file', details) file.read().then(url => { if (get(record, 'url') == null) { set(record, 'url', url) } }) file.upload('/api/upload').then(response => { set(record, 'url', response.headers.Location) return record.save() }, () => { record.rollback() }) }, willTransition () { $('body').unbind('dragenter dragleave', this.toggleDropzone) }, didTransition () { $('body').on('dragenter dragleave', this.toggleDropzone) } }, model () { return this.store.findAll('file') } })
import Ember from 'ember' import Authenticated from 'ember-simple-auth/mixins/authenticated-route-mixin' const { get, set } = Ember export default Ember.Route.extend(Authenticated, { pageTitle: 'Media', init () { $('body').on('dragenter dragleave', this.toggleDropzone) }, toggleDropzone (event) { $('body').toggleClass('dz-open') }, actions: { uploadImage (file) { const properties = ['type', 'size', 'name'] var details = {} $('body').removeClass('dz-open') for (var property of properties) { details[property] = get(file, property) } const record = this.store.createRecord('file', details) file.read().then(url => { if (get(record, 'url') == null) { set(record, 'url', url) } }) file.upload('/api/upload').then(response => { set(record, 'url', response.headers.Location) return record.save() }, () => { record.rollback() }) } }, model () { return this.store.findAll('file') } })
Add project to integration credential api fields
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCredentialSerializer(serializers.HyperlinkedModelSerializer): environments = EnvironmentSerializer(many=True, read_only=True) integration_type = IntegrationTypeSerializer(many=False, read_only=True) class Meta: model = IntegrationCredential fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments',"project",) class IntegrationCredentialAPI(viewsets.ModelViewSet): """ Integration Credential Api """ serializer_class = IntegrationCredentialSerializer queryset = IntegrationCredential.objects.all()
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCredentialSerializer(serializers.HyperlinkedModelSerializer): environments = EnvironmentSerializer(many=True, read_only=True) integration_type = IntegrationTypeSerializer(many=False, read_only=True) class Meta: model = IntegrationCredential fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments') class IntegrationCredentialAPI(viewsets.ModelViewSet): """ Integration Credential Api """ serializer_class = IntegrationCredentialSerializer queryset = IntegrationCredential.objects.all()
Use JSON to parse hlint output
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Hardy Jones # Copyright (c) 2013 # # License: MIT # """This module exports the Hlint plugin class.""" import json from SublimeLinter.lint import Linter, LintMatch class Hlint(Linter): """Provides an interface to hlint.""" cmd = 'hlint ${args} --json -' defaults = { 'selector': 'source.haskell' } def find_errors(self, output): # type: (str) -> Iterator[LintMatch] errors = json.loads(output) for error in errors: message = "{hint}. Found: {from}".format(**error) if error['to']: message += " Perhaps: {to}".format(**error) yield LintMatch( error_type=error['severity'].lower(), line=error['startLine'] - 1, col=error['startColumn'] - 1, message=message )
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Hardy Jones # Copyright (c) 2013 # # License: MIT # """This module exports the Hlint plugin class.""" from SublimeLinter.lint import Linter class Hlint(Linter): """Provides an interface to hlint.""" defaults = { 'selector': 'source.haskell' } cmd = 'hlint' regex = ( r'^.+:(?P<line>\d+):' '(?P<col>\d+):\s*' '(?:(?P<error>Error)|(?P<warning>Warning)):\s*' '(?P<message>.+)$' ) multiline = True tempfile_suffix = 'hs'
Use a better structure for components
/** * Transfer component data from .mxt to json */ var fs = require('fs'); var path = require('path'); var componentDataPath = './componentdata.tmp'; fs.readFile(componentDataPath, { encoding : 'utf-8' }, function (err, data) { if(err) return console.log(err); var lines = data.split('\n'); var categories = ['groups', 'teachers', 'rooms', 'other']; var container = {}; lines.forEach(function (line) { if(!line.length) return; var data = line.split('=')[1]; var items = data.split(';'); container[items[0]] = { name : items[1], category : categories[items[2] - 1] }; }); fs.writeFile('components.json', JSON.stringify(container, null, '\t'), function (err) { if(err) console.log(err); }); console.log('Files are processing'); });
/** * Transfer component data from .mxt to json */ var fs = require('fs'); var path = require('path'); var componentDataPath = './componentdata.tmp'; fs.readFile(componentDataPath, { encoding : 'utf-8' }, function (err, data) { if(err) return console.log(err); var lines = data.split('\n'); var categories = ['groups', 'teachers', 'rooms', 'other']; var container = categories.map(function (item) { return { name : item, data : [] } }); lines.forEach(function (line) { if(!line.length) return; var data = line.split('=')[1]; var items = data.split(';'); container[items[2] - 1].data.push({ code : items[0], name : items[1] }); }); container.forEach(function (item) { fs.writeFile(item.name + '.json', JSON.stringify(item.data, null, '\t'), function (err) { if(err) console.log(err); }); }); console.log('Files are processing'); });
Fix linting issues and duplicate check for components and sections
import React from 'react'; import ReactDOM from 'react-dom'; import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils'; import StyleGuide from 'rsg-components/StyleGuide'; import 'highlight.js/styles/tomorrow.css'; import './styles.css'; global.React = React; if (module.hot) { module.hot.accept(); } // Load style guide let { config, components, sections } = require('styleguide!'); function processComponents(cs) { cs = flattenChildren(cs); cs = promoteInlineExamples(cs); cs = setComponentsNames(cs); globalizeComponents(cs); return cs; } function processSections(ss) { return ss.map(section => { section.components = processComponents(section.components || []); section.sections = processSections(section.sections || []); return section; }); } // Components are required unless sections are provided if (sections) { sections = processSections(sections); components = []; } else { components = processComponents(components); sections = []; } ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
import React from 'react'; import ReactDOM from 'react-dom'; import { setComponentsNames, globalizeComponents, promoteInlineExamples, flattenChildren } from './utils/utils'; import StyleGuide from 'rsg-components/StyleGuide'; import 'highlight.js/styles/tomorrow.css'; import './styles.css'; global.React = React; if (module.hot) { module.hot.accept(); } // Load style guide let { config, components, sections } = require('styleguide!'); function processComponents(cs) { cs = flattenChildren(cs); cs = promoteInlineExamples(cs); cs = setComponentsNames(cs); globalizeComponents(cs); return cs; } function processSections(ss) { return ss.map(section => { section.components = processComponents(section.components || []); section.sections = processSections(section.sections || []); return section; }); } // Components are required unless sections are provided if (sections) { sections = processSections(sections) components = [] } else { components = processComponents(components) sections = [] } components = components ? processComponents(components) : []; sections = sections ? processSections(sections) : []; ReactDOM.render(<StyleGuide config={config} components={components} sections={sections} />, document.getElementById('app'));
Put in numbers that are at least kinda right
package main; import search.SqRoomExploration; import lejos.nxt.SensorPort; import lejos.nxt.addon.tetrix.TetrixMotorController; import lejos.nxt.addon.tetrix.TetrixRegulatedMotor; import lejos.nxt.addon.tetrix.TetrixControllerFactory; import lejos.robotics.navigation.DifferentialPilot; /** This is the class StartUp * Created by OneNationUnderCanadia * To start the robot * * Created on Feb 16, 2015 at 8:48:15 AM */ public class StartUp { private static TetrixControllerFactory cf; private static TetrixMotorController mc; public static void main(String[] args) { // TODO headlights cf = new TetrixControllerFactory(SensorPort.S1); mc = cf.newMotorController(); TetrixRegulatedMotor motor1 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_1); TetrixRegulatedMotor motor2 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_2); DifferentialPilot pilot = new DifferentialPilot(7.5, 31.9, motor1, motor2); SqRoomExploration mapper = new SqRoomExploration(pilot, 60, 60); } }
package main; import search.SqRoomExploration; import lejos.nxt.SensorPort; import lejos.nxt.addon.tetrix.TetrixMotorController; import lejos.nxt.addon.tetrix.TetrixRegulatedMotor; import lejos.nxt.addon.tetrix.TetrixControllerFactory; import lejos.robotics.navigation.DifferentialPilot; /** This is the class StartUp * Created by OneNationUnderCanadia * To start the robot * * Created on Feb 16, 2015 at 8:48:15 AM */ public class StartUp { private static TetrixControllerFactory cf; private static TetrixMotorController mc; public static void main(String[] args) { // TODO headlights cf = new TetrixControllerFactory(SensorPort.S1); mc = cf.newMotorController(); TetrixRegulatedMotor motor1 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_1); TetrixRegulatedMotor motor2 = new TetrixRegulatedMotor(mc, TetrixMotorController.MOTOR_2); DifferentialPilot pilot = new DifferentialPilot((double) 10, (double) 10, motor1, motor2); SqRoomExploration mapper = new SqRoomExploration(pilot, 60, 60); } }
Update for Mailgun v3 API
<?php //// Browning: A Mailgun Script (v0.25) // https://github.com/eustasy/browning-a-mailgun-script //// Mailgun // Sign up at https://mailgun.com/signup // First 10,00 mails a month free. // Mailgun API URL // Replace example.com with your domain after signing up at // $Browning['URL'] = 'https://api.mailgun.net/v3/example.com'; $Browning['URL'] = 'https://api.mailgun.net/v3/example.com'; // Mailgun API Key // Use API Key found at https://mailgun.com/cp // $Browning['Key'] = 'key-123456-abcdefg-789012-abc-34567'; $Browning['Key'] = 'key-123456-abcdefg-789012-abc-34567'; // Not the Public Key. We don't need that. // From for Mail // $Browning['Default']['Regards'] = 'Example Support'; $Browning['Default']['Regards'] = 'Example Support'; // Reply-to address // Please don't use noreply. // Should match the domain in your API URL. // $Browning['Default']['ReplyTo'] = 'support@example.com'; $Browning['Default']['ReplyTo'] = 'support@example.com';
<?php //// Browning: A Mailgun Script (v0.25) // https://github.com/eustasy/browning-a-mailgun-script //// Mailgun // Sign up at https://mailgun.com/signup // First 10,00 mails a month free. // Mailgun API URL // Replace example.com with your domain after signing up at // $Browning['URL'] = 'https://api.mailgun.net/v2/example.com'; $Browning['URL'] = 'https://api.mailgun.net/v2/example.com'; // Mailgun API Key // Use API Key found at https://mailgun.com/cp // $Browning['Key'] = 'key-123456-abcdefg-789012-abc-34567'; $Browning['Key'] = 'key-123456-abcdefg-789012-abc-34567'; // Not the Public Key. We don't need that. // From for Mail // $Browning['Default']['Regards'] = 'Example Support'; $Browning['Default']['Regards'] = 'Example Support'; // Reply-to address // Please don't use noreply. // Should match the domain in your API URL. // $Browning['Default']['ReplyTo'] = 'support@example.com'; $Browning['Default']['ReplyTo'] = 'support@example.com';
Add data attribute and set value when nil to input replacing of progress
window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() { function GobiertoCommonCustomFieldRecordsProgressPluginController() {} GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) { _handlePluginData(opts.uid); }; function _handlePluginData(uid) { let element = $(`[data-uid=${uid}]`) let id = element.attr('id') let data = JSON.parse($(`#${id}`).find("input[name$='[value]'").val()) _insertProgressPlugin(id, data) } function _insertProgressPlugin(id, data) { let element = $(`#${id}`) element.remove(); let progress_select = $("select[id$='_progress'") if(progress_select.length) { progress_select.replaceWith( $('<input type="text" disabled="disabled" data-plugin-type="progress">').val( data ? data.toLocaleString(I18n.locale, { style: 'percent', maximumFractionDigits: 1 }) : "-" ) ); } } return GobiertoCommonCustomFieldRecordsProgressPluginController; })(); window.GobiertoAdmin.gobierto_common_custom_field_records_progress_plugin_controller = new GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController;
window.GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController = (function() { function GobiertoCommonCustomFieldRecordsProgressPluginController() {} GobiertoCommonCustomFieldRecordsProgressPluginController.prototype.form = function(opts = {}) { _handlePluginData(opts.uid); }; function _handlePluginData(uid) { let element = $(`[data-uid=${uid}]`) let id = element.attr('id') let data = JSON.parse($(`#${id}`).find("input[name$='[value]'").val()) _insertProgressPlugin(id, data) } function _insertProgressPlugin(id, data) { let element = $(`#${id}`) element.remove(); let progress_select = $("select[id$='_progress'") if(progress_select.length) { progress_select.replaceWith( $('<input type="text" disabled="disabled">').val( data.toLocaleString(I18n.locale, { style: 'percent', maximumFractionDigits: 1 }) ) ); } } return GobiertoCommonCustomFieldRecordsProgressPluginController; })(); window.GobiertoAdmin.gobierto_common_custom_field_records_progress_plugin_controller = new GobiertoAdmin.GobiertoCommonCustomFieldRecordsProgressPluginController;
Add support to custom mongo database name
'use strict'; // Load environment variables from .env file, where API keys and passwords are configured. const dotenv = require('dotenv'); if (!process.env.NODE_ENV) { process.env.NODE_ENV = 'development'; } dotenv.config({ path: `.env.${process.env.NODE_ENV}` }); const { MONGO_HOST, MONGO_PORT, MONGO_USER, MONGO_PASSWORD, MONGO_DATABASE_NAME, MONGO_OPTIONS, APP_SECRET, NODE_ENV } = process.env; const databaseName = MONGO_DATABASE_NAME || `gcriva_${NODE_ENV}`; const mongoOptions = MONGO_OPTIONS ? `?${MONGO_OPTIONS}` : ''; const mongoPort = MONGO_PORT || 27017; const auth = MONGO_USER && MONGO_PASSWORD ? `${MONGO_USER}:${MONGO_PASSWORD}@` : ''; module.exports = { appSecret: APP_SECRET || 'pikachu', mongoUri: `mongodb://${auth}${MONGO_HOST}:${mongoPort}/${databaseName}${mongoOptions}` };
'use strict'; // Load environment variables from .env file, where API keys and passwords are configured. const dotenv = require('dotenv'); if (!process.env.NODE_ENV) { process.env.NODE_ENV = 'development'; } dotenv.config({ path: `.env.${process.env.NODE_ENV}` }); const { MONGO_HOST, MONGO_PORT, MONGO_USER, MONGO_PASSWORD, MONGO_OPTIONS, APP_SECRET, NODE_ENV } = process.env; const databaseName = `gcriva_${NODE_ENV}`; const mongoOptions = MONGO_OPTIONS ? `?${MONGO_OPTIONS}` : ''; const mongoPort = MONGO_PORT || 27017; const auth = MONGO_USER && MONGO_PASSWORD ? `${MONGO_USER}:${MONGO_PASSWORD}@` : ''; module.exports = { appSecret: APP_SECRET || 'pikachu', mongoUri: `mongodb://${auth}${MONGO_HOST}:${mongoPort}/${databaseName}${mongoOptions}` };
Test: Change allowed globals when linting Move away from specify() and setImmediate().
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: ['Gruntfile.js'], lib: ['index.js', 'lib/**/*.js'], tests: { options: { globals: { describe: true, it: true } }, files: { src: ['tests/**/*.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: grunt.file.readJSON('.jshintrc'), gruntfile: ['Gruntfile.js'], lib: ['index.js', 'lib/**/*.js'], tests: { options: { globals: { describe: true, specify: true, setImmediate: true } }, files: { src: ['tests/**/*.js'] } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); };
Use doctrine_extensions.default_locale instead of en_US as default locale
<?php namespace Bundle\DoctrineExtensionsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use DoctrineExtensions\Sluggable\SluggableListener; use DoctrineExtensions\Timestampable\TimestampableListener; use DoctrineExtensions\Tree\TreeListener; class DoctrineExtensionsBundle extends Bundle { public function boot() { try { $em = $this->container->get('doctrine.orm.entity_manager'); } catch (\InvalidArgumentException $e){ throw new \InvalidArgumentException('You must provide a Doctrine ORM Entity Manager'); } $eventManager = $em->getEventManager(); $treeListener = new TreeListener(); $eventManager->addEventSubscriber($treeListener); $timestampableListener = new TimestampableListener(); $eventManager->addEventSubscriber($timestampableListener); $sluggableListener = new SluggableListener(); $eventManager->addEventSubscriber($sluggableListener); $translatableListener = new TranslationListener(); $translatableListener->setTranslatableLocale($this->container->get('doctrine_extensions.default_locale')); $eventManager->addEventSubscriber($translatableListener); } }
<?php namespace Bundle\DoctrineExtensionsBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use DoctrineExtensions\Sluggable\SluggableListener; use DoctrineExtensions\Timestampable\TimestampableListener; use DoctrineExtensions\Tree\TreeListener; class DoctrineExtensionsBundle extends Bundle { public function boot() { try { $em = $this->container->get('doctrine.orm.entity_manager'); } catch (\InvalidArgumentException $e){ throw new \InvalidArgumentException('You must provide a Doctrine ORM Entity Manager'); } $eventManager = $em->getEventManager(); $treeListener = new TreeListener(); $eventManager->addEventSubscriber($treeListener); $timestampableListener = new TimestampableListener(); $eventManager->addEventSubscriber($timestampableListener); $sluggableListener = new SluggableListener(); $eventManager->addEventSubscriber($sluggableListener); $translatableListener = new TranslationListener(); $translatableListener->setTranslatableLocale('en_US'); $eventManager->addEventSubscriber($translatableListener); } }
Use calcLineNo() for getLineExcerpt() to handle undefined offset
/** * copyObject(object, [recurse]) -- for all JS Objects * * Copies all properties and the prototype to a new object * Optionally set recurse to array containing the properties, on wich this function should be called recursively */ function copyObject(object, recurse) { var new_obj = Object.create(Object.getPrototypeOf(object)); recurse = (recurse) ? recurse : []; for(var prop in object) { new_obj[prop] = object[prop]; if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]); } return new_obj; } function repeatString(str, times) { for(var padding = "", i=0; i < times; i++) { padding += str; } return padding; } function isInt(n) { return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n); } function calcLineNo(source, offset) { return offset ? source.substr( 0, offset ).split("\n").length : -1; }; function getLineExcerpt(source, offset) { var line = calcLineNo(source, offset); return (line >= 0) ? source.split("\n")[line-1] : '<No code reference>'; }; function getLineCol(source, offset) { return source.substr( 0, offset ).split("\n").pop().length+1 };
/** * copyObject(object, [recurse]) -- for all JS Objects * * Copies all properties and the prototype to a new object * Optionally set recurse to array containing the properties, on wich this function should be called recursively */ function copyObject(object, recurse) { var new_obj = Object.create(Object.getPrototypeOf(object)); recurse = (recurse) ? recurse : []; for(var prop in object) { new_obj[prop] = object[prop]; if(recurse.indexOf(prop) !== -1) new_obj[prop] = copyObject(object[prop]); } return new_obj; } function repeatString(str, times) { for(var padding = "", i=0; i < times; i++) { padding += str; } return padding; } function isInt(n) { return String(parseInt(n)) === String(n) && parseInt(n) >= 0 && isFinite(n); } function calcLineNo(source, offset) { return offset ? source.substr( 0, offset ).split("\n").length : -1; }; function getLineExcerpt(source, offset) { return source.substr( 0, offset ).split("\n").pop() + source.substr( offset, 250 ).split("\n")[0]; }; function getLineCol(source, offset) { return source.substr( 0, offset ).split("\n").pop().length+1 };
Set default taking access for GradingProjectSurvey to org. This will allow Mentors and Org Admins to take GradingProjectSurveys in case that an Org Admin has no Mentor roles.
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GradingProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.project_survey import ProjectSurvey class GradingProjectSurvey(ProjectSurvey): """Survey for Mentors for each of their StudentProjects. """ def __init__(self, *args, **kwargs): super(GradingProjectSurvey, self).__init__(*args, **kwargs) self.taking_access = 'org'
#!/usr/bin/python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module contains the GradingProjectSurvey model. """ __authors__ = [ '"Daniel Diniz" <ajaksu@gmail.com>', '"Lennard de Rijk" <ljvderijk@gmail.com>', ] from soc.models.project_survey import ProjectSurvey class GradingProjectSurvey(ProjectSurvey): """Survey for Mentors for each of their StudentProjects. """ def __init__(self, *args, **kwargs): super(GradingProjectSurvey, self).__init__(*args, **kwargs) self.taking_access = 'mentor'
Change yield from to return to be compatible with python 3.2
from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def get_me(self): return self.telegram_api.get_me() def send_message(self, message): return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text, reply_to_message_id=message.reply_to_message_id) def get_pending_updates(self): return self.get_updates(timeout=0) def get_updates(self, timeout=45): updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1)
from bot.api.telegram import TelegramBotApi from bot.storage import State class Api: def __init__(self, telegram_api: TelegramBotApi, state: State): self.telegram_api = telegram_api self.state = state def get_me(self): return self.telegram_api.get_me() def send_message(self, message): return self.telegram_api.send_message(chat_id=message.chat.id, text=message.text, reply_to_message_id=message.reply_to_message_id) def get_pending_updates(self): yield from self.get_updates(timeout=0) def get_updates(self, timeout=45): updates = self.telegram_api.get_updates(offset=self.__get_updates_offset(), timeout=timeout) for update in updates: self.__set_updates_offset(update.update_id) yield update def __get_updates_offset(self): return self.state.next_update_id def __set_updates_offset(self, last_update_id): self.state.next_update_id = str(last_update_id + 1)
Fix to use vanilla JS.
module.exports = function runSagas(routes, dispatch, props, sagaMiddleware) { return Promise.all( routes .filter(function(route) { var sagasToRun; return route.component && (sagasToRun = route.component.sagasToRun) && typeof sagasToRun === 'function'; }) .map(function(route) { var sagasToRun = route.component.sagasToRun(dispatch, props); if (sagasToRun == null || !(sagasToRun instanceof Array) || sagasToRun.some(function(s) { return !(s instanceof Array) })) { return Promise.reject( new Error(`\`sagasToRun()\` must return an array of arrays, in route component ${route.component.displayName}`)); } return Promise.all( sagasToRun.map(function(args) { // Run each Saga // http://yelouafi.github.io/redux-saga/docs/api/index.html#middlewarerunsaga-args // …returning the Task descriptor's Promise // http://yelouafi.github.io/redux-saga/docs/api/index.html#task-descriptor return sagaMiddleware.run.apply(null, args).done; }) ) }) ) }
module.exports = function runSagas(routes, dispatch, props, sagaMiddleware) { return Promise.all( routes .filter(function(route) { var sagasToRun; return route.component && (sagasToRun = route.component.sagasToRun) && typeof sagasToRun === 'function'; }) .map(function(route) { var sagasToRun = route.component.sagasToRun(dispatch, props); if (sagasToRun == null || !(sagasToRun instanceof Array) || sagasToRun.some( s => !(s instanceof Array) )) { return Promise.reject( new Error(`\`sagasToRun()\` must return an array of arrays, in route component ${route.component.displayName}`)); } return Promise.all( sagasToRun.map(function(args) { // Run each Saga // http://yelouafi.github.io/redux-saga/docs/api/index.html#middlewarerunsaga-args // …returning the Task descriptor's Promise // http://yelouafi.github.io/redux-saga/docs/api/index.html#task-descriptor return sagaMiddleware.run.apply(null, args).done; }) ) }) ) }
Remove unused resource fetching of receivers
'use strict'; GLClient.controller('LoginCtrl', ['$scope', '$location', '$routeParams', 'Authentication', 'Receivers', function($scope, $location, $routeParams, Authentication) { var src = $routeParams['src']; $scope.loginUsername = ""; $scope.loginPassword = ""; $scope.loginRole = "receiver"; if (src && src.indexOf("/admin") != -1) { $scope.loginUsername = "admin"; $scope.loginRole = "admin"; }; $scope.$watch("loginUsername", function(){ if ($scope.loginUsername == "admin") { $scope.loginRole = "admin"; } else if ($scope.loginUsername == "wb") { $scope.loginRole = "wb"; } else { $scope.loginRole = "receiver"; } }); }]);
'use strict'; GLClient.controller('LoginCtrl', ['$scope', '$location', '$routeParams', 'Authentication', 'Receivers', function($scope, $location, $routeParams, Authentication, Receivers) { var src = $routeParams['src']; $scope.loginUsername = ""; $scope.loginPassword = ""; $scope.loginRole = "receiver"; Receivers.query(function (receivers) { $scope.receivers = receivers; }); if (src && src.indexOf("/admin") != -1) { $scope.loginUsername = "admin"; $scope.loginRole = "admin"; }; $scope.$watch("loginUsername", function(){ if ($scope.loginUsername == "admin") { $scope.loginRole = "admin"; } else if ($scope.loginUsername == "wb") { $scope.loginRole = "wb"; } else { $scope.loginRole = "receiver"; } }); }]);
[FEATURE] Add route for user ripple deposit, withdraw in angular
'use strict'; angular.module('publicApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/users/:id', { templateUrl: 'views/users.html', controller: 'UsersCtrl' }) .when('/admin', { templateUrl: 'views/admin.html', controller: 'AdminCtrl' }) .when('/register', { templateUrl: 'views/register.html', controller: 'RegistrationCtrl' }) .when('/login', { templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .when('/api/docs', { templateUrl: 'views/api.html', controller: 'ApiDocsCtrl' }) .when('/ripple/deposit', { templateUrl: 'views/ripple/deposit.html', controller: 'RippleTransactionsCtrl' }) .when('/ripple/withdraw', { templateUrl: 'views/ripple/withdraw.html', controller: 'RippleTransactionsCtrl' }) .otherwise({ redirectTo: '/users/-1' }); });
'use strict'; angular.module('publicApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) .config(function ($routeProvider) { $routeProvider .when('/users/:id', { templateUrl: 'views/user.html', controller: 'UsersCtrl' }) .when('/admin', { templateUrl: 'views/admin/settings.html', controller: 'AdminCtrl' }) .when('/register', { templateUrl: 'views/register', controller: 'RegistrationCtrl' }) .when('/login', { templateUrl: 'views/login.html', controller: 'LoginCtrl' }) .when('/api/docs', { templateUrl: 'views/api.html', controller: 'ApiDocsCtrl' }) .otherwise({ redirectTo: '/api/docs' }); });
UPGRADE: Use upload field for image which is compatible with ss3
<?php class FacebookMetadataSiteConfig extends DataExtension { static $db = array( 'SkipToMainContentAccessKey' => 'VarChar(1)' ); static $has_one = array( 'FacebookLogo' => 'Image' ); public function updateCMSFields(FieldList $fields) { $tf2 = new TextField('SkipToMainContentAccessKey'); $tf2->setMaxLength(1); $fields->addFieldToTab('Root.FacebookMetadata', $tf2); $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); $fields->addFieldToTab("Root.FacebookMetadata", new UploadField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square'))); } } ?>
<?php class FacebookMetadataSiteConfig extends DataExtension { static $db = array( 'SkipToMainContentAccessKey' => 'VarChar(1)' ); static $has_one = array( 'FacebookLogo' => 'Image' ); public function updateCMSFields(FieldList $fields) { $tf2 = new TextField('SkipToMainContentAccessKey'); $tf2->setMaxLength(1); $fields->addFieldToTab('Root.FacebookMetadata', $tf2); $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); $fields->addFieldToTab("Root.FacebookMetadata", new ImageField("FacebookLogo", _t('Facebook.METADATA_LOGO', 'Image that will show in facebook when linking to this site. The image should be a square'))); } } ?>
Create weatherAPI var for openweathermap forecast
var primed = angular.module('primed', ['ngRoute', 'ngResource']); primed.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'pages/home.html', controller: 'homeController' }) .when('/forecast', { templateUrl: 'pages/forecast.html', controller: 'forecastController' }); }); //SERVICE primed.service('cityService', function() { this.city = "Denver, CO"; }); //CONTROLLERS primed.controller('homeController', ['$scope', 'cityService', function($scope, cityService) { $scope.city = cityService.city; $scope.$watch('city', function() { cityService.city = $scope.city; }); }]); primed.controller('forecastController', ['$scope', '$resource', 'cityService', function($scope, $resource, cityService) { $scope.city = cityService.city; $scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', { callback: 'JSON_CALLBACK' }, { get: { method: 'JSONP' }}); }]);
var primed = angular.module('primed', ['ngRoute', 'ngResource']); primed.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'pages/home.html', controller: 'homeController' }) .when('/forecast', { templateUrl: 'pages/forecast.html', controller: 'forecastController' }); }); //SERVICE primed.service('cityService', function() { this.city = "Denver, CO"; }); //CONTROLLERS primed.controller('homeController', ['$scope', 'cityService', function($scope, cityService) { $scope.city = cityService.city; $scope.$watch('city', function() { cityService.city = $scope.city; }); }]); primed.controller('forecastController', ['$scope', '$resource', 'cityService', function($scope, $resource, cityService) { $scope.city = cityService.city; }]);
Return 0 tracks in case of error
from flask import Module, render_template, url_for, redirect, session, escape, request from sqlobject.main import SQLObjectNotFound from muzicast.web.util import is_first_run from muzicast.meta import Track main = Module(__name__) def top_tracks(n): """ Returns the top n tracks """ #TODO(nikhil) fix this to use statistics try: return [Track.get(i) for i in range(1, n+1)] except SQLObjectNotFound: return [] def recently_played(n): """ Returns n latest played tracks """ #TODO(nikhil) fix this to use statistics try: return [Track.get(i) for i in range(1, n+1)] except SQLObjectNotFound: return [] @main.route('/') def index(): #just do first run check if is_first_run(): return redirect(url_for('admin.index')) # TODO: will need attributes for template return render_template('home.html', top_tracks=top_tracks, recently_played=recently_played)
from flask import Module, render_template, url_for, redirect, session, escape, request from muzicast.web.util import is_first_run from muzicast.meta import Track main = Module(__name__) def top_tracks(n): """ Returns the top n tracks """ #TODO(nikhil) fix this to use statistics return [Track.get(i) for i in range(1, n+1)] def recently_played(n): """ Returns n latest played tracks """ #TODO(nikhil) fix this to use statistics return [Track.get(i) for i in range(1, n+1)] @main.route('/') def index(): #just do first run check if is_first_run(): return redirect(url_for('admin.index')) # TODO: will need attributes for template return render_template('home.html', top_tracks=top_tracks, recently_played=recently_played)
Check empty image + missing alt attribute.
<li class="news-list-item"> <a class="news-list-item-link" href="{{ $news->uri() }}"> @empty (!$news->image) <img class="news-list-item-image" src="{{ $news->present()->image(540, 400) }}" width="{{ $news->image->width }}" height="{{ $news->image->height }}" alt="{{ $news->image->alt_attribute }}"> @endempty <div class="news-list-item-info"> <h2 class="news-list-item-title">{{ $news->title }}</h2> <div class="news-list-item-date">{{ $news->present()->dateLocalized }}</div> @empty(!$news->summary) <div class="news-list-item-summary">{{ $news->summary }}</div> @endempty </div> </a> </li>
<li class="news-list-item"> <a class="news-list-item-link" href="{{ $news->uri() }}"> <img class="news-list-item-image" src="{{ $news->present()->image(540, 400) }}" width="{{ $news->image->width }}" height="{{ $news->image->height }}" alt=""> <div class="news-list-item-info"> <h2 class="news-list-item-title">{{ $news->title }}</h2> <div class="news-list-item-date">{{ $news->present()->dateLocalized }}</div> @empty(!$news->summary) <div class="news-list-item-summary">{{ $news->summary }}</div> @endempty </div> </a> </li>
Fix mailbox password type password
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Input, Label } from 'react-components'; const UnlockForm = ({ password, setPassword }) => { return ( <> <Label htmlFor="password">{c('Label').t`Mailbox password`}</Label> <Input type="password" name="password" autoFocus autoCapitalize="off" autoCorrect="off" id="password" required className="w100 mb1" value={password} placeholder={c('Placeholder').t`Mailbox password`} onChange={({ target: { value } }) => setPassword(value)} data-cy-login="mailbox password" /> </> ); }; UnlockForm.propTypes = { password: PropTypes.string, setPassword: PropTypes.func }; export default UnlockForm;
import React from 'react'; import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Input, Label } from 'react-components'; const UnlockForm = ({ password, setPassword }) => { return ( <> <Label htmlFor="password">{c('Label').t`Mailbox password`}</Label> <Input type="text" name="password" autoFocus autoCapitalize="off" autoCorrect="off" id="password" required className="w100 mb1" value={password} placeholder={c('Placeholder').t`Mailbox password`} onChange={({ target: { value } }) => setPassword(value)} data-cy-login="mailbox password" /> </> ); }; UnlockForm.propTypes = { password: PropTypes.string, setPassword: PropTypes.func }; export default UnlockForm;
Fix super dumb mistake causing all test runs to hit tests folder. This causes integration level tests to run both test suites. Oops!
""" Fabric's own fabfile. """ from __future__ import with_statement import nose from fabric.api import abort, local, task import tag from utils import msg @task(default=True) def test(args=None): """ Run all unit tests and doctests. Specify string argument ``args`` for additional args to ``nosetests``. """ # Default to explicitly targeting the 'tests' folder, but only if nothing # is being overridden. tests = "" if args else " tests" default_args = "-sv --with-doctest --nologcapture --with-color %s" % tests default_args += (" " + args) if args else "" nose.core.run_exit(argv=[''] + default_args.split()) @task def upload(): """ Build, register and upload to PyPI """ with msg("Uploading to PyPI"): local('python setup.py sdist register upload') @task def release(force='no'): """ Tag, push tag to Github, & upload new version to PyPI. """ tag.tag(force=force, push='yes') upload()
""" Fabric's own fabfile. """ from __future__ import with_statement import nose from fabric.api import abort, local, task import tag from utils import msg @task(default=True) def test(args=None): """ Run all unit tests and doctests. Specify string argument ``args`` for additional args to ``nosetests``. """ default_args = "-sv --with-doctest --nologcapture --with-color tests" default_args += (" " + args) if args else "" nose.core.run_exit(argv=[''] + default_args.split()) @task def upload(): """ Build, register and upload to PyPI """ with msg("Uploading to PyPI"): local('python setup.py sdist register upload') @task def release(force='no'): """ Tag, push tag to Github, & upload new version to PyPI. """ tag.tag(force=force, push='yes') upload()
Add command-line option to set port.
#!/usr/bin/env python import random from twisted.protocols import amp from twisted.internet import reactor from twisted.internet.protocol import Factory from twisted.python import usage port = 1234 _rand = random.Random() class Options(usage.Options): optParameters = [ ["port", "p", port, "server port"], ] class RollDice(amp.Command): arguments = [('sides', amp.Integer())] response = [('result', amp.Integer())] class Dice(amp.AMP): def roll(self, sides=6): """Return a random integer from 1 to sides""" result = _rand.randint(1, sides) return {'result': result} RollDice.responder(roll) def main(): options = Options() try: options.parseOptions() except usage.UsageError, err: print "%s: %s" % (sys.argv[0], err) print "%s: Try --help for usage details" % sys.argv[0] sys.exit(1) port = int(options["port"]) pf = Factory() pf.protocol = Dice reactor.listenTCP(port, pf) reactor.run() if __name__ == '__main__': main()
#!/usr/bin/env python import random from twisted.protocols import amp port = 1234 _rand = random.Random() class RollDice(amp.Command): arguments = [('sides', amp.Integer())] response = [('result', amp.Integer())] class Dice(amp.AMP): def roll(self, sides=6): """Return a random integer from 1 to sides""" result = _rand.randint(1, sides) return {'result': result} RollDice.responder(roll) def main(): from twisted.internet import reactor from twisted.internet.protocol import Factory pf = Factory() pf.protocol = Dice reactor.listenTCP(port, pf) reactor.run() if __name__ == '__main__': main()
Fix typo on API URL
var request = require('request'); var Scholarcheck = function(apiKey) { this.apiUrl = "https://app.scholarcheck.io/api/v1/"; this.apiKey = apiKey || ''; }; Scholarcheck.prototype._apiCall = function(endpoint, callback) { var options = { url: this.apiUrl + endpoint, headers: { 'Token': this.apiKey }, rejectUnauthorized: false }; //rejectUnauthorized must be true until the SSL cert is changed to include api.scholarcheck.io request(options, function(err, res, body) { callback(err, JSON.parse(body)); }); }; Scholarcheck.prototype.valid = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { return cb(err); } return cb(null, data.valid); }); }; Scholarcheck.prototype.institution = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { cb(err); } return cb(null, data.institution); }); }; Scholarcheck.prototype.rawData = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { return cb(err); } return cb(null, data); }); }; module.exports = Scholarcheck;
var request = require('request'); var Scholarcheck = function(apiKey) { this.apiUrl = "https://api.scholarcheck.io/api/v1/"; this.apiKey = apiKey || ''; }; Scholarcheck.prototype._apiCall = function(endpoint, callback) { var options = { url: this.apiUrl + endpoint, headers: { 'Token': this.apiKey }, rejectUnauthorized: false }; //rejectUnauthorized must be true until the SSL cert is changed to include api.scholarcheck.io request(options, function(err, res, body) { callback(err, JSON.parse(body)); }); }; Scholarcheck.prototype.valid = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { return cb(err); } return cb(null, data.valid); }); }; Scholarcheck.prototype.institution = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { cb(err); } return cb(null, data.institution); }); }; Scholarcheck.prototype.rawData = function(email, cb) { var apiReq = 'email/' + email; this._apiCall(apiReq, function(err, data) { if (!!err) { return cb(err); } return cb(null, data); }); }; module.exports = Scholarcheck;
Reduce test timeout to 60 seconds Tests have been split into smaller units
package com.github.triceo.splitlog; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.rules.Timeout; import org.junit.runner.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all Splitlog tests. Will enforce a default timeout and add * some useful test execution logging. */ public abstract class AbstractSplitlogTest { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSplitlogTest.class); @Rule public Timeout globalTimeout = new Timeout((int) TimeUnit.MINUTES.toMillis(1)); @Rule public TestRule watchman = new TestWatcher() { @Override protected void finished(final Description d) { AbstractSplitlogTest.LOGGER.info("----- Finished test: {}\n", d); } @Override protected void starting(final Description d) { AbstractSplitlogTest.LOGGER.info("----- Starting test: {}", d); } }; }
package com.github.triceo.splitlog; import java.util.concurrent.TimeUnit; import org.junit.Rule; import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.rules.Timeout; import org.junit.runner.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all Splitlog tests. Will enforce a default timeout and add * some useful test execution logging. */ public abstract class AbstractSplitlogTest { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSplitlogTest.class); @Rule public Timeout globalTimeout = new Timeout((int) TimeUnit.MINUTES.toMillis(2)); @Rule public TestRule watchman = new TestWatcher() { @Override protected void finished(final Description d) { AbstractSplitlogTest.LOGGER.info("----- Finished test: {}\n", d); } @Override protected void starting(final Description d) { AbstractSplitlogTest.LOGGER.info("----- Starting test: {}", d); } }; }
Add firefox and ie to protractor capable browsers
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], multiCapabilities: [ { 'browserName': 'firefox' }, { 'browserName': 'chrome' }, { 'browserName': 'internet explorer' } ], seleniumAddress: 'http://localhost:4444/wd/hub', baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.e2e.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } };
// Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); exports.config = { allScriptsTimeout: 11000, specs: [ './src/**/*.e2e-spec.ts' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function() {} }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.e2e.json') }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); } };
Improve integration test tear down functionality
package com.centurylink.cloud.sdk.servers.services; import com.centurylink.cloud.sdk.servers.AbstractServersSdkTest; import com.centurylink.cloud.sdk.servers.client.domain.server.metadata.ServerMetadata; import com.centurylink.cloud.sdk.servers.services.domain.Response; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Inject; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import static com.centurylink.cloud.sdk.servers.services.TestServerSupport.anyServerConfig; /** * @author ilya.drabenia */ @Test(groups = "LongRunning") public class CreateServerAsyncTest extends AbstractServersSdkTest { @Inject ServerService serverService; Response<ServerMetadata> createServerResponse; @Test public void testCreateServerAsync() throws Exception { ListenableFuture<Response<ServerMetadata>> future = serverService.createAsync(anyServerConfig().name("CSAC")); createServerResponse = future.get(); assert createServerResponse.getResult().getId() != null; } @AfterMethod public void deleteTestServer() { createServerResponse .waitUntilComplete(); serverService .delete(createServerResponse.getResult().asRefById()) .waitUntilComplete(); } }
package com.centurylink.cloud.sdk.servers.services; import com.centurylink.cloud.sdk.servers.AbstractServersSdkTest; import com.centurylink.cloud.sdk.servers.client.domain.server.metadata.ServerMetadata; import com.centurylink.cloud.sdk.servers.services.domain.Response; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Inject; import org.testng.annotations.AfterMethod; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import static com.centurylink.cloud.sdk.servers.services.TestServerSupport.anyServerConfig; /** * @author ilya.drabenia */ @Test(groups = "LongRunning") public class CreateServerAsyncTest extends AbstractServersSdkTest { @Inject ServerService serverService; Response<ServerMetadata> createServerResponse; @Test public void testCreateServerAsync() throws Exception { ListenableFuture<Response<ServerMetadata>> future = serverService.createAsync(anyServerConfig().name("CSAC")); createServerResponse = future.get(); assert createServerResponse.getResult().getId() != null; } @AfterMethod public void deleteTestServer() { createServerResponse .waitUntilComplete(); serverService .delete(createServerResponse.getResult().asRefById()) .waitUntilComplete(); } }
[REF] Optimize (only look for DOCTYPE at the start of the string) git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@61820 b456876b-0849-0410-b77d-98878d47e9d5
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function smarty_prefilter_log_tpl($source, $smarty) { global $prefs; if ($prefs['log_tpl'] != 'y') { return $source; } $current_file = $smarty->_current_file; // Refrain from logging for some templates if ( strpos($smarty->template_resource, 'eval:') === 0 || // Evaluated templates preg_match('/^<!DOCTYPE /', $source) || // templates that generate a DOCTYPE, which must be output first strpos($current_file, '/mail/') !== false // email tpls ) { return $source; } return '<!-- TPL: ' . $current_file . ' -->' . $source . '<!-- /TPL: ' . $current_file . ' -->'; }
<?php // (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id$ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } function smarty_prefilter_log_tpl($source, $smarty) { global $prefs; if ($prefs['log_tpl'] != 'y') { return $source; } $current_file = $smarty->_current_file; // Refrain from logging for some templates if ( strpos($smarty->template_resource, 'eval:') === 0 || // Evaluated templates strpos($source, '<!DOCTYPE ') === 0 || // templates that generate a DOCTYPE, which must be output first strpos($current_file, '/mail/') !== false // email tpls ) { return $source; } return '<!-- TPL: ' . $current_file . ' -->' . $source . '<!-- /TPL: ' . $current_file . ' -->'; }
Remove duplicate usage of describe
var assert = require("assert"); var documents = require("../lib/documents"); var DocumentConverter = documents.DocumentConverter; var test = require("./testing").test; describe('DocumentConverter', function() { test('should convert document containing one paragraph to single p element', function() { var document = new documents.Document([ paragraphOfText("Hello.") ]); var converter = new DocumentConverter(); return converter.convertToHtml(document).then(function(result) { assert.equal("<p>Hello.</p>", result.html); }); }) test('should convert document containing multiple paragraphs to multiple p elements', function() { var document = new documents.Document([ paragraphOfText("Hello."), paragraphOfText("Goodbye.") ]); var converter = new DocumentConverter(); return converter.convertToHtml(document).then(function(result) { assert.equal("<p>Hello.</p><p>Goodbye.</p>", result.html); }); }) }); function paragraphOfText(text) { var run = runOfText(text); return new documents.Paragraph([run]); } function runOfText(text) { var textElement = new documents.Text(text); return new documents.Run([textElement]); }
var assert = require("assert"); var documents = require("../lib/documents"); var DocumentConverter = documents.DocumentConverter; var test = require("./testing").test; describe('DocumentConverter', function() { test('should convert document containing one paragraph to single p element', function() { var document = new documents.Document([ paragraphOfText("Hello.") ]); var converter = new DocumentConverter(); return converter.convertToHtml(document).then(function(result) { assert.equal("<p>Hello.</p>", result.html); }); }) }); describe('DocumentConverter', function() { test('should convert document containing multiple paragraphs to multiple p elements', function() { var document = new documents.Document([ paragraphOfText("Hello."), paragraphOfText("Goodbye.") ]); var converter = new DocumentConverter(); return converter.convertToHtml(document).then(function(result) { assert.equal("<p>Hello.</p><p>Goodbye.</p>", result.html); }); }) }); function paragraphOfText(text) { var run = runOfText(text); return new documents.Paragraph([run]); } function runOfText(text) { var textElement = new documents.Text(text); return new documents.Run([textElement]); }
Change EnterpriseBeanTest not to rely on @Stateless beans preserving state
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.enterprise; import javax.ejb.Stateful; @Stateful public class Castle { private boolean pinged; public boolean isPinged() { return pinged; } public void ping() { this.pinged = true; } }
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.tests.enterprise; import javax.ejb.Stateless; @Stateless public class Castle { private boolean pinged; public boolean isPinged() { return pinged; } public void ping() { this.pinged = true; } }
Add optional editor parameter to constructor. Add setCanvasView method.
function PPApplication(canvasName, editor) { this.canvasName = canvasName; if (editor != null ) { this.setEditController(editor); } } PPApplication.prototype.setEditController = function (controller) { this.editController = controller; if(this.tournament != null ) { this.editController.setTournament(this.tournament); } } PPApplication.prototype.setCanvasView = function (view) { this.canvasView = view; var canvas = $(this.canvasName); var self = this; this.canvasView.setCanvas(canvas); canvas.onclick = function handleClick (e) { self.canvasView.handleClick(e); } } PPApplication.prototype.setTournament = function ( tObj ) { this.tournament = tObj; this.setCanvasView( new PPCanvasView(this.tournament) ); if (this.editController != null ) { this.editController.setTournament(this.tournament); } } PPApplication.prototype.titleChanged = function (id, evt) { this.tournament.titleChanged(id,evt); } PPApplication.prototype.redraw = function () { this.canvasView.redraw(); }
function PPApplication(canvasName) { this.canvasName = canvasName; } PPApplication.prototype.setEditController = function (controller) { this.editController = controller; this.editController.setTournament(this.tournament); } PPApplication.prototype.setTournament = function ( tObj ) { this.tournament = tObj; this.canvasView = new PPCanvasView(this.tournament); var canvas = $(this.canvasName); var self = this; this.canvasView.setCanvas(canvas); canvas.onclick = function handleClick (e) { self.canvasView.handleClick(e); } this.setEditController(new PPEditController()); } PPApplication.prototype.titleChanged = function (id, evt) { this.tournament.titleChanged(id,evt); } PPApplication.prototype.redraw = function () { this.canvasView.redraw(); }
Change tender init handlers names
from pyramid.events import subscriber from openprocurement.tender.core.events import TenderInitializeEvent from openprocurement.tender.core.utils import get_now, calculate_business_date @subscriber(TenderInitializeEvent, procurementMethodType="reporting") def tender_init_handler_1(event): """ initialization handler for tenders """ event.tender.date = get_now() @subscriber(TenderInitializeEvent, procurementMethodType="negotiation") def tender_init_handler_2(event): """ initialization handler for tenders """ tender = event.tender tender.date = get_now() if tender.lots: for lot in tender.lots: lot.date = get_now() @subscriber(TenderInitializeEvent, procurementMethodType="negotiation.quick") def tender_init_handler_3(event): """ initialization handler for tenders """ tender = event.tender tender.date = get_now() if tender.lots: for lot in tender.lots: lot.date = get_now()
from pyramid.events import subscriber from openprocurement.tender.core.events import TenderInitializeEvent from openprocurement.tender.core.utils import get_now, calculate_business_date @subscriber(TenderInitializeEvent, procurementMethodType="reporting") def tender_init_handler(event): """ initialization handler for tenders """ event.tender.date = get_now() @subscriber(TenderInitializeEvent, procurementMethodType="negotiation") def tender_init_handler(event): """ initialization handler for tenders """ tender = event.tender tender.date = get_now() if tender.lots: for lot in tender.lots: lot.date = get_now() @subscriber(TenderInitializeEvent, procurementMethodType="negotiation.quick") def tender_init_handler(event): """ initialization handler for tenders """ tender = event.tender tender.date = get_now() if tender.lots: for lot in tender.lots: lot.date = get_now()
Add configuration properties for legend title specifications.
import {GuideTitleStyle} from './constants'; import guideMark from './guide-mark'; import {lookup} from './guide-util'; import {TextMark} from '../marks/marktypes'; import {LegendTitleRole} from '../marks/roles'; import {addEncode, encoder} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter; encode.enter = enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero }; addEncode(enter, 'align', lookup('titleAlign', spec, config)); addEncode(enter, 'baseline', lookup('titleBaseline', spec, config)); addEncode(enter, 'fill', lookup('titleColor', spec, config)); addEncode(enter, 'font', lookup('titleFont', spec, config)); addEncode(enter, 'fontSize', lookup('titleFontSize', spec, config)); addEncode(enter, 'fontWeight', lookup('titleFontWeight', spec, config)); addEncode(enter, 'limit', lookup('titleLimit', spec, config)); encode.exit = { opacity: zero }; encode.update = { opacity: {value: 1}, text: encoder(spec.title) }; return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }
import {GuideTitleStyle} from './constants'; import guideMark from './guide-mark'; import {TextMark} from '../marks/marktypes'; import {LegendTitleRole} from '../marks/roles'; import {addEncode} from '../encode/encode-util'; export default function(spec, config, userEncode, dataRef) { var zero = {value: 0}, title = spec.title, encode = {}, enter; encode.enter = enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero }; addEncode(enter, 'align', config.titleAlign); addEncode(enter, 'baseline', config.titleBaseline); addEncode(enter, 'fill', config.titleColor); addEncode(enter, 'font', config.titleFont); addEncode(enter, 'fontSize', config.titleFontSize); addEncode(enter, 'fontWeight', config.titleFontWeight); addEncode(enter, 'limit', config.titleLimit); encode.exit = { opacity: zero }; encode.update = { opacity: {value: 1}, text: title && title.signal ? {signal: title.signal} : {value: title + ''} }; return guideMark(TextMark, LegendTitleRole, GuideTitleStyle, null, dataRef, encode, userEncode); }
Add bidirectional toggle to storybook closes OUT-4253 flag=none Test-plan: - Find bidirectional toggle, ensure rtl / ltr function as expected Change-Id: I15d61906f7ff2f8202b5bac51418ec9fa56b3c20 Reviewed-on: https://gerrit.instructure.com/c/canvas-lms/+/258581 Tested-by: Service Cloud Jenkins <9144042a601061f88f1e1d7a1753ea3e2972119d@instructure.com> Reviewed-by: Michael Brewer-Davis <785693f4c81267e5b88c0f98d39b56a39a2b6910@instructure.com> Reviewed-by: Augusto Callejas <7d9b9fd126d23d111f693e51511b33ea0e7192f6@instructure.com> QA-Review: Martin Yosifov <6a3824bf5c535ee1ddd50b39e2ac9b6ba130ccb0@instructure.com> Product-Review: Brian Watson <4411c2aac809443ec63e2dd517de0f2dbc7408c6@instructure.com>
import React from 'react' import {ApplyTheme} from '@instructure/ui-themeable' import {ApplyTextDirection} from '@instructure/ui-i18n' import '@instructure/canvas-high-contrast-theme' import '@instructure/canvas-theme' export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, } export const globalTypes = { canvasTheme: { name: 'Canvas Theme', description: 'Default or High Contrast', defaultValue: 'canvas', toolbar: { icon: 'user', items: ['canvas', 'canvas-high-contrast'] } }, bidirectional: { name: 'Bidirectional', description: 'Left-to-right or Right-to-left', defaultValue: 'ltr', toolbar: { icon: 'transfer', items: ['ltr', 'rtl'] } } } const canvasThemeProvider = (Story, context) => { const canvasTheme = context.globals.canvasTheme return ( <ApplyTheme theme={ApplyTheme.generateTheme(canvasTheme)}> <Story {...context}/> </ApplyTheme> ) } const bidirectionalProvider = (Story, context) => { const direction = context.globals.bidirectional return ( <ApplyTextDirection dir={direction}> <Story {...context}/> </ApplyTextDirection> ) } export const decorators = [canvasThemeProvider, bidirectionalProvider]
import React from 'react' import {ApplyTheme} from '@instructure/ui-themeable' import '@instructure/canvas-high-contrast-theme' import '@instructure/canvas-theme' export const parameters = { actions: { argTypesRegex: "^on[A-Z].*" }, } export const globalTypes = { canvasTheme: { name: 'Canvas Theme', description: 'Default or High Contrast', defaultValue: 'canvas', toolbar: { icon: 'user', items: ['canvas', 'canvas-high-contrast'] } } } const canvasThemeProvider = (Story, context) => { const canvasTheme = context.globals.canvasTheme return ( <ApplyTheme theme={ApplyTheme.generateTheme(canvasTheme)}> <Story {...context}/> </ApplyTheme> ) } export const decorators = [canvasThemeProvider]
Increase a bit verbosity of tests so people know which test failed
#!/usr/bin/env python import glob import os import sys import unittest import common program = None if len(sys.argv) < 2: raise ValueError('Need at least 2 parameters: runtests.py <build-dir> ' '<test-module-1> <test-module-2> ...') buildDir = sys.argv[1] files = sys.argv[2:] common.importModules(buildDir=buildDir) dir = os.path.split(os.path.abspath(__file__))[0] os.chdir(dir) def gettestnames(): names = map(lambda x: x[:-3], files) return names suite = unittest.TestSuite() loader = unittest.TestLoader() for name in gettestnames(): if program and program not in name: continue suite.addTest(loader.loadTestsFromName(name)) testRunner = unittest.TextTestRunner(verbosity=2) testRunner.run(suite)
#!/usr/bin/env python import glob import os import sys import unittest import common program = None if len(sys.argv) < 2: raise ValueError('Need at least 2 parameters: runtests.py <build-dir> ' '<test-module-1> <test-module-2> ...') buildDir = sys.argv[1] files = sys.argv[2:] common.importModules(buildDir=buildDir) dir = os.path.split(os.path.abspath(__file__))[0] os.chdir(dir) def gettestnames(): names = map(lambda x: x[:-3], files) return names suite = unittest.TestSuite() loader = unittest.TestLoader() for name in gettestnames(): if program and program not in name: continue suite.addTest(loader.loadTestsFromName(name)) testRunner = unittest.TextTestRunner() testRunner.run(suite)
Add global methods to pause and resume simulation These will eventually be hooked up to buttons in the DOM. Signed-off-by: Zac Delventhal <593147d2808cd66b7e2ad59ca4b0c07d6c52cddd@gmail.com>
import * as settings from './settings.js'; import { createView, getFrameRenderer, } from './view.js'; import { separateBodies, simulateFrame, } from './simulation.js'; import { getRandomBody, } from './meebas/bodies.js'; import { range, } from './utils/arrays.js'; const { width, height } = settings.tank; const view = createView(width, height); const renderFrame = getFrameRenderer(view); /** @type {Object<string, any>} */ const anyWindow = window; const MeebaFarm = {}; anyWindow.MeebaFarm = MeebaFarm; MeebaFarm.bodies = range(settings.simulation.bodies).map(getRandomBody); separateBodies(MeebaFarm.bodies); /** @type {boolean} */ let isRunning; /** @param {number} lastTick */ const simulate = (lastTick) => { if (isRunning) { const thisTick = performance.now(); MeebaFarm.bodies = simulateFrame(MeebaFarm.bodies, lastTick, thisTick); setTimeout(() => simulate(thisTick), 8); } }; const render = () => { if (isRunning) { renderFrame(MeebaFarm.bodies); requestAnimationFrame(render); } }; MeebaFarm.pause = () => { isRunning = false; }; MeebaFarm.resume = () => { isRunning = true; simulate(performance.now()); requestAnimationFrame(render); }; // eslint-disable-next-line no-console console.log('Simulating with seed:', settings.seed); MeebaFarm.resume();
import * as settings from './settings.js'; import { createView, getFrameRenderer, } from './view.js'; import { separateBodies, simulateFrame, } from './simulation.js'; import { getRandomBody, } from './meebas/bodies.js'; import { range, } from './utils/arrays.js'; const { width, height } = settings.tank; const view = createView(width, height); const renderFrame = getFrameRenderer(view); /** @type {Object<string, any>} */ const anyWindow = window; const MeebaFarm = {}; anyWindow.MeebaFarm = MeebaFarm; MeebaFarm.bodies = range(settings.simulation.bodies).map(getRandomBody); separateBodies(MeebaFarm.bodies); /** @param {number} lastTick */ const simulate = (lastTick) => { const thisTick = performance.now(); MeebaFarm.bodies = simulateFrame(MeebaFarm.bodies, lastTick, thisTick); setTimeout(() => simulate(thisTick), 8); }; const render = () => { renderFrame(MeebaFarm.bodies); requestAnimationFrame(render); }; // eslint-disable-next-line no-console console.log('Simulating with seed:', settings.seed); simulate(performance.now()); requestAnimationFrame(render);
Move S3 bucket connection into `upload_image`
# -*- coding: utf-8 -*- import StringIO import shortuuid from boto.s3.connection import S3Connection from ga import settings def upload_image_from_pil_image(image): output = StringIO.StringIO() image.save(output, 'JPEG') output.name = 'file' return upload_image(output) def upload_image(stream): conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET) bucket = conn.get_bucket(settings.AWS_BUCKET) key = bucket.new_key(shortuuid.uuid() + '.jpg') key.set_contents_from_string(stream.getvalue()) key.set_metadata('Content-Type', 'image/jpeg') key.set_acl('public-read') return key.generate_url(expires_in=0, query_auth=False, force_http=True)
# -*- coding: utf-8 -*- import StringIO import shortuuid from boto.s3.connection import S3Connection from ga import settings conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET) bucket = conn.get_bucket(settings.AWS_BUCKET) def upload_image_from_pil_image(image): output = StringIO.StringIO() image.save(output, 'JPEG') output.name = 'file' return upload_image(output) def upload_image(stream): uuid = shortuuid.uuid() key = bucket.new_key(uuid + '.jpg') key.set_contents_from_string(stream.getvalue()) key.set_metadata('Content-Type', 'image/jpeg') key.set_acl('public-read') return key.generate_url(expires_in=0, query_auth=False, force_http=True)
Write csv line even if msgstr is empty
<? $file = fopen($argv[1], 'r'); $msgid = false; $msgstr = false; while( ($line = fgets($file)) ) { if(preg_match('/msgid\s"(.*)"/U', $line, $matches)) { $msgid = '"'.$matches[1].'"'; } else if(preg_match('/msgstr\s"(.*)"/U', $line, $matches)) { $msgstr = '"'.$matches[1].'"'; if($msgid != '""') { echo $msgid.';'.$msgstr."\n"; } else { $msgid = false; } } }
<? $file = fopen($argv[1], 'r'); $msgid = false; $msgstr = false; while( ($line = fgets($file)) ) { if(preg_match('/msgid\s"(.*)"/U', $line, $matches)) { $msgid = '"'.$matches[1].'"'; } else if(preg_match('/msgstr\s"(.*)"/U', $line, $matches)) { $msgstr = '"'.$matches[1].'"'; if($msgstr != '""' && $msgid != '""') { echo $msgid.';'.$msgstr."\n"; } else { $msgid = false; } } }
Add homepage to plugin details
<?php namespace Romanov\ClearCacheWidget; use System\Classes\PluginBase; class Plugin extends PluginBase { public function pluginDetails() { return [ 'name' => 'romanov.clearcachewidget::lang.plugin.name', 'description' => 'romanov.clearcachewidget::lang.plugin.description', 'author' => 'Alexander Romanov', 'icon' => 'icon-trash', 'homepage' => 'https://github.com/romanov-acc/octobercms_clearcachewidget' ]; } public function registerReportWidgets() { return [ 'Romanov\ClearCacheWidget\ReportWidgets\ClearCache' => [ 'label' => 'romanov.clearcachewidget::lang.plugin.name', 'context' => 'dashboard' ] ]; } }
<?php namespace Romanov\ClearCacheWidget; use System\Classes\PluginBase; class Plugin extends PluginBase { public function pluginDetails() { return [ 'name' => 'romanov.clearcachewidget::lang.plugin.name', 'description' => 'romanov.clearcachewidget::lang.plugin.description', 'author' => 'Alexander Romanov', 'icon' => 'icon-trash' ]; } public function registerReportWidgets() { return [ 'Romanov\ClearCacheWidget\ReportWidgets\ClearCache' => [ 'label' => 'romanov.clearcachewidget::lang.plugin.name', 'context' => 'dashboard' ] ]; } }
Access yaml resource using absolute path; hopefully this fixes travis
package folioxml.config; import java.io.InputStream; import java.nio.file.Paths; import java.util.Map; /** * Created by nathanael on 5/25/15. */ public class TestConfig { public static String slash(){ return System.getProperty("file.separator"); } public static Map<String,InfobaseSet> getAllUncached(){ InputStream foo = TestConfig.class.getResourceAsStream("/test.yaml"); String classDir = TestConfig.class.getProtectionDomain().getCodeSource().getLocation().getFile(); String workingDir = Paths.get(classDir).getParent().getParent().getParent().getParent().toAbsolutePath().toString(); return YamlInfobaseSet.parseYaml(workingDir,foo); } public static Map<String,InfobaseSet> getAll(){ if (configs == null){ configs = getAllUncached(); } return configs; } static Map<String,InfobaseSet> configs; public static InfobaseConfig getFolioHlp(){ return getAll().get("folio_help").getFirst(); } public static InfobaseSet get(String configName) { return getAll().get(configName); } public static InfobaseConfig getFirst(String configName) { return getAll().get(configName).getFirst(); } }
package folioxml.config; import java.io.InputStream; import java.nio.file.Paths; import java.util.Map; /** * Created by nathanael on 5/25/15. */ public class TestConfig { public static String slash(){ return System.getProperty("file.separator"); } public static Map<String,InfobaseSet> getAllUncached(){ InputStream foo = TestConfig.class.getResourceAsStream("../../test.yaml"); String classDir = TestConfig.class.getProtectionDomain().getCodeSource().getLocation().getFile(); String workingDir = Paths.get(classDir).getParent().getParent().getParent().getParent().toAbsolutePath().toString(); return YamlInfobaseSet.parseYaml(workingDir,foo); } public static Map<String,InfobaseSet> getAll(){ if (configs == null){ configs = getAllUncached(); } return configs; } static Map<String,InfobaseSet> configs; public static InfobaseConfig getFolioHlp(){ return getAll().get("folio_help").getFirst(); } public static InfobaseSet get(String configName) { return getAll().get(configName); } public static InfobaseConfig getFirst(String configName) { return getAll().get(configName).getFirst(); } }
Store processes in a global var
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) global.processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) } exports.runTask = function (task, cb) { // Stop task if running if (global.processes[task]) { global.processes[task].kill() cb() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save global.processes[task] = command cb() // Remove when done command.on('close', function () { delete global.processes[task] }) }
'use strict' const grunt = require('gruntfile-api') const fs = require('fs') const path = require('path') const spawn = require('child_process').spawn const gruntfile = fs.readFileSync(path.join(window.localStorage.getItem('current'), 'Gruntfile.js')) var processes = {} exports.getTasks = function () { return new Promise(function (resolve, reject) { grunt.init(gruntfile) let tasks = JSON.parse(grunt.getJsonTasks()) let taskList = [] for (let task in tasks) { taskList.push(task) } return resolve(taskList) }) } exports.runTask = function (task) { // Stop task if running if (processes[task]) { processes[task].kill() return } let dir = window.localStorage.getItem('current') var command = spawn('grunt', [task], {cwd: dir}) // Save processes[task] = command // Remove when done command.on('close', function () { delete processes[task] }) }
Fix open shift login check
<div id="page" class="container"> <div id="content"> <div> <h2>Welcome <?php echo $user?></h2> <?php $this->load->database(); $this->db->query("use applicationportal"); $sql = "SELECT * FROM app WHERE student_id = ?"; $lower = strtolower($user); $data[0]=$lower; $valid = $this->db->query($sql,$data); if($valid->num_rows()==0){?> <p><a href="<?=base_url('index.php/form/index')?>" class="button1">Begin Application</a></p> <?php } ?> <p><a href="#" class="button1">Appication Status</a></p> </div> </div> </div> <div id="banner" class="container"> <img src="<?=base_url('images/mizzou.jpg')?>" width="1000" height="500" alt="" /> </div> </div> </div>
<div id="page" class="container"> <div id="content"> <div> <h2>Welcome <?php echo $user?></h2> <?php $this->load->database(); $this->db->query("use applicationportal"); $sql = "SELECT * FROM app WHERE student_id = $user"; $valid = $this->db->query($sql); if($valid->num_rows()==0){?> <p><a href="<?=base_url('index.php/form/index')?>" class="button1">Begin Application</a></p> <?php } ?> <p><a href="#" class="button1">Appication Status</a></p> </div> </div> </div> <div id="banner" class="container"> <img src="<?=base_url('images/mizzou.jpg')?>" width="1000" height="500" alt="" /> </div> </div> </div>
Create copy of input array
/* * Copyright 2004-present Facebook. All Rights Reserved. */ package com.facebook.presto.operator; import com.facebook.presto.block.Block; import com.google.common.base.Preconditions; import java.util.Arrays; public class Page { private final Block[] blocks; public Page(Block... blocks) { Preconditions.checkNotNull(blocks, "blocks is null"); Preconditions.checkArgument(blocks.length > 0, "blocks is empty"); this.blocks = Arrays.copyOf(blocks, blocks.length); } public int getChannelCount() { return blocks.length; } public int getPositionCount() { return blocks[0].getPositionCount(); } public Block[] getBlocks() { return blocks.clone(); } public Block getBlock(int channel) { return blocks[channel]; } }
/* * Copyright 2004-present Facebook. All Rights Reserved. */ package com.facebook.presto.operator; import com.facebook.presto.block.Block; import com.google.common.base.Preconditions; public class Page { private final Block[] blocks; public Page(Block... blocks) { Preconditions.checkNotNull(blocks, "blocks is null"); Preconditions.checkArgument(blocks.length > 0, "blocks is empty"); this.blocks = blocks; } public int getChannelCount() { return blocks.length; } public int getPositionCount() { return blocks[0].getPositionCount(); } public Block[] getBlocks() { return blocks.clone(); } public Block getBlock(int channel) { return blocks[channel]; } }
Fix mktime returning error on no default timezone
<?php namespace Rafasamp\Sonus; class Helpers { /** * Extracts seconds from HH:MM:SS string * @param string HH:MM:SS formatted value * @return string */ public static function timestampToSeconds($string) { // Extract hour, minute, and seconds $time = explode(":", $string); // Convert to seconds (round up to nearest second) $secs = ($time[0] * 3600) + ($time[1] * 60) + (ceil($time[2])); return $secs; } /** * Converts seconds to HH:MM:SS string * @param integer $int seconds * @return string */ public static function secondsToTimestamp($int) { // Set default timezone to UTC avoiding mktime errors date_default_timezone_set('UTC'); $output = date('H:i:s', mktime(0, 0, $int)); return $output; } /** * Returns percent completion of current conversion task * @param integer $current current time in seconds * @param integer $total total time in seconds * @return integer */ public static function progressPercentage($current, $total) { // Round to the nearest percent $output = ceil(($current / $total) * 100); return $output; } }
<?php namespace Rafasamp\Sonus; class Helpers { /** * Extracts seconds from HH:MM:SS string * @param string HH:MM:SS formatted value * @return string */ public static function timestampToSeconds($string) { // Extract hour, minute, and seconds $time = explode(":", $string); // Convert to seconds (round up to nearest second) $secs = ($time[0] * 3600) + ($time[1] * 60) + (ceil($time[2])); return $secs; } /** * Converts seconds to HH:MM:SS string * @param integer $int seconds * @return string */ public static function secondsToTimestamp($int) { $output = date('H:i:s', mktime(0, 0, $int)); return $output; } /** * Returns percent completion of current conversion task * @param integer $current current time in seconds * @param integer $total total time in seconds * @return integer */ public static function progressPercentage($current, $total) { // Round to the nearest percent $output = ceil(($current / $total) * 100); return $output; } }
Fix min hp and mp
class Status { constructor(currentHp, maxHp, currentMp, maxMp) { currentHp = Math.min(currentHp, maxHp); currentHp = Math.max(currentHp, 0); currentMp = Math.min(currentMp, maxMp); currentMp = Math.max(currentMp, 0); this.currentHp = isNaN(currentHp) ? 0 : currentHp; this.currentMp = isNaN(currentMp) ? 0 : currentMp; this.maxHp = isNaN(maxHp) ? Infinity : maxHp; this.maxMp = isNaN(maxMp) ? Infinity : maxMp; Object.freeze(this); }; changeHp(nextHp) { return new Status(nextHp, this.maxHp, this.currentMp, this.maxMp); } changeMp(nextMp) { return new Status(this.currentHp, this.maxHp, nextMp, this.maxMp); } canCast(spell) { return spell.requiredMp <= this.currentMp; }; isDead() { return this.currentHp <= this.minHp; }; } module.exports = Status;
class Status { constructor(currentHp, maxHp, currentMp, maxMp) { currentHp = Math.min(currentHp, maxHp); currentMp = Math.min(currentMp, maxMp); this.currentHp = isNaN(currentHp) ? 0 : currentHp; this.currentMp = isNaN(currentMp) ? 0 : currentMp; this.maxHp = isNaN(maxHp) ? Infinity : maxHp; this.maxMp = isNaN(maxMp) ? Infinity : maxMp; Object.freeze(this); }; changeHp(nextHp) { return new Status(nextHp, this.maxHp, this.currentMp, this.maxMp); } changeMp(nextMp) { return new Status(this.currentHp, this.maxHp, nextMp, this.maxMp); } canCast(spell) { return spell.requiredMp <= this.currentMp; }; isDead() { return this.currentHp <= this.minHp; }; } module.exports = Status;
Fix /api/roms/ returning names with .nes extension
import fs from 'fs'; import path from 'path'; import {makeId, removePrefix} from '../common'; const romExtName = '.nes'; const thumbExtNames = ['.png', '.git', '.jpg', '.jpeg']; export function isRomFile(file) { return path.extname(file).toLowerCase() === romExtName; } export function getRomId(romFile) { const extName = path.extname(romFile); const baseName = path.basename(romFile, extName); return makeId(baseName); } export function getRomName(romFile) { const extName = path.extname(romFile); return path.basename(romFile, extName).trim(); } export function compareRomsByName(rom1, rom2) { const name1 = removePrefix(rom1.name, 'the ', true); const name2 = removePrefix(rom2.name, 'the ', true); return name1.localeCompare(name2); } export function findRomThumbFile(romFile) { const dirName = path.dirname(romFile); const extName = path.extname(romFile); const baseName = path.basename(romFile, extName); for (const thumbExtName of thumbExtNames) { const thumbFileName = baseName + thumbExtName; const thumbFile = path.join(dirName, thumbFileName); if (fs.existsSync(thumbFile)) { return thumbFile; } } return null; }
import fs from 'fs'; import path from 'path'; import {makeId, removePrefix} from '../common'; const romExtName = '.nes'; const thumbExtNames = ['.png', '.git', '.jpg', '.jpeg']; export function isRomFile(file) { return path.extname(file).toLowerCase() === romExtName; } export function getRomId(romFile) { const extName = path.extname(romFile); const baseName = path.basename(romFile, extName); return makeId(baseName); } export function getRomName(romFile) { return path.basename(romFile).trim(); } export function compareRomsByName(rom1, rom2) { const name1 = removePrefix(rom1.name, 'the ', true); const name2 = removePrefix(rom2.name, 'the ', true); return name1.localeCompare(name2); } export function findRomThumbFile(romFile) { const dirName = path.dirname(romFile); const extName = path.extname(romFile); const baseName = path.basename(romFile, extName); for (const thumbExtName of thumbExtNames) { const thumbFileName = baseName + thumbExtName; const thumbFile = path.join(dirName, thumbFileName); if (fs.existsSync(thumbFile)) { return thumbFile; } } return null; }
Use jQuery prop instead of attr
$(document).ready(function() { $(".additional-options-toggle").on("click", function(e) { e.preventDefault(); $("#" + $(this).data("export-section") + "_options").toggle(); }); $("#kanji_form input[name='argument']").on("click", function() { $("#kanji_form input[id='selected_levels_specific']").prop('checked', true); }); $("#vocabulary_form input[name='argument']").on("click", function() { $("#vocabulary_form input[id='selected_levels_specific']").prop('checked', true); }); $("#radicals_form input[name='argument']").on("click", function() { $("#radicals_form input[id='selected_levels_specific']").prop('checked', true); }); $("#critical_items_form").validate({ rules: { argument: { required: false, range: [1, 99] } }, messages: { argument: "Please enter a value between 1 and 99, or leave blank for a default of 75." } }); });
$(document).ready(function() { $(".additional-options-toggle").on("click", function(e) { e.preventDefault(); $("#" + $(this).data("export-section") + "_options").toggle(); }); $("#kanji_form input[name='argument']").on("click", function() { $("#kanji_form input[id='selected_levels_specific']").attr('checked', 'checked'); }); $("#vocabulary_form input[name='argument']").on("click", function() { $("#vocabulary_form input[id='selected_levels_specific']").attr('checked', 'checked'); }); $("#radicals_form input[name='argument']").on("click", function() { $("#radicals_form input[id='selected_levels_specific']").attr('checked', 'checked'); }); $("#critical_items_form").validate({ rules: { argument: { required: false, range: [1, 99] } }, messages: { argument: "Please enter a value between 1 and 99, or leave blank for a default of 75." } }); $("#kanji_form input[name='argument']").on("click", function() { $("#kanji_form input[id='selected_levels_specific']").attr('checked', 'checked'); }); });
Update balance checker struct name
package balance import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" orCommon "github.com/notegio/openrelay/common" tokenModule "github.com/notegio/openrelay/token" "github.com/notegio/openrelay/types" "math/big" ) type rpcERC20BalanceChecker struct { conn bind.ContractBackend } func (funds *rpcERC20BalanceChecker) GetBalance(tokenAsset types.AssetData, userAddrBytes *types.Address) (*big.Int, error) { token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn) if err != nil { return nil, err } return token.BalanceOf(nil, orCommon.ToGethAddress(userAddrBytes)) } func (funds *rpcERC20BalanceChecker) GetAllowance(tokenAsset types.AssetData, ownerAddress, spenderAddress *types.Address) (*big.Int, error) { token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn) if err != nil { return nil, err } return token.Allowance(nil, orCommon.ToGethAddress(ownerAddress), orCommon.ToGethAddress(spenderAddress)) } func NewRpcERC20BalanceChecker(conn bind.ContractBackend) (BalanceChecker) { return &rpcERC20BalanceChecker{conn} }
package balance import ( "github.com/ethereum/go-ethereum/accounts/abi/bind" orCommon "github.com/notegio/openrelay/common" tokenModule "github.com/notegio/openrelay/token" "github.com/notegio/openrelay/types" "math/big" ) type rpcBalanceChecker struct { conn bind.ContractBackend } func (funds *rpcBalanceChecker) GetBalance(tokenAsset types.AssetData, userAddrBytes *types.Address) (*big.Int, error) { token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn) if err != nil { return nil, err } return token.BalanceOf(nil, orCommon.ToGethAddress(userAddrBytes)) } func (funds *rpcBalanceChecker) GetAllowance(tokenAsset types.AssetData, ownerAddress, spenderAddress *types.Address) (*big.Int, error) { token, err := tokenModule.NewToken(orCommon.ToGethAddress(tokenAsset.Address()), funds.conn) if err != nil { return nil, err } return token.Allowance(nil, orCommon.ToGethAddress(ownerAddress), orCommon.ToGethAddress(spenderAddress)) } func NewRpcERC20BalanceChecker(conn bind.ContractBackend) (BalanceChecker) { return &rpcBalanceChecker{conn} }
Correct statuscode for when requested pid is not existent
package se.christianjensen.maintenance.resources; import io.dropwizard.auth.Auth; import se.christianjensen.maintenance.representation.config.UserConfiguration; import se.christianjensen.maintenance.representation.processes.Process; import se.christianjensen.maintenance.sigar.ProcessMetrics; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Path("process") @Produces(MediaType.APPLICATION_JSON) public class ProcessResource extends Resource { ProcessMetrics processMetrics; public ProcessResource(ProcessMetrics processMetrics) { this.processMetrics = processMetrics; } @Override @GET public List<Process> getRoot(@Auth UserConfiguration user) { return processMetrics.getProcesses(); } @Path("{pid}") @GET public Process getProcessByPid(@Auth UserConfiguration user, @PathParam("pid") long pid) { try { return processMetrics.getProcessByPid(pid); } catch (IllegalArgumentException e) { throw buildWebException(Response.Status.NOT_FOUND, e.getMessage()); } } }
package se.christianjensen.maintenance.resources; import io.dropwizard.auth.Auth; import se.christianjensen.maintenance.representation.config.UserConfiguration; import se.christianjensen.maintenance.representation.processes.Process; import se.christianjensen.maintenance.sigar.ProcessMetrics; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; @Path("process") @Produces(MediaType.APPLICATION_JSON) public class ProcessResource extends Resource { ProcessMetrics processMetrics; public ProcessResource(ProcessMetrics processMetrics) { this.processMetrics = processMetrics; } @Override @GET public List<Process> getRoot(@Auth UserConfiguration user) { return processMetrics.getProcesses(); } @Path("{pid}") @GET public Process getProcessByPid(@Auth UserConfiguration user, @PathParam("pid") long pid) { try { return processMetrics.getProcessByPid(pid); } catch (IllegalArgumentException e) { throw buildWebException(Response.Status.BAD_REQUEST, e.getMessage()); } } }
:muscle: Store a mapping to lists instead of single actions
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. module.exports = function(landscape) { let actions = new Map(); let tickCount = 0; return { "tick": () => new Promise(function(resolve, reject) { try { tickCount += 1; if (actions.has(tickCount)) { let thing = actions.get(tickCount).pop(); landscape[thing.method].apply(landscape, thing.args); } resolve(); } catch(error) { reject(error); } }), "at": function(when, method) { if (!actions.has(when)) actions.set(when, []); actions.get(when).push({ "when": when, "method": method, "args": [...arguments].slice(2) }); } }; };
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. module.exports = function(landscape) { let actions = new Map(); let tickCount = 0; return { "tick": () => new Promise(function(resolve, reject) { try { tickCount += 1; if (actions.has(tickCount)) { let thing = actions.get(tickCount); landscape[thing.method].apply(landscape, thing.args); } resolve(); } catch(error) { reject(error); } }), "at": function(when, method) { actions.set(when, { "when": when, "method": method, "args": [...arguments].slice(2) }); } }; };
Revert "Added missing generator commands to Lumen provider" This reverts commit 3fb2cb778edcad84c3904bd8a26a6fc843cf83d9.
<?php namespace Prettus\Repository\Providers; use Illuminate\Support\ServiceProvider; /** * Class LumenRepositoryServiceProvider * @package Prettus\Repository\Providers */ class LumenRepositoryServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $this->commands('Prettus\Repository\Generators\Commands\RepositoryCommand'); $this->app->register('Prettus\Repository\Providers\EventServiceProvider'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
<?php namespace Prettus\Repository\Providers; use Illuminate\Support\ServiceProvider; /** * Class LumenRepositoryServiceProvider * @package Prettus\Repository\Providers */ class LumenRepositoryServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $this->commands('Prettus\Repository\Generators\Commands\RepositoryCommand'); $this->commands('Prettus\Repository\Generators\Commands\TransformerCommand'); $this->commands('Prettus\Repository\Generators\Commands\PresenterCommand'); $this->commands('Prettus\Repository\Generators\Commands\EntityCommand'); $this->commands('Prettus\Repository\Generators\Commands\ValidatorCommand'); $this->commands('Prettus\Repository\Generators\Commands\ControllerCommand'); $this->commands('Prettus\Repository\Generators\Commands\BindingsCommand'); $this->app->register('Prettus\Repository\Providers\EventServiceProvider'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Update with the SecurityManager implementation.
package com.cedarsoftware.controller; import com.cedarsoftware.security.Security; import com.cedarsoftware.security.SecurityManager; import org.apache.log4j.Logger; /** * Common functionality for all Controllers. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br/> * Copyright (c) Cedar Software LLC * <br/><br/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br/><br/> * http://www.apache.org/licenses/LICENSE-2.0 * <br/><br/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class BaseController implements IBaseController { private static final Logger _log = Logger.getLogger(BaseController.class); private Security security = new SecurityManager(); public void logout() { } protected String getHID() { return security.getHID(); } protected Security getSecurity() { return security; } }
package com.cedarsoftware.controller; import com.cedarsoftware.security.Security; import com.cedarsoftware.security.SecurityManager; import org.apache.log4j.Logger; /** * Common functionality for all Controllers. * * @author John DeRegnaucourt (jdereg@gmail.com) * <br/> * Copyright (c) Cedar Software LLC * <br/><br/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <br/><br/> * http://www.apache.org/licenses/LICENSE-2.0 * <br/><br/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class BaseController implements IBaseController { private static final Logger _log = Logger.getLogger(BaseController.class); private Security security = new SecurityManager(); public void logout() { } protected String getHID() { return security.getUserId(); } protected Security getSecurity() { return security; } }
Use the first mention for saving
#!/usr/bin/env python import os import random import tweepy import config last_seen_path = os.path.join(os.path.dirname(__file__), 'last-seen') def get_api(): auth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.key, config.secret) return tweepy.API(auth) def get_last_seen(): try: return int(open(last_seen_path).read()) except: pass def save_last_seen(mentions): open(last_seen_path, 'w').write(str(mentions[0].id)) def generate_wenks(): return ' '.join(['Wenk.'] * random.randrange(1, 4)) def generate_reply(mention): return '@' + mention.user.screen_name + ' ' + generate_wenks() def should_wenk(): # 10% probability return random.randrange(-9, 1) == 0 api = get_api() mentions = api.mentions_timeline(since_id=get_last_seen()) if mentions: for mention in reversed(mentions): api.update_status(generate_reply(mention)) save_last_seen(mentions) elif should_wenk(): api.update_status(generate_wenks())
#!/usr/bin/env python import os import random import tweepy import config last_seen_path = os.path.join(os.path.dirname(__file__), 'last-seen') def get_api(): auth = tweepy.OAuthHandler(config.consumer_key, config.consumer_secret) auth.set_access_token(config.key, config.secret) return tweepy.API(auth) def get_last_seen(): try: return int(open(last_seen_path).read()) except: pass def save_last_seen(mentions): open(last_seen_path, 'w').write(str(mentions[-1].id)) def generate_wenks(): return ' '.join(['Wenk.'] * random.randrange(1, 4)) def generate_reply(mention): return '@' + mention.user.screen_name + ' ' + generate_wenks() def should_wenk(): # 10% probability return random.randrange(-9, 1) == 0 api = get_api() mentions = api.mentions_timeline(since_id=get_last_seen()) if mentions: for mention in reversed(mentions): api.update_status(generate_reply(mention)) save_last_seen(mentions) elif should_wenk(): api.update_status(generate_wenks())
Return the Throwable on error
package me.normanmaurer.niosmtp.impl.internal; import java.util.Collection; import java.util.Iterator; import me.normanmaurer.niosmtp.DeliveryRecipientStatus; import me.normanmaurer.niosmtp.DeliveryResult; public class DeliveryResultImpl implements DeliveryResult{ private final Collection<DeliveryRecipientStatus> status; private final Throwable cause; public DeliveryResultImpl(Collection<DeliveryRecipientStatus> status) { this.status = status; this.cause = null; } public DeliveryResultImpl(Throwable cause) { this.cause = cause; this.status = null; } @Override public boolean isSuccess() { return cause == null; } @Override public Throwable getCause() { return cause; } @Override public Iterator<DeliveryRecipientStatus> getRecipientStatus() { if (status == null) { return null; } return status.iterator(); } }
package me.normanmaurer.niosmtp.impl.internal; import java.util.Collection; import java.util.Iterator; import me.normanmaurer.niosmtp.DeliveryRecipientStatus; import me.normanmaurer.niosmtp.DeliveryResult; public class DeliveryResultImpl implements DeliveryResult{ private final Collection<DeliveryRecipientStatus> status; private final Throwable cause; public DeliveryResultImpl(Collection<DeliveryRecipientStatus> status) { this.status = status; this.cause = null; } public DeliveryResultImpl(Throwable cause) { this.cause = cause; this.status = null; } @Override public boolean isSuccess() { return cause == null; } @Override public Throwable getCause() { return null; } @Override public Iterator<DeliveryRecipientStatus> getRecipientStatus() { if (status == null) { return null; } return status.iterator(); } }
Fix adding google maps file in landing logic
"use strict"; const gulp = require('gulp'), rename = require('gulp-rename'), concat = require('gulp-concat'), babel = require('gulp-babel'), ngAnnotate = require('gulp-ng-annotate'), sourcemaps = require('gulp-sourcemaps'), browserSync = require('browser-sync'), scripts = { landing: landing }; module.exports = scripts; function landing() { const src = [ 'landing/app.js', 'landing/config.js', 'landing/**/*.js', '!landing/static/**/*.js' ]; const dest = 'landing/static/vendor/js/.'; return gulp .src(src) .pipe(sourcemaps.init()) .pipe(rename({ dirname: '' })) .pipe(babel({ presets: ['es2015'] })) .on('error', function(e) { console.log('>>> ERROR', e.message); this.emit('end'); }) .pipe(ngAnnotate()) .pipe(concat('app.min.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest(dest)) .pipe(browserSync.reload({stream: true})) };
"use strict"; const gulp = require('gulp'), rename = require('gulp-rename'), concat = require('gulp-concat'), babel = require('gulp-babel'), ngAnnotate = require('gulp-ng-annotate'), sourcemaps = require('gulp-sourcemaps'), browserSync = require('browser-sync'), scripts = { landing: landing }; module.exports = scripts; function landing() { const src = [ 'landing/app.js', 'landing/config.js', 'landing/**/*.js', '!landing/static/js/*.js' ]; const dest = 'landing/static/vendor/js/.'; return gulp .src(src) .pipe(sourcemaps.init()) .pipe(rename({ dirname: '' })) .pipe(babel({ presets: ['es2015'] })) .on('error', function(e) { console.log('>>> ERROR', e.message); this.emit('end'); }) .pipe(ngAnnotate()) .pipe(concat('app.min.js')) .pipe(sourcemaps.write()) .pipe(gulp.dest(dest)) .pipe(browserSync.reload({stream: true})) };
Fix double/triple fetching of random quote Since the quote is fetched during ssr, it doesn't have to be fetched on the client. Only fetch using prepare when there is no quote. The "new random quote" button will still work. This fixes the annoying flicker when the random quote change during first client render.
// @flow import React from 'react'; import { compose } from 'redux'; import { isEmpty } from 'lodash'; import prepare from 'app/utils/prepare'; import { fetchRandomQuote } from 'app/actions/QuoteActions'; import { connect } from 'react-redux'; import RandomQuote from './RandomQuote'; import { addReaction, deleteReaction } from 'app/actions/ReactionActions'; import { selectEmojis } from 'app/reducers/emojis'; import { selectRandomQuote } from 'app/reducers/quotes'; import { fetchEmojis } from 'app/actions/EmojiActions'; import loadingIndicator from 'app/utils/loadingIndicator'; import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn'; function mapStateToProps(state, props) { const emojis = selectEmojis(state); const currentQuote = selectRandomQuote(state); return { loggedIn: props.loggedIn, emojis, fetchingEmojis: state.emojis.fetching, fetching: state.quotes.fetching, currentQuote }; } const mapDispatchToProps = { fetchRandomQuote, addReaction, deleteReaction, fetchEmojis }; const LoginToSeeQuotes = () => <div>Logg inn for å se sitater.</div>; export default compose( replaceUnlessLoggedIn(LoginToSeeQuotes), connect( mapStateToProps, mapDispatchToProps ), prepare((props, dispatch) => Promise.all([ isEmpty(props.currentQuote) && dispatch(fetchRandomQuote()), dispatch(fetchEmojis()) ]) ), loadingIndicator(['currentQuote.id']) )(RandomQuote);
// @flow import React from 'react'; import { compose } from 'redux'; import prepare from 'app/utils/prepare'; import { fetchRandomQuote } from 'app/actions/QuoteActions'; import { connect } from 'react-redux'; import RandomQuote from './RandomQuote'; import { addReaction, deleteReaction } from 'app/actions/ReactionActions'; import { selectEmojis } from 'app/reducers/emojis'; import { selectRandomQuote } from 'app/reducers/quotes'; import { fetchEmojis } from 'app/actions/EmojiActions'; import loadingIndicator from 'app/utils/loadingIndicator'; import replaceUnlessLoggedIn from 'app/utils/replaceUnlessLoggedIn'; function mapStateToProps(state, props) { const emojis = selectEmojis(state); const currentQuote = selectRandomQuote(state); return { loggedIn: props.loggedIn, emojis, fetchingEmojis: state.emojis.fetching, fetching: state.quotes.fetching, currentQuote }; } const mapDispatchToProps = { fetchRandomQuote, addReaction, deleteReaction, fetchEmojis }; const LoginToSeeQuotes = () => <div>Logg inn for å se sitater.</div>; export default compose( replaceUnlessLoggedIn(LoginToSeeQuotes), prepare((props, dispatch) => Promise.all([dispatch(fetchRandomQuote()), dispatch(fetchEmojis())]) ), connect( mapStateToProps, mapDispatchToProps ), loadingIndicator(['currentQuote.id']) )(RandomQuote);
Refactor headers list() with map/collect
package com.hamishrickerby.http_server; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Created by rickerbh on 18/08/2016. */ public class Headers { private static String HEADER_SEPARATOR = ": "; Map<String, String> headers; public Headers() { headers = new HashMap<>(); } public List<String> list() { return headers.keySet().stream() .map(key -> key + HEADER_SEPARATOR + headers.get(key)) .collect(Collectors.toList()); } public void put(String key, String value) { headers.put(key, value); } public void parse(String headerString) { String[] lines = headerString.split("\r\n"); for (String line : Arrays.asList(lines)) { String[] components = line.split(":"); put(components[0].trim(), components[1].trim()); } } public String get(String key) { return headers.getOrDefault(key, ""); } }
package com.hamishrickerby.http_server; import java.util.*; /** * Created by rickerbh on 18/08/2016. */ public class Headers { private static String HEADER_SEPARATOR = ": "; Map<String, String> headers; public Headers() { headers = new HashMap<>(); } public List<String> list() { List<String> headerList = new ArrayList<>(); for (String key : headers.keySet()) { headerList.add(key + HEADER_SEPARATOR + headers.get(key)); } return headerList; } public void put(String key, String value) { headers.put(key, value); } public void parse(String headerString) { String[] lines = headerString.split("\r\n"); for (String line : Arrays.asList(lines)) { String[] components = line.split(":"); put(components[0].trim(), components[1].trim()); } } public String get(String key) { return headers.getOrDefault(key, ""); } }
Modify unit test framework to delete db during setup
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self): Base.metadata.drop_all(engine) self.session.close_all() def create_default_settings(self): about_page_setting = Setting(name='about_page_content', value='example content value') self.session.add(about_page_setting) welcome_page_setting = Setting(name='welcome_page_content', value='example welcome content <br>here') self.session.add(welcome_page_setting) round_time_sleep_setting = Setting(name='round_time_sleep', value=60) self.session.add(round_time_sleep_setting) worker_refresh_time_setting = Setting(name='worker_refresh_time', value=30) self.session.add(worker_refresh_time_setting) self.session.commit()
Change argument naming in provisioning callback function
'use strict'; var fs = require('fs'); var exec = require('child_process').exec; var plist = require('simple-plist'); var decompress = require('decompress-zip'); var which = require('which'); var provisioning = require('provisioning'); var entitlements = require('entitlements'); var rimraf = require('rimraf'); var tmp = require('temporary'); var glob = require("glob"); var output = new tmp.Dir(); module.exports = function (file, callback){ var data = {}; var unzipper = new decompress(file); unzipper.extract({ path: output.path }); unzipper.on('error', cleanUp); unzipper.on('extract', function() { var path = glob.sync(output.path + '/Payload/*/')[0]; data.metadata = plist.readFileSync(path + 'Info.plist'); if(!fs.existsSync(path + 'embedded.mobileprovision')){ return cleanUp(); } provisioning(path + 'embedded.mobileprovision', function(error, provision){ if(error){ return cleanUp(error); } data.provisioning = provision; delete data.provisioning.DeveloperCertificates; if(!which.sync('codesign')){ return cleanUp(); } entitlements(path, function(error, entitlement) { data.entitlements = entitlement; return cleanUp(); }); }); }); function cleanUp(error){ rimraf.sync(output.path); return callback(error, data); } };
'use strict'; var fs = require('fs'); var exec = require('child_process').exec; var plist = require('simple-plist'); var decompress = require('decompress-zip'); var which = require('which'); var provisioning = require('provisioning'); var entitlements = require('entitlements'); var rimraf = require('rimraf'); var tmp = require('temporary'); var glob = require("glob"); var output = new tmp.Dir(); module.exports = function (file, callback){ var data = {}; var unzipper = new decompress(file); unzipper.extract({ path: output.path }); unzipper.on('error', cleanUp); unzipper.on('extract', function() { var path = glob.sync(output.path + '/Payload/*/')[0]; data.metadata = plist.readFileSync(path + 'Info.plist'); if(!fs.existsSync(path + 'embedded.mobileprovision')){ return cleanUp(); } provisioning(path + 'embedded.mobileprovision', function(error, output){ if(error){ return cleanUp(error); } data.provisioning = output; delete data.provisioning.DeveloperCertificates; if(!which.sync('codesign')){ return cleanUp(); } entitlements(path, function(error, entitlement) { data.entitlements = entitlement; return cleanUp(); }); }); }); function cleanUp(error){ rimraf.sync(output.path); return callback(error, data); } };
Add comment explaining what test task is
var gulp = require('gulp') var connect = require('gulp-connect') var browserify = require('browserify') var source = require('vinyl-source-stream'); var gulp = require('gulp'); var mocha = require('gulp-mocha'); gulp.task('connect', function () { connect.server({ root: '', port: 4000 }) }) gulp.task('build', function() { // Grabs the app.js file return browserify('./js/app.js') // bundles it and creates a file called build.js .bundle() .pipe(source('build.js')) // saves it the js/ directory .pipe(gulp.dest('./js/')); }) gulp.task('watch', function() { gulp.watch(['./**/*', '!./js/build.js'], { interval: 500 }, ['build']) }) gulp.task('test', function() { //Creates local server, runs mocha tests, then exits process (therefore killing server) connect.server({ root: '', port: 4000 }); return gulp.src('./test/test.js').pipe(mocha()) .once('end', function () { process.exit(); }); }) gulp.task('default', ['connect', 'watch'])
var gulp = require('gulp') var connect = require('gulp-connect') var browserify = require('browserify') var source = require('vinyl-source-stream'); var gulp = require('gulp'); var mocha = require('gulp-mocha'); gulp.task('connect', function () { connect.server({ root: '', port: 4000 }) }) gulp.task('build', function() { // Grabs the app.js file return browserify('./js/app.js') // bundles it and creates a file called build.js .bundle() .pipe(source('build.js')) // saves it the js/ directory .pipe(gulp.dest('./js/')); }) gulp.task('watch', function() { gulp.watch(['./**/*', '!./js/build.js'], { interval: 500 }, ['build']) }) gulp.task('test', function() { connect.server({ root: '', port: 4000 }); return gulp.src('./test/test.js').pipe(mocha()) .once('end', function () { process.exit(); }); }) gulp.task('default', ['connect', 'watch'])
Fix name of test object for enumerables
class TestEnumberable(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
class TestKernel(object): def test_inject(self, ec): w_res = ec.space.execute(ec, """ return (5..10).inject(1) do |prod, n| prod * n end """) assert ec.space.int_w(w_res) == 15120 w_res = ec.space.execute(ec, """ return (1..10).inject 0 do |sum, n| sum + n end """) assert ec.space.int_w(w_res) == 45 def test_each_with_index(self, ec): w_res = ec.space.execute(ec, """ result = [] (5..10).each_with_index do |n, idx| result << [n, idx] end return result """) assert [[ec.space.int_w(w_x) for w_x in ec.space.listview(w_sub)] for w_sub in ec.space.listview(w_res)] == [[5, 0], [6, 1], [7, 2], [8, 3], [9, 4]]
Print the cmd arguments to help message.
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; public class HelpCommand implements Command { private Application app; private CommandMap commands; public HelpCommand(Application app) { this.app = app; this.commands = app.getCommandMap(); } @Override public String getDescription() { return "Lists every command"; } @Override public String getName() { return "help"; } @Override public void run(String[] args) { System.out.println("Usage: tmc-cli [args] COMMAND [command-args]"); System.out.println(""); System.out.println("TMC commands:"); for (Command command : this.commands.getCommands().values()) { System.out.println(" " + command.getName() + "\t" + command.getDescription()); } System.out.println(""); app.printHelp(); } }
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; public class HelpCommand implements Command { private CommandMap commands; public HelpCommand(Application app) { this.commands = app.getCommandMap(); } @Override public String getDescription() { return "Lists every command"; } @Override public String getName() { return "help"; } @Override public void run(String[] args) { System.out.println("TMC commands:"); for (Command command : this.commands.getCommands().values()) { System.out.println(" " + command.getName() + "\t" + command.getDescription()); } } }
EPMRPP-38336: Replace fetched user filters when switching project
import { combineReducers } from 'redux'; import { fetchReducer } from 'controllers/fetch'; import { paginationReducer } from 'controllers/pagination'; import { loadingReducer } from 'controllers/loading'; import { NAMESPACE, FETCH_USER_FILTERS_SUCCESS, UPDATE_FILTER_CONDITIONS, ADD_FILTER, UPDATE_FILTER_SUCCESS, REMOVE_FILTER, } from './constants'; import { updateFilter } from './utils'; const updateFilterConditions = (filters, filterId, conditions) => { const filter = filters.find((item) => item.id === filterId); return updateFilter(filters, { ...filter, conditions }); }; export const launchesFiltersReducer = (state = [], { type, payload, meta: { oldId } = {} }) => { switch (type) { case FETCH_USER_FILTERS_SUCCESS: return payload; case UPDATE_FILTER_CONDITIONS: return updateFilterConditions(state, payload.filterId, payload.conditions); case UPDATE_FILTER_SUCCESS: return updateFilter(state, payload, oldId); case ADD_FILTER: return [...state, payload]; case REMOVE_FILTER: return state.filter((filter) => filter.id !== payload); default: return state; } }; export const filterReducer = combineReducers({ filters: fetchReducer(NAMESPACE, { contentPath: 'content' }), pagination: paginationReducer(NAMESPACE), loading: loadingReducer(NAMESPACE), launchesFilters: launchesFiltersReducer, });
import { combineReducers } from 'redux'; import { fetchReducer } from 'controllers/fetch'; import { paginationReducer } from 'controllers/pagination'; import { loadingReducer } from 'controllers/loading'; import { NAMESPACE, FETCH_USER_FILTERS_SUCCESS, UPDATE_FILTER_CONDITIONS, ADD_FILTER, UPDATE_FILTER_SUCCESS, REMOVE_FILTER, } from './constants'; import { updateFilter } from './utils'; const updateFilterConditions = (filters, filterId, conditions) => { const filter = filters.find((item) => item.id === filterId); return updateFilter(filters, { ...filter, conditions }); }; export const launchesFiltersReducer = (state = [], { type, payload, meta: { oldId } = {} }) => { switch (type) { case FETCH_USER_FILTERS_SUCCESS: return [...state, ...payload]; case UPDATE_FILTER_CONDITIONS: return updateFilterConditions(state, payload.filterId, payload.conditions); case UPDATE_FILTER_SUCCESS: return updateFilter(state, payload, oldId); case ADD_FILTER: return [...state, payload]; case REMOVE_FILTER: return state.filter((filter) => filter.id !== payload); default: return state; } }; export const filterReducer = combineReducers({ filters: fetchReducer(NAMESPACE, { contentPath: 'content' }), pagination: paginationReducer(NAMESPACE), loading: loadingReducer(NAMESPACE), launchesFilters: launchesFiltersReducer, });
Use Socket in the Client interface
package transport import ( "time" ) type Message struct { Header map[string]string Body []byte } type Socket interface { Recv(*Message) error Send(*Message) error Close() error } type Client interface { Socket } type Listener interface { Addr() string Close() error Accept(func(Socket)) error } // Transport is an interface which is used for communication between // services. It uses socket send/recv semantics and had various // implementations {HTTP, RabbitMQ, NATS, ...} type Transport interface { Dial(addr string, opts ...DialOption) (Client, error) Listen(addr string, opts ...ListenOption) (Listener, error) String() string } type Option func(*Options) type DialOption func(*DialOptions) type ListenOption func(*ListenOptions) var ( DefaultTransport Transport = newHTTPTransport() DefaultDialTimeout = time.Second * 5 ) func NewTransport(opts ...Option) Transport { return newHTTPTransport(opts...) } func Dial(addr string, opts ...DialOption) (Client, error) { return DefaultTransport.Dial(addr, opts...) } func Listen(addr string, opts ...ListenOption) (Listener, error) { return DefaultTransport.Listen(addr, opts...) } func String() string { return DefaultTransport.String() }
package transport import ( "time" ) type Message struct { Header map[string]string Body []byte } type Socket interface { Recv(*Message) error Send(*Message) error Close() error } type Client interface { Recv(*Message) error Send(*Message) error Close() error } type Listener interface { Addr() string Close() error Accept(func(Socket)) error } // Transport is an interface which is used for communication between // services. It uses socket send/recv semantics and had various // implementations {HTTP, RabbitMQ, NATS, ...} type Transport interface { Dial(addr string, opts ...DialOption) (Client, error) Listen(addr string, opts ...ListenOption) (Listener, error) String() string } type Option func(*Options) type DialOption func(*DialOptions) type ListenOption func(*ListenOptions) var ( DefaultTransport Transport = newHTTPTransport() DefaultDialTimeout = time.Second * 5 ) func NewTransport(opts ...Option) Transport { return newHTTPTransport(opts...) } func Dial(addr string, opts ...DialOption) (Client, error) { return DefaultTransport.Dial(addr, opts...) } func Listen(addr string, opts ...ListenOption) (Listener, error) { return DefaultTransport.Listen(addr, opts...) } func String() string { return DefaultTransport.String() }
Store fileReader in the module, not component instance
import React from 'react'; import { processLicense } from 'processor'; let fileReader; // TODO: import only what's needed from React and other packages export default class FileHandler extends React.Component { render() { return ( <input type="file" onChange={this.onChange} style={invisibleFileInputStyle} /> ); } componentDidMount() { fileReader = new FileReader(); fileReader.addEventListener('load', this.handleNewFile); } componentWillUnmount() { fileReader.removeEventListener('load', this.handleNewFile); } onChange = (event) => { if (event.target.files[0]) { fileReader.readAsText(event.target.files[0]) } } handleNewFile = (event) => { // TODO: make timeout a constant setTimeout((() => ( this.props.requestResults( processLicense(event.target.result) ) )), 200) } } const invisibleFileInputStyle = { opacity: 0, top: 0, bottom: 0, left: 0, right: 0, cursor: 'pointer', position: 'absolute', width: '100%' };
import React from 'react'; import { processLicense } from 'processor'; export default class FileHandler extends React.Component { render() { return ( <input type="file" onChange={this.onChange} style={invisibleFileInputStyle} /> ); } componentDidMount() { this.fileReader = new FileReader(); this.fileReader.addEventListener('load', this.handleNewFile); } componentWillUnmount() { this.fileReader.removeEventListener('load', this.handleNewFile); } onChange = (event) => { if (event.target.files[0]) { this.fileReader.readAsText(event.target.files[0]) } } handleNewFile = (event) => { // TODO: make timeout a constant setTimeout((() => ( this.props.requestResults( processLicense(event.target.result) ) )), 200) } } const invisibleFileInputStyle = { opacity: 0, top: 0, bottom: 0, left: 0, right: 0, cursor: 'pointer', position: 'absolute', width: '100%' };
Format the quotes of mode to single quotes
/* global __dirname */ module.exports = { entry: { 'index': `${__dirname}/index.jsx`, 'query': `${__dirname}/query.jsx`, 'plan': `${__dirname}/plan.jsx`, 'embedded_plan': `${__dirname}/embedded_plan.jsx`, 'stage': `${__dirname}/stage.jsx`, 'worker': `${__dirname}/worker.jsx`, }, mode: 'development', module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', '.jsx'] }, output: { path: __dirname + '/../dist', filename: '[name].js' } };
/* global __dirname */ module.exports = { entry: { 'index': `${__dirname}/index.jsx`, 'query': `${__dirname}/query.jsx`, 'plan': `${__dirname}/plan.jsx`, 'embedded_plan': `${__dirname}/embedded_plan.jsx`, 'stage': `${__dirname}/stage.jsx`, 'worker': `${__dirname}/worker.jsx`, }, mode: "development", module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', '.jsx'] }, output: { path: __dirname + '/../dist', filename: '[name].js' } };
Disable this test which doesn't work probably for environmental reasons
package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } // Doesn't work on Travis, does work locally. @Test @Ignore public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } }
package org.sagebionetworks.bridge.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.sagebionetworks.bridge.sdk.Config; public class ConfigTest { @Test public void createConfig() { Config conf = new Config(); assertNotNull(conf); assertEquals("conf returns values", "/researchers/v1/surveys/asdf/published", conf.getSurveyMostRecentlyPublishedVersionApi("asdf")); } @Test(expected=IllegalArgumentException.class) public void configChecksArguments() { Config conf = new Config(); conf.getSurveyMostRecentlyPublishedVersionApi(null); } @Test public void configPicksUpSystemProperty() { System.setProperty("ENV", "staging"); Config conf = new Config(); assertTrue(Environment.STAGING == conf.getEnvironment()); } }
Reset navigation using key prop to tell when route changes Closes #149
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { fetchNavigation, setNavigationVisibility } from './reducer'; import { itemById } from '../../utils/helpers'; import Navigation from './Navigation'; const mapDispatchToProps = (dispatch) => { return { fetchNavigation: bindActionCreators(fetchNavigation, dispatch), push: (path) => dispatch(push(path)), setNavigationVisibility: bindActionCreators(setNavigationVisibility, dispatch) }; }; const mapStateToProps = (state, ownProps) => { const { items } = state.navigation; const { selectedTOS, classification } = state; const tos = selectedTOS.classification ? itemById(items, selectedTOS.classification) : classification.id ? itemById(items, classification.id) : null; const tosPath = ownProps.tosPath ? ownProps.tosPath : tos ? tos.path : []; return { tosPath, is_open: state.navigation.is_open, isFetching: state.navigation.isFetching, items: JSON.parse(JSON.stringify(items)), // TODO: Unhack this when Navigation doesn't mutate state selectedTOS, key: state.routing.locationBeforeTransitions.key }; }; export default connect(mapStateToProps, mapDispatchToProps)(Navigation);
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; import { fetchNavigation, setNavigationVisibility } from './reducer'; import { itemById } from '../../utils/helpers'; import Navigation from './Navigation'; const mapDispatchToProps = (dispatch) => { return { fetchNavigation: bindActionCreators(fetchNavigation, dispatch), push: (path) => dispatch(push(path)), setNavigationVisibility: bindActionCreators(setNavigationVisibility, dispatch) }; }; const mapStateToProps = (state, ownProps) => { const { items } = state.navigation; const { selectedTOS, classification } = state; const tos = selectedTOS.classification ? itemById(items, selectedTOS.classification) : classification.id ? itemById(items, classification.id) : null; const tosPath = ownProps.tosPath ? ownProps.tosPath : tos ? tos.path : []; return { tosPath, is_open: state.navigation.is_open, isFetching: state.navigation.isFetching, items: JSON.parse(JSON.stringify(items)), // TODO: Unhack this when Navigation doesn't mutate state selectedTOS }; }; export default connect(mapStateToProps, mapDispatchToProps)(Navigation);
Change the way to determine path to config file
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps def with_app(func): @arg('--config', help='Path to config file') @wraps(func) def wrapper(*args, **kwargs): config = args[0].config from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
#!/usr/bin/env python import os from argh import arg, ArghParser from functools import wraps CONFIG = os.environ.get('ALFRED_LISTENER_CONFIG') def with_app(func, args): if CONFIG is None: raise RuntimeError('ALFRED_LISTENER_CONFIG env variable is not set.') @wraps(func) def wrapper(*args, **kwargs): from alfred_listener import create_app app = create_app(config) return func(app, *args, **kwargs) return wrapper @arg('--host', default='127.0.0.1', help='the host') @arg('--port', default=5000, help='the port') @with_app def runserver(app, args): app.run(args.host, args.port) @with_app def shell(app, args): from alfred_listener.helpers import get_shell with app.test_request_context(): sh = get_shell() sh(app=app) def main(): parser = ArghParser() parser.add_commands([runserver, shell]) parser.dispatch() if __name__ == '__main__': main()
Update the schedules times and days
import json from buffer.response import ResponseObject PATHS = { 'GET_PROFILES': 'profiles.json', 'GET_PROFILE': 'profiles/%s.json', 'GET_SCHEDULES': 'profiles/%s/schedules.json', 'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json' } class Profile(ResponseObject): def __init__(self, api, raw_response): super(Profile, self).__init__(raw_response) self.api = api def __getattr__(self, name): if callable(name): name() if hasattr(self, name): return getattr(self, name) if hasattr(self, "_get_%s" % name): return getattr(self, "_get_%s" % name)() def _post_schedules(self, schedules): url = PATHS['UPDATE_SCHEDULES'] % self.id data_format = "schedules[0][%s][]=%s&" post_data = "" for format_type, values in schedules.iteritems(): for value in values: post_data += data_format % (format_type, value) self.api.post(url=url, parser=json.loads, data=post_data) def _get_schedules(self): url = PATHS['GET_SCHEDULES'] % self.id self.schedules = self.api.get(url=url, parser=json.loads) return self.schedules
import json from buffer.response import ResponseObject PATHS = { 'GET_PROFILES': 'profiles.json', 'GET_PROFILE': 'profiles/%s.json', 'GET_SCHEDULES': 'profiles/%s/schedules.json', 'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json' } class Profile(ResponseObject): def __init__(self, api, raw_response): super(Profile, self).__init__(raw_response) self.api = api def __getattr__(self, name): if callable(name): name() if hasattr(self, name): return getattr(self, name) if hasattr(self, "_get_%s" % name): return getattr(self, "_get_%s" % name)() def _get_schedules(self): url = PATHS['GET_SCHEDULES'] % self.id self.schedules = self.api.get(url=url, parser=json.loads) return self.schedules
Fix undefined var in wield script
exports.listeners = { wield: function (l10n) { return function (location, player, players) { location = location || 'wield'; player.sayL10n(l10n, 'WIELD', this.getShortDesc(player.getLocale())); player.equip(location, this); } }, remove: function (l10n) { return function (player) { player.sayL10n(l10n, 'REMOVE', this.getShortDesc(player.getLocale())); } }, hit: function (l10n) { return function (player) { player.sayL10n(l10n, 'HIT', this.getShortDesc(player.getLocale())); } }, miss: function (l10n) { return function (player) { player.sayL10n(l10n, 'MISS'); } }, parry: function (l10n) { return function (player) { player.sayL10n(l10n, 'PARRY'); } }, };
exports.listeners = { wield: function (l10n) { return function (location, player, players) { location = location || body; player.sayL10n(l10n, 'WIELD', this.getShortDesc(player.getLocale())); player.equip(location, this); } }, remove: function (l10n) { return function (player) { player.sayL10n(l10n, 'REMOVE', this.getShortDesc(player.getLocale())); } }, hit: function (l10n) { return function (player) { player.sayL10n(l10n, 'HIT', this.getShortDesc(player.getLocale())); } }, miss: function (l10n) { return function (player) { player.sayL10n(l10n, 'MISS'); } }, parry: function (l10n) { return function (player) { player.sayL10n(l10n, 'PARRY'); } }, };
Fix cmd arguments parsing for server
package main import ( "flag" "github.com/itsankoff/gotcha/server" "log" ) func main() { config := server.NewConfig() flag.StringVar(&config.ListenHost, "host", "0.0.0.0:9000", "host to listen") flag.StringVar(&config.FileServerHost, "file_host", "http://0.0.0.0:9000", "host to server files") flag.StringVar(&config.FileServerPath, "file_path", "/", "query path to access files") flag.StringVar(&config.FileServerFolder, "file_folder", "./", "storage folder") flag.StringVar(&config.SSLKeyPath, "key_path", "", "path to ssl key") flag.StringVar(&config.SSLCertPath, "cert_path", "", "path to ssl cert") flag.Parse() srv := server.New(config) wss := server.NewWebSocket(config) srv.AddTransport("127.0.0.1:9000", &wss) done := make(chan interface{}) err := srv.Start(done) if err != nil { log.Fatal("Failed to start server") } }
package main import ( "flag" "github.com/itsankoff/gotcha/server" "log" ) func main() { config := server.NewConfig() flag.StringVar(&config.ListenHost, "host", "0.0.0.0:9000", "host to listen") flag.StringVar(&config.FileServerHost, "file_host", "http://0.0.0.0:9000", "host to server files") flag.StringVar(&config.FileServerPath, "file_path", "/", "query path to access files") flag.StringVar(&config.FileServerFolder, "file_folder", "./", "storage folder") flag.StringVar(&config.SSLKeyPath, "key_path", "", "path to ssl key") flag.StringVar(&config.SSLCertPath, "cert_path", "", "path to ssl cert") flag.Parse() args := flag.Args() if len(args) > 0 && args[0] == "--help" { flag.PrintDefaults() return } srv := server.New(config) wss := server.NewWebSocket(config) srv.AddTransport("127.0.0.1:9000", &wss) done := make(chan interface{}) err := srv.Start(done) if err != nil { log.Fatal("Failed to start server") } }
Test tile now gets it's texture from the tile type array.
require("pixi.js"); import TileType from "./TileType"; // Constants const ASSET_URL = "assets"; var tileTypes; /** * Load game tile types... */ function loadTileTypes() { console.log("Loading tile types..."); var tileTypeConfig = require("../assets/tiles/tiles.json"); var tileTypes = {}; for (var tileTypeId in tileTypeConfig) { if (!tileTypeConfig.hasOwnProperty(tileTypeId)) { continue; } var tileTypeDef = tileTypeConfig[tileTypeId]; var id = parseInt(tileTypeId); tileTypes[id] = new TileType(id, tileTypeDef.texture, tileTypeDef.encounter); } console.log("Loaded " + Object.keys(tileTypes).length + " tiles!"); return tileTypes; } tileTypes = loadTileTypes(); // Init rendering var stage = new PIXI.Container(); var renderer = PIXI.autoDetectRenderer(800, 600); document.body.appendChild(renderer.view); requestAnimationFrame(animate); // Add a test tile for testing. var testTileTexture = PIXI.Texture.fromImage(ASSET_URL + "/tiles/" + tileTypes[1].texture); var testTile = new PIXI.Sprite(testTileTexture); stage.addChild(testTile); function animate() { requestAnimationFrame(animate); renderer.render(stage); }
require("pixi.js"); import TileType from "./TileType"; var tileTypes; /** * Load game tile types... */ function loadTileTypes() { console.log("Loading tile types..."); var tileTypeConfig = require("../assets/tiles/tiles.json"); var tileTypes = {}; for (var tileTypeId in tileTypeConfig) { if (!tileTypeConfig.hasOwnProperty(tileTypeId)) { continue; } var tileTypeDef = tileTypeConfig[tileTypeId]; var id = parseInt(tileTypeId); tileTypes[id] = new TileType(id, tileTypeDef.texture, tileTypeDef.encounter); } console.log("Loaded " + Object.keys(tileTypes).length + " tiles!"); return tileTypes; } tileTypes = loadTileTypes(); // Init rendering var stage = new PIXI.Container(); var renderer = PIXI.autoDetectRenderer(800, 600); document.body.appendChild(renderer.view); requestAnimationFrame(animate); // Add a test tile for testing. var testTileTexture = PIXI.Texture.fromImage("assets/tiles/white01.png"); var testTile = new PIXI.Sprite(testTileTexture); stage.addChild(testTile); function animate() { requestAnimationFrame(animate); renderer.render(stage); }
Fix ignoring mock artifacts on release
#!/usr/bin/env node // This script removes the build artifacts of ignored contracts. const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const match = require('micromatch'); function readJSON (path) { return JSON.parse(fs.readFileSync(path)); } cp.spawnSync('npm', ['run', 'compile'], { stdio: 'inherit' }); const pkgFiles = readJSON('package.json').files; // Get only negated patterns. const ignorePatterns = pkgFiles .filter(pat => pat.startsWith('!')) // Remove the negation part and initial slash. Makes micromatch usage more intuitive. .map(pat => pat.slice(1).replace(/^\//, '')); const ignorePatternsSubtrees = ignorePatterns // Add **/* to ignore all files contained in the directories. .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))); const artifactsDir = 'build/contracts'; let n = 0; for (const artifact of fs.readdirSync(artifactsDir)) { const fullArtifactPath = path.join(artifactsDir, artifact); const { sourcePath: fullSourcePath } = readJSON(fullArtifactPath); const sourcePath = path.relative('.', fullSourcePath); const ignore = match.any(sourcePath, ignorePatternsSubtrees); if (ignore) { fs.unlinkSync(fullArtifactPath); n += 1; } } console.error(`Removed ${n} mock artifacts`);
#!/usr/bin/env node // This script removes the build artifacts of ignored contracts. const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const match = require('micromatch'); function readJSON (path) { return JSON.parse(fs.readFileSync(path)); } cp.spawnSync('npm', ['run', 'compile'], { stdio: 'inherit' }); const pkgFiles = readJSON('package.json').files; // Get only negated patterns. const ignorePatterns = pkgFiles .filter(pat => pat.startsWith('!')) // Remove the negation part. Makes micromatch usage more intuitive. .map(pat => pat.slice(1)); const ignorePatternsSubtrees = ignorePatterns // Add **/* to ignore all files contained in the directories. .concat(ignorePatterns.map(pat => path.join(pat, '**/*'))); const artifactsDir = 'build/contracts'; let n = 0; for (const artifact of fs.readdirSync(artifactsDir)) { const fullArtifactPath = path.join(artifactsDir, artifact); const { sourcePath: fullSourcePath } = readJSON(fullArtifactPath); const sourcePath = path.relative('.', fullSourcePath); const ignore = match.any(sourcePath, ignorePatternsSubtrees); if (ignore) { fs.unlinkSync(fullArtifactPath); n += 1; } } console.error(`Removed ${n} mock artifacts`);
Update URL patterns for staticfiles.
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.simple import direct_to_template # Enable the django admin admin.autodiscover() urlpatterns = patterns('', # Wire up olcc urls url(r'', include('olcc.urls')), # Wire up the admin urls url(r'^admin/', include(admin.site.urls)), # humans.txt (r'^humans\.txt$', direct_to_template, {'template': 'humans.txt', 'mimetype': 'text/plain'}), # robots.txt (r'^robots\.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # crossdomain.xml (r'^crossdomain\.xml$', direct_to_template, {'template': 'crossdomain.xml', 'mimetype': 'application/xml'}), ) # Static files if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() else: urlpatterns += patterns('', (r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), )
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.simple import direct_to_template # Enable the django admin admin.autodiscover() urlpatterns = patterns('', # Wire up olcc urls url(r'', include('olcc.urls')), # Wire up the admin urls url(r'^admin/', include(admin.site.urls)), # humans.txt (r'^humans\.txt$', direct_to_template, {'template': 'humans.txt', 'mimetype': 'text/plain'}), # robots.txt (r'^robots\.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}), # crossdomain.xml (r'^crossdomain\.xml$', direct_to_template, {'template': 'crossdomain.xml', 'mimetype': 'application/xml'}), ) # Static files urlpatterns += staticfiles_urlpatterns()
Add default contact parameter in move method.
<?php namespace LaravelLb; class LogicBoxesProduct extends LogicBoxes { public $resource; public function __construct() { parent::__construct(); $this->resource = "products"; } public function getPlanDetails() { $method = "plan-details"; $response = $this->get($this->resource, $method); return $this; } /** * Move domain to another customer * Ref: https://manage.netearthone.com/kb/answer/904 * * @param $domainName * @param $customerIdFrom * @param $customerIdTo * @return LogicBoxes */ public function move($domainName, $customerIdFrom, $customerIdTo, $defaultContact = 'oldcontact') { $variables = [ 'domain-name' => $domainName, 'existing-customer-id' => $customerIdFrom, 'new-customer-id' => $customerIdTo, 'default-contact' => $defaultContact, ]; $method = 'move'; return $this->post($this->resource, $method, $variables); } }
<?php namespace LaravelLb; class LogicBoxesProduct extends LogicBoxes { public $resource; public function __construct() { parent::__construct(); $this->resource = "products"; } public function getPlanDetails() { $method = "plan-details"; $response = $this->get($this->resource, $method); return $this; } /** * Move domain to another customer * Ref: https://manage.netearthone.com/kb/answer/904 * * @param $domainName * @param $customerIdFrom * @param $customerIdTo * @return LogicBoxes */ public function move($domainName, $customerIdFrom, $customerIdTo) { $variables = [ 'domain-name' => $domainName, 'existing-customer-id' => $customerIdFrom, 'new-customer-id' => $customerIdTo, ]; $method = 'move'; return $this->post($this->resource, $method, $variables); } }
Fix "Luminary" migration for SQLite [WEB-1834]
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RenameSustainingFellowsColumnsToLuminary extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('sustaining_fellow_copy', 'luminary_copy'); }); Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('send_sustaining_fellow_test', 'send_luminary_test'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('luminary_copy', 'sustaining_fellow_copy'); }); Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('send_luminary_test', 'send_sustaining_fellow_test'); }); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RenameSustainingFellowsColumnsToLuminary extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('sustaining_fellow_copy', 'luminary_copy'); $table->renameColumn('send_sustaining_fellow_test', 'send_luminary_test'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('event_email_series', function (Blueprint $table) { $table->renameColumn('luminary_copy', 'sustaining_fellow_copy'); $table->renameColumn('send_luminary_test', 'send_sustaining_fellow_test'); }); } }
Tag error, rolling to 0.7.2
"""setup.py file.""" import uuid from setuptools import setup from pip.req import parse_requirements install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in install_reqs] setup( name="napalm-ansible", version='0.7.2', packages=["napalm_ansible"], author="David Barroso, Kirk Byers, Mircea Ulinic", author_email="dbarrosop@dravetech.com, ktbyers@twb-tech.com", description="Network Automation and Programmability Abstraction Layer with Multivendor support", classifiers=[ 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS', ], url="https://github.com/napalm-automation/napalm-base", include_package_data=True, install_requires=reqs, entry_points={ 'console_scripts': [ 'napalm-ansible=napalm_ansible:main', ], } )
"""setup.py file.""" import uuid from setuptools import setup from pip.req import parse_requirements install_reqs = parse_requirements('requirements.txt', session=uuid.uuid1()) reqs = [str(ir.req) for ir in install_reqs] setup( name="napalm-ansible", version='0.7.1', packages=["napalm_ansible"], author="David Barroso, Kirk Byers, Mircea Ulinic", author_email="dbarrosop@dravetech.com, ktbyers@twb-tech.com", description="Network Automation and Programmability Abstraction Layer with Multivendor support", classifiers=[ 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS', ], url="https://github.com/napalm-automation/napalm-base", include_package_data=True, install_requires=reqs, entry_points={ 'console_scripts': [ 'napalm-ansible=napalm_ansible:main', ], } )
Fix ImportError: No module named requests setup.py imports camplight which ends up importing requests via camplight.api. It does the import before running setup so you cannot install the package unless you already have requests installed.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages setup(name='camplight', version='0.3', author='Mathias Lafeldt', author_email='mathias.lafeldt@gmail.com', url='https://github.com/mlafeldt/camplight', license='MIT', description='Python implementation of the Campfire API', long_description=open('README.md').read() + '\n\n' + open('HISTORY.md').read(), classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python'], packages=find_packages(), zip_safe=False, setup_requires=[], install_requires=['requests>=0.12.1'], entry_points=""" # -*- Entry points: -*- [console_scripts] camplight=camplight.cli:main """, test_suite='test')
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import camplight setup(name='camplight', version=camplight.__version__, author='Mathias Lafeldt', author_email='mathias.lafeldt@gmail.com', url='https://github.com/mlafeldt/camplight', license='MIT', description='Python implementation of the Campfire API', long_description=open('README.md').read() + '\n\n' + open('HISTORY.md').read(), classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python'], packages=find_packages(), zip_safe=False, setup_requires=[], install_requires=['requests>=0.12.1'], entry_points=""" # -*- Entry points: -*- [console_scripts] camplight=camplight.cli:main """, test_suite='test')
Fix for textbox view bridge causing recursion
var bridge = function (presenterPath) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.apply(this, arguments); }; bridge.prototype = new window.rhubarb.viewBridgeClasses.HtmlViewBridge(); bridge.prototype.constructor = bridge; bridge.spawn = function (spawnData, index, parentPresenterPath) { var textBox = document.createElement("INPUT"); textBox.setAttribute("type", spawnData.type); textBox.setAttribute("size", spawnData.size); if (spawnData.maxLength) { textBox.setAttribute("maxlength", spawnData.maxLength); } window.rhubarb.viewBridgeClasses.HtmlViewBridge.applyStandardAttributesToSpawnedElement(textBox, spawnData, index, parentPresenterPath); return textBox; }; bridge.prototype.keyPressed = function(event){ if (this.onKeyPress){ this.onKeyPress(event); } }; bridge.prototype.attachDomChangeEventHandler = function (triggerChangeEvent) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.prototype.attachDomChangeEventHandler.apply(this,arguments); var self = this; if (!this.viewNode.addEventListener) { this.viewNode.attachEvent("onkeypress", self.keyPressed.bind(self)); } else { // Be interested in a changed event if there is one. this.viewNode.addEventListener('keypress', self.keyPressed.bind(self), false); } }; window.rhubarb.viewBridgeClasses.TextBoxViewBridge = bridge;
var bridge = function (presenterPath) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.apply(this, arguments); }; bridge.prototype = new window.rhubarb.viewBridgeClasses.HtmlViewBridge(); bridge.prototype.constructor = bridge; bridge.spawn = function (spawnData, index, parentPresenterPath) { var textBox = document.createElement("INPUT"); textBox.setAttribute("type", spawnData.type); textBox.setAttribute("size", spawnData.size); if (spawnData.maxLength) { textBox.setAttribute("maxlength", spawnData.maxLength); } window.rhubarb.viewBridgeClasses.HtmlViewBridge.applyStandardAttributesToSpawnedElement(textBox, spawnData, index, parentPresenterPath); return textBox; }; bridge.prototype.onKeyPress = function(event){ if (this.onKeyPress){ this.onKeyPress(event); } }; bridge.prototype.attachDomChangeEventHandler = function (triggerChangeEvent) { window.rhubarb.viewBridgeClasses.HtmlViewBridge.prototype.attachDomChangeEventHandler.apply(this,arguments); var self = this; if (!this.viewNode.addEventListener) { this.viewNode.attachEvent("onkeypress", self.onKeyPress.bind(self)); } else { // Be interested in a changed event if there is one. this.viewNode.addEventListener('keypress', self.onKeyPress.bind(self), false); } }; window.rhubarb.viewBridgeClasses.TextBoxViewBridge = bridge;
Correct for capture in getValidMoves from store
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var to_from = this.valid_moves[move].Move.substr(1).replace('x','-').split('-'); if (to_from[0] === pos) { valid.push(to_from[1]); } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
import Reflux from 'reflux'; import GameActions from '../actions/GameActions'; var GameStore = Reflux.createStore({ init() { getGameFEN() { return this.fen; }, getActivePlayer() { return this.fen.split(' ')[1] === 'w' ? "White" : "Black"; }, getAllValidMoves() { return this.valid_moves; }, getValidMoves(pos) { var valid = []; for (var move in this.valid_moves) { var movement = this.valid_moves[move].Move.substr(1).split('-'); if (movement[0] === pos) { valid.push(movement[1]); } } return valid; }, getGameHistory() { return this.history; } }); export default GameStore;
Add new url to get request
document.addEventListener("DOMContentLoaded", function (event) { // redirect to 7777 port // ping golang counter httpGetAsync("http://www.aracki.me:7777/count", function (res) { alert(res); }) }); function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4 && xmlHttp.status === 200) callback(xmlHttp.responseText); }; xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*'); xmlHttp.setRequestHeader("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS'); xmlHttp.setRequestHeader("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token'); xmlHttp.send("ivan"); }
document.addEventListener("DOMContentLoaded", function (event) { // redirect to 7777 port // ping golang counter httpGetAsync("http://www.aracki.me:7777", function (res) { alert(res); }) }); function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4 && xmlHttp.status === 200) callback(xmlHttp.responseText); }; xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.setRequestHeader("Access-Control-Allow-Origin", '*'); xmlHttp.setRequestHeader("Access-Control-Allow-Methods", 'GET, POST, PATCH, PUT, DELETE, OPTIONS'); xmlHttp.setRequestHeader("Access-Control-Allow-Headers", 'Origin, Content-Type, X-Auth-Token'); xmlHttp.send("ivan"); }
Allow passing None for function, and use the executable name in that case. Save error list anonymously
#!/usr/bin/env python # -*- coding: utf-8 -*- # This software is under a BSD license. See LICENSE.txt for details. __all__ = ["DTErrorMessage", "DTSaveError"] import sys import os _errors = [] def DTErrorMessage(fcn, msg): """Accumulate a message and echo to standard error. Arguments: fcn -- typically a function or module name msg -- an error or warning message Returns: Nothing Typically you call this each time an error or warning should be presented, then call DTSaveError before exiting. """ if fcn == None: fcn = os.path.basename(sys.argv[0]) err_msg = "%s: %s" % (fcn, msg) _errors.append(err_msg) sys.stderr.write(err_msg + "\n") def DTSaveError(datafile, name="ExecutionErrors"): """Save accumulated messages to a file. Arguments: datafile -- an open DTDataFile instance name -- defaults to "ExecutionErrors" for DataTank Returns: Nothing This will be displayed in DataTank's Messages panel. """ if len(_errors): datafile.write_anonymous(_errors, name)
#!/usr/bin/env python # -*- coding: utf-8 -*- # This software is under a BSD license. See LICENSE.txt for details. __all__ = ["DTErrorMessage", "DTSaveError"] import sys _errors = [] def DTErrorMessage(fcn, msg): """Accumulate a message and echo to standard error. Arguments: fcn -- typically a function or module name msg -- an error or warning message Returns: Nothing Typically you call this each time an error or warning should be presented, then call DTSaveError before exiting. """ err_msg = "%s: %s" % (fcn, msg) _errors.append(err_msg) sys.stderr.write(err_msg + "\n") def DTSaveError(datafile, name="ExecutionErrors"): """Save accumulated messages to a file. Arguments: datafile -- an open DTDataFile instance name -- defaults to "ExecutionErrors" for DataTank Returns: Nothing This will be displayed in DataTank's Messages panel. """ if len(_errors): datafile[name] = _errors
Change variable name 'buffer' -> 'buffer_' to avoid conflict with python keyword
from abc import ABCMeta, abstractmethod class Searcher(object): __metaclass__ = ABCMeta class IndexSearcher(Searcher): pass class DataBaseSearcher(Searcher): pass class BacktrackSearcher(Searcher): def __init__(self, file_path): self._file_path = file_path def _reverse_from_offset(self, offset, buf_size=8192): """ a generator that returns the lines of a file in reverse order beginning with the specified offset """ with open(self._file_path) as fh: fh.seek(offset) total_size = remaining_size = fh.tell() reverse_offset = 0 truncated = None while remaining_size > 0: reverse_offset = min(total_size, reverse_offset + buf_size) fh.seek(total_size-reverse_offset, 0) buffer_ = fh.read(min(remaining_size, buf_size)) lines = buffer_.split('\n') remaining_size -= buf_size if truncated is not None: if buffer_[-1] is not '\n': lines[-1] += truncated else: yield truncated truncated = lines[0] for index in xrange(len(lines) - 1, 0, -1): if len(lines[index]): yield lines[index] yield truncated
from abc import ABCMeta, abstractmethod class Searcher(object): __metaclass__ = ABCMeta class IndexSearcher(Searcher): pass class DataBaseSearcher(Searcher): pass class BacktrackSearcher(Searcher): def __init__(self, file_path): self._file_path = file_path def _reverse_from_offset(self, offset, buf_size=8192): """ a generator that returns the lines of a file in reverse order beginning with the specified offset """ with open(self._file_path) as fh: fh.seek(offset) total_size = remaining_size = fh.tell() reverse_offset = 0 truncated = None while remaining_size > 0: reverse_offset = min(total_size, reverse_offset + buf_size) fh.seek(total_size-reverse_offset, 0) buffer = fh.read(min(remaining_size, buf_size)) lines = buffer.split('\n') remaining_size -= buf_size if truncated is not None: if buffer[-1] is not '\n': lines[-1] += truncated else: yield truncated truncated = lines[0] for index in xrange(len(lines) - 1, 0, -1): if len(lines[index]): yield lines[index] yield truncated
Check if there's a narrative before displaying a Read More link.
<?php $title = __('Neatline | Browse Exhibits'); echo head(array( 'title' => $title, 'content_class' => 'neatline' )); ?> <div id="primary"> <?php echo flash(); ?> <h1><?php echo $title; ?></h1> <?php if (nl_exhibitsHaveBeenCreated()): ?> <div class="pagination"><?php echo pagination_links(); ?></div> <?php foreach (loop('NeatlineExhibit') as $e): ?> <h2> <?php echo nl_getExhibitLink( $e, 'show', nl_getExhibitField('title'), array('class' => 'neatline'), true );?> </h2> <?php if ($description = snippet_by_word_count(nl_getExhibitField('narrative'), 20)) : ?> <div class="neatline-exhibit-description"><?php echo $description . nl_getExhibitLink($e, 'show', 'Read more.', array('class' => 'neatline'), true); ?></div> <?php endif; ?> <?php endforeach; ?> <div class="pagination"><?php echo pagination_links(); ?></div> <?php endif; ?> </div> <?php echo foot(); ?>
<?php $title = __('Neatline | Browse Exhibits'); echo head(array( 'title' => $title, 'content_class' => 'neatline' )); ?> <div id="primary"> <?php echo flash(); ?> <h1><?php echo $title; ?></h1> <?php if (nl_exhibitsHaveBeenCreated()): ?> <div class="pagination"><?php echo pagination_links(); ?></div> <?php foreach (loop('NeatlineExhibit') as $e): ?> <h2> <?php echo nl_getExhibitLink( $e, 'show', nl_getExhibitField('title'), array('class' => 'neatline'), true );?> </h2> <div class="neatline-exhibit-description"><?php echo snippet_by_word_count(nl_getExhibitField('narrative'), 20); ?>.<?php echo nl_getExhibitLink( $e, 'show', 'Read more.', array('class' => 'neatline'), true );?> </div> <?php endforeach; ?> <div class="pagination"><?php echo pagination_links(); ?></div> <?php endif; ?> </div> <?php echo foot(); ?>
Remove gzip stuff for now.
#!/usr/bin/env node var chalk = require('chalk'), path = require('path'), fs = require('fs-extra'), browserify = require('browserify'); var EXAMPLES_DIR = 'examples', BUILD_DIR = 'build'; console.log(chalk.green('Bundling examples...')); fs.emptydirSync(BUILD_DIR); fs.copySync(EXAMPLES_DIR, BUILD_DIR); fs.readdirSync(BUILD_DIR) .map((dir) => path.join(BUILD_DIR, dir, 'index.js')) .filter((path) => { try { return fs.statSync(path).isFile(); } catch (err) { return false; } }) .map((file) => { var dir = path.dirname(file); console.log(chalk.yellow(' ⇢ %s/bundle.js'), dir); var bundle = browserify() .add(file) .bundle(); bundle .pipe(fs.createWriteStream(path.join(dir, 'bundle.js'))); }); process.on('exit', () => console.log(chalk.black.bgGreen(' Success! 🍻 ')));
#!/usr/bin/env node var chalk = require('chalk'), path = require('path'), fs = require('fs-extra'), // zlib = require('zlib'), browserify = require('browserify'); var EXAMPLES_DIR = 'examples', BUILD_DIR = 'build'; // var gzip = zlib.createGzip(); console.log(chalk.green('Bundling examples...')); fs.emptydirSync(BUILD_DIR); fs.copySync(EXAMPLES_DIR, BUILD_DIR); fs.readdirSync(BUILD_DIR) .map((dir) => path.join(BUILD_DIR, dir, 'index.js')) .filter((path) => { try { return fs.statSync(path).isFile(); } catch (err) { return false; } }) .map((file) => { var dir = path.dirname(file); console.log(chalk.yellow(' ⇢ %s/bundle.js'), dir); var bundle = browserify() .add(file) .bundle(); bundle .pipe(fs.createWriteStream(path.join(dir, 'bundle.js'))); // bundle // .pipe(gzip) // .pipe(fs.createWriteStream(path.join(dir, 'bundle.js.gz'))); }); process.on('exit', () => console.log(chalk.black.bgGreen(' Success! 🍻 ')));
Fix to publisher matching logic
package core import ( "github.com/projectjane/jane/connectors" "github.com/projectjane/jane/models" "github.com/projectjane/jane/parse" "log" "strings" ) func Publishers(publishMsgs <-chan models.Message, config *models.Config) { log.Print("Initializing Publishers") for { message := <-publishMsgs for _, route := range message.Routes { if match, _ := parse.Match(route.Match, message.Out.Text+" "+message.Out.Detail); match || route.Match == "*" { for _, connector := range config.Connectors { if connector.Active { if sendToConnector(connector.ID, route.Connectors) { if connector.Debug { log.Print("Broadcasting to " + connector.ID + " (type:" + connector.Type + ") for route " + route.Connectors) log.Printf("Message: %+v", message) log.Print("") } c := connectors.MakeConnector(connector.Type).(connectors.Connector) c.Publish(connector, message, route.Target) } } } } } } } func sendToConnector(connId string, connectors string) (send bool) { send = false if connectors == "*" { send = true } r := strings.Split(connectors, ",") for _, v := range r { if v == connId { send = true } } return send }
package core import ( "github.com/projectjane/jane/connectors" "github.com/projectjane/jane/models" "log" "strings" ) func Publishers(publishMsgs <-chan models.Message, config *models.Config) { log.Print("Initializing Publishers") for { message := <-publishMsgs for _, route := range message.Routes { if strings.Contains(message.Out.Text, route.Match) || route.Match == "*" { for _, connector := range config.Connectors { if connector.Active { if sendToConnector(connector.ID, route.Connectors) { if connector.Debug { log.Print("Broadcasting to " + connector.ID + " (type:" + connector.Type + ") for route " + route.Connectors) log.Printf("Message: %+v", message) log.Print("") } c := connectors.MakeConnector(connector.Type).(connectors.Connector) c.Publish(connector, message, route.Target) } } } } } } } func sendToConnector(connId string, connectors string) (send bool) { send = false if connectors == "*" { send = true } r := strings.Split(connectors, ",") for _, v := range r { if v == connId { send = true } } return send }
Change the session lifetime duration
<?php namespace PicoFarad\Session; const SESSION_LIFETIME = 0; function open($base_path = '/', $save_path = '') { if ($save_path !== '') session_save_path($save_path); // HttpOnly and secure flags for session cookie session_set_cookie_params( SESSION_LIFETIME, $base_path ?: '/', null, isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', true ); // Avoid session id in the URL ini_set('session.use_only_cookies', true); // Ensure session ID integrity ini_set('session.entropy_file', '/dev/urandom'); ini_set('session.entropy_length', '32'); ini_set('session.hash_bits_per_character', 6); // Custom session name session_name('__$'); session_start(); // Regenerate the session id to avoid session fixation issue if (empty($_SESSION['__validated'])) { session_regenerate_id(true); $_SESSION['__validated'] = 1; } } function close() { session_destroy(); } function flash($message) { $_SESSION['flash_message'] = $message; } function flash_error($message) { $_SESSION['flash_error_message'] = $message; }
<?php namespace PicoFarad\Session; const SESSION_LIFETIME = 2678400; function open($base_path = '/', $save_path = '') { if ($save_path !== '') session_save_path($save_path); // HttpOnly and secure flags for session cookie session_set_cookie_params( SESSION_LIFETIME, $base_path ?: '/', null, isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', true ); // Avoid session id in the URL ini_set('session.use_only_cookies', true); // Ensure session ID integrity ini_set('session.entropy_file', '/dev/urandom'); ini_set('session.entropy_length', '32'); ini_set('session.hash_bits_per_character', 6); // Custom session name session_name('__$'); session_start(); // Regenerate the session id to avoid session fixation issue if (empty($_SESSION['__validated'])) { session_regenerate_id(true); $_SESSION['__validated'] = 1; } } function close() { session_destroy(); } function flash($message) { $_SESSION['flash_message'] = $message; } function flash_error($message) { $_SESSION['flash_error_message'] = $message; }
Fix path to navigation component
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import { rhythm } from '../utils/typography'; import Navigation from '../components/Navigation/navigation'; import Footer from '../components/footer/footer'; import '../css/main.css'; export default class Template extends React.Component { static propTypes = { children: PropTypes.func }; render() { return ( <main> <Helmet title="Quality Link Consulting" meta={[{ name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }]} /> <Navigation /> <div>{this.props.children()}</div> <Footer /> </main> ); } }
import React from 'react'; import PropTypes from 'prop-types'; import Link from 'gatsby-link'; import Helmet from 'react-helmet'; import { rhythm } from '../utils/typography'; import Navigation from '../components/navigation/navigation'; import Footer from '../components/footer/footer'; import '../css/main.css'; export default class Template extends React.Component { static propTypes = { children: PropTypes.func }; render() { return ( <main> <Helmet title="Quality Link Consulting" meta={[{ name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }]} /> <Navigation /> <div>{this.props.children()}</div> <Footer /> </main> ); } }
Remove obsolete imports, add logging
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(conn=None): _logger.info('Initializing database') from rtrss.models import Base Base.metadata.create_all(bind=conn) def clear_db(conn=None): _logger.info('Clearing database') from rtrss.models import Base Base.metadata.drop_all(bind=conn)
import logging from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError from rtrss import OperationInterruptedException from rtrss import config _logger = logging.getLogger(__name__) engine = create_engine(config.SQLALCHEMY_DATABASE_URI, client_encoding='utf8') Session = sessionmaker(bind=engine) @contextmanager def session_scope(SessionFactory=None): """Provide a transactional scope around a series of operations.""" if SessionFactory is None: SessionFactory = Session session = SessionFactory() try: yield session except SQLAlchemyError as e: _logger.error("Database error %s", e) session.rollback() raise OperationInterruptedException(e) else: session.commit() finally: session.close() def init_db(conn=None): from rtrss.models import Base if conn is None: from database import engine as conn Base.metadata.create_all(bind=conn) def clear_db(conn=None): from rtrss.models import Base if conn is None: from database import engine as conn Base.metadata.drop_all(bind=conn)