text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove unnecessary space from the dashboard items
import React, { PropTypes } from 'react'; const formatValue = (item, results) => { if (!results.hasOwnProperty(item.query)) { return '—'; } return (item.formatValue || (e => e))(results[item.query]); }; const Dashboard = props => ( <div className="dashboard"> {props.items.map(item => ( <div className="dashboard-item" key={item.query}> {item.title} <span className="value">{formatValue(item, props.results)}</span> </div> ))} </div> ); Dashboard.propTypes = { items: PropTypes.arrayOf( PropTypes.shape({ formatValue: PropTypes.func, query: PropTypes.string.isRequired, title: PropTypes.string.isRequired }) ).isRequired, results: PropTypes.shape().isRequired }; export default Dashboard;
import React, { PropTypes } from 'react'; const formatValue = (item, results) => { if (!results.hasOwnProperty(item.query)) { return '—'; } return (item.formatValue || (e => e))(results[item.query]); }; const Dashboard = props => ( <div className="dashboard"> {props.items.map(item => ( <div className="dashboard-item" key={item.query}> {item.title}{' '} <span className="value">{formatValue(item, props.results)}</span> </div> ))} </div> ); Dashboard.propTypes = { items: PropTypes.arrayOf( PropTypes.shape({ formatValue: PropTypes.func, query: PropTypes.string.isRequired, title: PropTypes.string.isRequired }) ).isRequired, results: PropTypes.shape().isRequired }; export default Dashboard;
Use a decorator style syntax in the event attribute
import UTILS from './utils'; import HELPERS from './helpers'; const eventAttributeName = 'jtml-event'; export default class Render { constructor(func) { this.func = func; this.html = ''; } render(data, events) { this.html = this.func(data, UTILS, HELPERS); this.fragment = UTILS.fragmentFromString(this.html); Array.from(this.fragment.querySelectorAll(`[${eventAttributeName}]`)) .forEach(el => { if (events) { el.getAttribute('jtml-event').replace(/@(.*?)\((.*?)\)/g, (...args) => { let eventType = args[1]; let handlers = args[2].trim().split(/\s+/); handlers.forEach(handlers => { el.addEventListener(eventType, events[handlers]); }); }); } el.removeAttribute(eventAttributeName); }); return this; } appendTo(selectorOrNode) { if (UTILS.isDOM(selectorOrNode)) { selectorOrNode.appendChild(this.fragment); } else { let element = document.querySelector(selectorOrNode); if (element) { element.appendChild(this.fragment); } } return this; } }
import UTILS from './utils'; import HELPERS from './helpers'; const eventAttributeName = 'jtml-event'; export default class Render { constructor(func) { this.func = func; this.html = ''; } render(data, events) { this.html = this.func(data, UTILS, HELPERS); this.fragment = UTILS.fragmentFromString(this.html); Array.from(this.fragment.querySelectorAll(`[${eventAttributeName}]`)) .forEach(el => { if (events) { el.getAttribute('jtml-event').replace(/\[(.*?)]\((.*?)\)/g, (...args) => { let eventType = args[1]; let handlers = args[2].trim().split(/\s+/); handlers.forEach(handlers => { el.addEventListener(eventType, events[handlers]); }); }); } el.removeAttribute(eventAttributeName); }); return this; } appendTo(selectorOrNode) { if (UTILS.isDOM(selectorOrNode)) { selectorOrNode.appendChild(this.fragment); } else { let element = document.querySelector(selectorOrNode); if (element) { element.appendChild(this.fragment); } } return this; } }
Add passlib as package requirement
from setuptools import setup, find_packages setup( name='DeviceHub', version='0.1', packages=find_packages(), url='https://github.com/eReuse/DeviceHub', license='AGPLv3 License', author='eReuse team', author_email='x.bustamante@ereuse.org', description='The DeviceHub is a Device Management System (DMS) created under the project eReuse. Its purpose is to ' 'offer a way for donors and receivers to efficiently manage the reuse process ensuring final recycling.', install_requires=[ 'inflection', 'eve', # Which has a bug, for now... todo try 0.6.2 when stable 'passlib', 'validators' ], include_package_data=True, long_description=""" Credits: Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0">CC BY 3.0</a> """ )
from setuptools import setup, find_packages setup( name='DeviceHub', version='0.1', packages=find_packages(), url='https://github.com/eReuse/DeviceHub', license='AGPLv3 License', author='eReuse team', author_email='x.bustamante@ereuse.org', description='The DeviceHub is a Device Management System (DMS) created under the project eReuse. Its purpose is to ' 'offer a way for donors and receivers to efficiently manage the reuse process ensuring final recycling.', install_requires=[ 'inflection', 'eve', # Which has a bug, for now... todo try 0.6.2 when stable 'passlib' ], include_package_data=True, long_description=""" Credits: Icons made by <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="http://www.flaticon.com" title="Flaticon">www.flaticon.com</a> is licensed by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0">CC BY 3.0</a> """ )
internal-test-helpers: Convert `NamespacesAssert` to ES6 class
import { run } from '@ember/runloop'; import { NAMESPACES, NAMESPACES_BY_ID } from '@ember/-internals/metal'; export default class NamespacesAssert { constructor(env) { this.env = env; } reset() {} inject() {} assert() { let { assert } = QUnit.config.current; if (NAMESPACES.length > 0) { assert.ok(false, 'Should not have any NAMESPACES after tests'); run(() => { let namespaces = NAMESPACES.slice(); for (let i = 0; i < namespaces.length; i++) { namespaces[i].destroy(); } }); } let keys = Object.keys(NAMESPACES_BY_ID); if (keys.length > 0) { assert.ok(false, 'Should not have any NAMESPACES_BY_ID after tests'); for (let i = 0; i < keys.length; i++) { delete NAMESPACES_BY_ID[keys[i]]; } } } restore() {} }
import { run } from '@ember/runloop'; import { NAMESPACES, NAMESPACES_BY_ID } from '@ember/-internals/metal'; function NamespacesAssert(env) { this.env = env; } NamespacesAssert.prototype = { reset: function() {}, inject: function() {}, assert: function() { let { assert } = QUnit.config.current; if (NAMESPACES.length > 0) { assert.ok(false, 'Should not have any NAMESPACES after tests'); run(() => { let namespaces = NAMESPACES.slice(); for (let i = 0; i < namespaces.length; i++) { namespaces[i].destroy(); } }); } let keys = Object.keys(NAMESPACES_BY_ID); if (keys.length > 0) { assert.ok(false, 'Should not have any NAMESPACES_BY_ID after tests'); for (let i = 0; i < keys.length; i++) { delete NAMESPACES_BY_ID[keys[i]]; } } }, restore: function() {}, }; export default NamespacesAssert;
Raise exception if path not found, os not found, or command execution fails.
import os, platform, subprocess # I intend to hide the Operating Specific details of opening a folder # here in this module. # # On Mac OS X you do this with "open" # e.g. "open '\Users\golliher\Documents\Tickler File'" # On Windows you do this with "explorer" # e.g. "explorer c:\Documents and Settings\Tickler File" # On Linux xdg-open is a desktop-independant tool def open_folder(path): '''Runs operating specific command to open a folder. MacOS, Linux & Windows supported''' path = os.path.normpath(path) if not os.path.isdir(path): raise Exception("Folder does not exist.") # Find the operating system command to open a folder try: platform_cmd = { 'Darwin': "open", # note the quotation marks around path 'Linux': "xdg-open", 'Windows': "explorer"}[platform.system()] except: raise Exception("Your operating system was not recognized. Unable to determine how to open folders for you.") # Run the operating system command to open the folder try: subprocess.check_call([platform_cmd,path]) except OSError, e: raise Exception("Failed attempt executing folder opening command for your OS. \nCMD: %s\nARG: %s\nRESULT: %s\n" % (platform_cmd, path, e.strerror) )
import os, platform # I intend to hide the Operating Specific details of opening a folder # here in this module. # # On Mac OS X you do this with "open" # e.g. "open '\Users\golliher\Documents\Tickler File'" # On Windows you do this with "explorer" # e.g. "explorer c:\Documents and Settings\Tickler File" # On Linux xdg-open is a desktop-independant tool def open_folder(path): '''Runs operating specific command to open a folder. MacOS, Linux & Windows supported''' path = os.path.normpath(path) try: platform_cmd_formatstring = { 'Darwin': "open '%s'", # note the quotation marks around path 'Linux': "xdg-open '%s'", 'Windows': "explorer %s"}[platform.system()] except: raise Exception("Your operating system was not recognized. Unable to determine how to open folders for you.") platform_cmd = platform_cmd_formatstring % path os.popen(platform_cmd)
Fix rl mock for tests
var EventEmitter = require("events").EventEmitter; var sinon = require("sinon"); var util = require("util"); var _ = require("lodash"); var stub = { write : sinon.stub().returns(stub), moveCursor : sinon.stub().returns(stub), setPrompt : sinon.stub().returns(stub), close : sinon.stub().returns(stub), pause : sinon.stub().returns(stub), resume : sinon.stub().returns(stub), _getCursorPos : sinon.stub().returns({cols: 0, rows: 0}), output : { end : sinon.stub(), mute : sinon.stub(), unmute : sinon.stub(), __raw__: '', write : function (str) { this.__raw__ += str; } } }; var ReadlineStub = function () { EventEmitter.apply(this, arguments); }; util.inherits(ReadlineStub, EventEmitter); _.assign(ReadlineStub.prototype, stub); module.exports = ReadlineStub;
var EventEmitter = require("events").EventEmitter; var sinon = require("sinon"); var util = require("util"); var _ = require("lodash"); var stub = { write : sinon.stub().returns(stub), moveCursor : sinon.stub().returns(stub), setPrompt : sinon.stub().returns(stub), close : sinon.stub().returns(stub), pause : sinon.stub().returns(stub), resume : sinon.stub().returns(stub), _getCursorPos : sinon.stub().returns(stub), output : { end : sinon.stub(), mute : sinon.stub(), unmute : sinon.stub(), __raw__: '', write : function (str) { this.__raw__ += str; } } }; var ReadlineStub = function () { EventEmitter.apply(this, arguments); }; util.inherits(ReadlineStub, EventEmitter); _.assign(ReadlineStub.prototype, stub); module.exports = ReadlineStub;
Add input and random explainer to utility function.
from .base import * from .gradient_based import * from .misc import * from .pattern_based import * from .relevance_based import * def create_explainer(name, output_layer, patterns=None, to_layer=None, **kwargs): return { # Utility. "input": InputExplainer, "random": RandomExplainer, # Gradient based "gradient": GradientExplainer, "deconvnet": DeConvNetExplainer, "guided": GuidedBackpropExplainer, "gradient.alt": AlternativeGradientExplainer, # Relevance based "lrp.z": LRPZExplainer, "lrp.eps": LRPEpsExplainer, # Pattern based "patternnet": PatternNetExplainer, "patternnet.guided": GuidedPatternNetExplainer, "patternlrp": PatternLRPExplainer, }[name](output_layer, patterns=patterns, to_layer=to_layer, **kwargs)
from .base import * from .gradient_based import * from .misc import * from .pattern_based import * from .relevance_based import * def create_explainer(name, output_layer, patterns=None, to_layer=None, **kwargs): return { # Gradient based "gradient": GradientExplainer, "deconvnet": DeConvNetExplainer, "guided": GuidedBackpropExplainer, "gradient.alt": AlternativeGradientExplainer, # Relevance based "lrp.z": LRPZExplainer, "lrp.eps": LRPEpsExplainer, # Pattern based "patternnet": PatternNetExplainer, "patternnet.guided": GuidedPatternNetExplainer, "patternlrp": PatternLRPExplainer, }[name](output_layer, patterns=patterns, to_layer=to_layer, **kwargs)
Set the __name__ on the traversal object
class Root(object): """ The main root object for any traversal """ __name__ = None __parent__ = None def __init__(self, request): pass def __getitem__(self, key): next_ctx = None if key == 'user': next_ctx = User() if key == 'domain': next_ctx = Domains() if next_ctx is None: raise KeyError next_ctx.__parent__ = self return next_ctx class User(object): __name__ = 'user' __parent__ = None def __init__(self): pass def __getitem__(self, key): raise KeyError class Domains(object): __name__ = 'domain' __parent__ = None def __init__(self): pass def __getitem__(self, key): next_ctx = Domain(key) next_ctx.__parent__ = self return next_ctx class Domain(object): __name__ = None __parent__ = None def __init__(self, key): self.__name__ = key def __getitem__(self, key): raise KeyError
class Root(object): """ The main root object for any traversal """ __name__ = None __parent__ = None def __init__(self, request): pass def __getitem__(self, key): next_ctx = None if key == 'user': next_ctx = User() if key == 'domain': next_ctx = Domains() if next_ctx is None: raise KeyError next_ctx.__parent__ = self return next_ctx class User(object): __name__ = 'user' __parent__ = None def __init__(self): pass def __getitem__(self, key): raise KeyError class Domains(object): __name__ = 'domain' __parent__ = None def __init__(self): pass def __getitem__(self, key): next_ctx = Domain(key) next_ctx.__parent__ = self return next_ctx class Domain(object): __name__ = None __parent__ = None def __init__(self, key): pass def __getitem__(self, key): raise KeyError
Add missing ? to palindrome-parsing
module.exports = function (data) { var firstLine = data.split('\n')[0]; switch (firstLine) { case 'ping': case 'say-hello': case 'fizzbuzz': case 'fibonacci': case 'nth-word': case 'sort': return firstLine; case '+': return 'add'; case '-': return 'deduct'; case 'palindrome?': return 'palindrome'; case 'caesar-cipher': return 'caesar'; case 'iban-checksum': return 'iban'; default: return undefined; } };
module.exports = function (data) { var firstLine = data.split('\n')[0]; switch (firstLine) { case 'ping': case 'say-hello': case 'fizzbuzz': case 'palindrome': case 'fibonacci': case 'nth-word': case 'sort': return firstLine; case '+': return 'add'; case '-': return 'deduct'; case 'caesar-cipher': return 'caesar'; case 'iban-checksum': return 'iban'; default: return undefined; } };
Update of work over prior couple weeks.
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = re.sub(r'\&lt.*?\&gt\;', ' ', fd) pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
import re import sys f = open ('/var/local/meTypesetTests/tests/testOutput/'+sys.argv[1] +'/nlm/out.xml', "r") print ("open operation complete") fd = f.read() s = '' fd = pattern = re.compile(r'(?:(&#\d*|>))(.*?)(?=(&#\d*|<))') for e in re.findall(pattern, fd): s += ' ' s += e[1] s = re.sub('-', ' ', s) s = re.sub(r'\,', ' ', s) s = re.sub(r'\.', ' ', s) s = re.sub('\'', '', s) s = re.sub(r'\;', ' ', s) s = re.sub('s', ' ', s) s = re.sub(r'\(.*?\)', ' ', s) s = re.sub(r'(\[.*?\])', ' ', s) f.close() o = open ( '/var/local/meTypesetTests/tests/regexOutput/'+sys.argv[1], "w") o.write(s) o.close()
Add Props Modified To Replace State Edited In Text Add props modified to replace the state edited in the text component since props modified is used throw out the application.
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), valueLink: this.props.valueLink, }) } _cx() { return cx({ "form-group": true, "has-error": this.props.errors != null, "has-success": this.props.modified && this.props.errors == null, }) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, label(this.props), div({className: "controls"}, textarea(this._inputHtml()), ), errorList(this.props.errors), ), ) } }
let React = require("react") let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js") let {div, textarea} = React.DOM let cx = require("classnames") export default class extends React.Component { static displayName = "Frig.friggingBootstrap.Text" static defaultProps = Object.assign(require("../default_props.js")) _inputHtml() { return Object.assign({}, this.props.inputHtml, { className: `${this.props.className || ""} form-control`.trim(), valueLink: this.props.valueLink, }) } _cx() { return cx({ "form-group": true, "has-error": this.props.errors != null, "has-success": this.state.edited && this.props.errors == null, }) } render() { return div({className: cx(sizeClassNames(this.props))}, div({className: this._cx()}, label(this.props), div({className: "controls"}, textarea(this._inputHtml()), ), errorList(this.props.errors), ), ) } }
Allow specification of custom settings module using DJANGO_SETTINGS_MODULE environment variable.
# vim:ts=4:sts=4:sw=4:expandtab """The core of the system. Manages the database and operational logic. Functionality is exposed over Thrift. """ import sys import os def manage(): from django.core.management import execute_manager settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'satori.core.settings') __import__(settings_module_name) settings_module = sys.modules[settings_module_name] # HACK import django.core.management old_fmm = django.core.management.find_management_module def find_management_module(app_name): if app_name == 'satori.core': return os.path.join(os.path.dirname(__file__), 'management') else: return old_fmm(app_name) django.core.management.find_management_module = find_management_module # END OF HACK execute_manager(settings_module)
# vim:ts=4:sts=4:sw=4:expandtab """The core of the system. Manages the database and operational logic. Functionality is exposed over Thrift. """ import os def manage(): from django.core.management import execute_manager import satori.core.settings # HACK import django.core.management old_fmm = django.core.management.find_management_module def find_management_module(app_name): if app_name == 'satori.core': return os.path.join(os.path.dirname(__file__), 'management') else: return old_fmm(app_name) django.core.management.find_management_module = find_management_module # END OF HACK execute_manager(satori.core.settings)
Fix misplaced dot, causing issues with routing
<?php namespace Onion\Framework\Middleware\Internal; use Interop\Http\Middleware\ServerMiddlewareInterface; use Interop\Http\Middleware\DelegateInterface; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface; use Zend\Diactoros\Request\Uri; class ModulePathStripperMiddleware implements ServerMiddlewareInterface { private $routePathPrefix; public function __construct($prefix) { $this->routePathPrefix = $prefix; } public function process(Request $request, DelegateInterface $delegate): ResponseInterface { $path = $request->getUri()->getPath(); return $delegate->process( $request->withUri( $request->getUri()->withPath( '/' . ltrim(substr($path, strlen($this->routePathPrefix)), '/') ) ) ); } }
<?php namespace Onion\Framework\Middleware\Internal; use Interop\Http\Middleware\ServerMiddlewareInterface; use Interop\Http\Middleware\DelegateInterface; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ResponseInterface; use Zend\Diactoros\Request\Uri; class ModulePathStripperMiddleware implements ServerMiddlewareInterface { private $routePathPrefix; public function __construct($prefix) { $this->routePathPrefix = $prefix; } public function process(Request $request, DelegateInterface $delegate): ResponseInterface { $path = $request->getUri()->getPath(); return $delegate->process( $request->withUri( $request->getUri()->withPath( '/' . ltrim(substr($path, strlen($this->routePathPrefix)). '/') ) ) ); } }
Add a route to admin/news
from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form) @admin.route('/news') @login_required def news(): return render_template('admin/news.html')
from flask import render_template, redirect, url_for, flash, request from flask.ext.login import login_required, current_user from . import admin from .forms import ProfileForm from .. import db from ..models import User @admin.route('/') @login_required def index(): return render_template('admin/user.html', user=current_user) @admin.route('/edit_user', methods=['GET', 'POST']) @login_required def edit_user(): form = ProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.bio = form.bio.data db.session.add(current_user._get_current_object()) db.session.commit() flash("Síðan hefur verið uppfærð") return redirect(url_for('admin.index')) form.name.data = current_user.name form.location.data = current_user.location form.bio.data = current_user.bio return render_template('admin/edit_user.html', form=form)
Fix bug in language selection switching https://github.com/globaleaks/GlobaLeaks/issues/452
GLClient.controller('toolTipCtrl', ['$scope', '$rootScope', 'Authentication', '$location', '$cookies', 'Translations', 'Node', '$route', function($scope, $rootScope, Authentication, $location, $cookies, Translations, Node, $route) { if (!$cookies['language']) $cookies['language'] = 'en'; $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; $scope.language = $cookies['language']; $rootScope.selected_language = $scope.language; Node.get(function(node_info) { $rootScope.available_languages = {}; $rootScope.languages_supported = Translations.supported_languages; $.each(node_info.languages_enabled, function(idx, lang) { $rootScope.available_languages[lang] = Translations.supported_languages[lang]; }); }); $scope.logout = Authentication.logout; $scope.$watch("language", function(){ $.cookie('language', $scope.language); $rootScope.selected_language = $scope.language; $route.reload(); }); $scope.$watch(function(scope){ return $cookies['session_id']; }, function(newVal, oldVal){ $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; }); }]);
GLClient.controller('toolTipCtrl', ['$scope', '$rootScope', 'Authentication', '$location', '$cookies', 'Translations', 'Node', '$route', function($scope, $rootScope, Authentication, $location, $cookies, Translations, Node, $route) { if (!$cookies['language']) $cookies['language'] = 'en'; $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; $scope.language = $cookies['language']; $rootScope.selected_language = $scope.language; Node.get(function(node_info) { $rootScope.available_languages = {}; $rootScope.languages_supported = Translations.supported_languages; $.each(node_info.languages_enabled, function(idx, lang) { $rootScope.available_languages[lang] = Translations.supported_languages[lang]; }); }); $scope.logout = Authentication.logout; $scope.$watch("language", function(){ $cookies['language'] = $scope.language; $route.reload(); }); $scope.$watch(function(scope){ return $cookies['session_id']; }, function(newVal, oldVal){ $scope.session_id = $cookies['session_id']; $scope.auth_landing_page = $cookies['auth_landing_page']; $scope.role = $cookies['role']; }); }]);
Fix migration for the version checking
<?php use App\Instance; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInstanceTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('instances', function (Blueprint $table) { $table->increments('id'); $table->string('uuid'); $table->string('current_version'); $table->string('latest_version')->nullable(); $table->mediumText('latest_release_notes')->nullable(); $table->integer('number_of_versions_since_current_version')->nullable(); $table->timestamps(); }); $instance = new Instance; $instance->current_version = config('monica.app_version'); $instance->latest_version = config('monica.app_version'); $instance->uuid = uniqid(); $instance->save(); } }
<?php use App\Instance; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInstanceTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('instances', function (Blueprint $table) { $table->increments('id'); $table->string('uuid'); $table->string('current_version'); $table->string('latest_version')->nullable(); $table->mediumText('latest_release_notes')->nullable(); $table->integer('number_of_versions_since_current_version')->nullable(); $table->timestamps(); }); $instance = new Instance; $instance->current_version = config('monica.app_version'); $instance->uuid = uniqid(); $instance->save(); } }
Fix errors if helper doesn't exist
<?php /** * Hackwork v2.0.0-beta (http://git.io/hackwork) * Licensed under the MIT License. */ /* * Paths * * Omit trailing slashes here. */ // Root define('ROOT', $_SERVER['DOCUMENT_ROOT']); define('PATH', ROOT); // Core define('CORE', PATH . '/core'); define('HELPERS', CORE . '/helpers'); // Layouts define('LAYOUTS', PATH . '/layouts'); // Data define('DATA', PATH . '/data'); // Assets define('ASSETS', '/assets'); define('CSS', ASSETS . '/css'); define('JS', ASSETS . '/js'); define('FONTS', ASSETS . '/fonts'); define('IMG', ASSETS . '/img'); /* * Helpers */ $helpers = array( 'http', 'errors', 'layout', 'config' ); foreach ($helpers as $helper) { $helper = HELPERS . "/$helper.php"; if (file_exists($helper)) { require_once $helper; } }
<?php /** * Hackwork v2.0.0-beta (http://git.io/hackwork) * Licensed under the MIT License. */ /* * Paths * * Omit trailing slashes here. */ // Root define('ROOT', $_SERVER['DOCUMENT_ROOT']); define('PATH', ROOT); // Core define('CORE', PATH . '/core'); define('HELPERS', CORE . '/helpers'); // Layouts define('LAYOUTS', PATH . '/layouts'); // Data define('DATA', PATH . '/data'); // Assets define('ASSETS', '/assets'); define('CSS', ASSETS . '/css'); define('JS', ASSETS . '/js'); define('FONTS', ASSETS . '/fonts'); define('IMG', ASSETS . '/img'); /* * Helpers */ $helpers = array( 'http', 'errors', 'layout', 'config' ); foreach ($helpers as $helper) { require_once HELPERS . "/$helper.php"; }
Add validation for new columns
<?php namespace Rogue\Http\Requests\Three; use Rogue\Http\Requests\Request; class PostRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'campaign_id' => 'required', 'campaign_run_id' => 'required_with:campaign_id|integer', 'northstar_id' => 'nullable|objectid', 'type' => 'required|string', 'action' => 'required|string', 'why_participated' => 'nullable|string', 'caption' => 'required|nullable|string|max:140', 'quantity' => 'nullable|integer', 'file' => 'image|dimensions:min_width=400,min_height=400', 'status' => 'in:pending,accepted,rejected', 'details'=> 'json', ]; } }
<?php namespace Rogue\Http\Requests\Three; use Rogue\Http\Requests\Request; class PostRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'campaign_id' => 'required', 'campaign_run_id' => 'required_with:campaign_id|integer', 'northstar_id' => 'nullable|objectid', 'why_participated' => 'nullable|string', 'caption' => 'required|nullable|string|max:140', 'quantity' => 'nullable|integer', 'file' => 'image|dimensions:min_width=400,min_height=400', 'status' => 'in:pending,accepted,rejected', ]; } }
Set a subscription relationship for users
<?php namespace App\Data; use UserPresenter; use App\Authorization; use Illuminate\Notifications\Notifiable; use Laracasts\Presenter\PresentableTrait; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Authorizable, Authorization, Notifiable, PresentableTrait; protected $table = 'core_users'; protected $fillable = ['points', 'signature']; protected $hidden = ['password', 'remember_token']; protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $presenter = UserPresenter::class; //-------------------------------------------------------------------------- // Relationships //-------------------------------------------------------------------------- public function discussions() { return $this->hasMany(Discussion::class)->latest(); } public function replies() { return $this->hasMany(Reply::class); } public function subscriptions() { return $this->hasMany(DiscussionSubscription::class); } //-------------------------------------------------------------------------- // Model Scopes //-------------------------------------------------------------------------- public function scopeUsername($query, $username) { $query->where('username', $username); } //-------------------------------------------------------------------------- // Model Methods //-------------------------------------------------------------------------- public function getRouteKeyName() { return 'username'; } }
<?php namespace App\Data; use UserPresenter; use App\Authorization; use Illuminate\Notifications\Notifiable; use Laracasts\Presenter\PresentableTrait; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Authorizable, Authorization, Notifiable, PresentableTrait; protected $table = 'core_users'; protected $fillable = ['points', 'signature']; protected $hidden = ['password', 'remember_token']; protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $presenter = UserPresenter::class; //-------------------------------------------------------------------------- // Relationships //-------------------------------------------------------------------------- public function discussions() { return $this->hasMany(Discussion::class)->latest(); } public function replies() { return $this->hasMany(Reply::class); } //-------------------------------------------------------------------------- // Model Scopes //-------------------------------------------------------------------------- public function scopeUsername($query, $username) { $query->where('username', $username); } //-------------------------------------------------------------------------- // Model Methods //-------------------------------------------------------------------------- public function getRouteKeyName() { return 'username'; } }
Change log level for 'Request accepted'
import * as Types from './types' const initialState = { server: {} } const mapServerState = (serverState, state) => { return { ...state, server: serverState } } export default (state = initialState, action) => { switch (action.type) { case Types.SERVER_STATE_LOADED: return mapServerState(action.serverState, state) return state case Types.REQUEST_ACCEPTED_BY_SERVER: console.debug('Request accepted:', action.url) return state case Types.SERVER_STATE_LOAD_FAILED: case Types.REQUEST_ACCEPTED_BY_SERVER: console.error(action.error) return state default: return state } }
import * as Types from './types' const initialState = { server: {} } const mapServerState = (serverState, state) => { return { ...state, server: serverState } } export default (state = initialState, action) => { switch (action.type) { case Types.SERVER_STATE_LOADED: return mapServerState(action.serverState, state) return state; case Types.REQUEST_ACCEPTED_BY_SERVER: console.log('Request accepted:', action.url); return state; case Types.SERVER_STATE_LOAD_FAILED: case Types.REQUEST_ACCEPTED_BY_SERVER: console.error(action.error) return state default: return state } }
Clean up code and add comments
define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) { 'use strict'; var ClearInput, uiEvents = { 'keydown [data-dough-clear-input]' : 'updateResetButton', 'click [data-dough-clear-input-button]' : 'resetForm' }; ClearInput = function($el, config) { this.uiEvents = uiEvents; ClearInput.baseConstructor.call(this, $el, config); this.$resetInput = this.$el.find('[data-dough-clear-input]'); this.$resetButton = this.$el.find('[data-dough-clear-input-button]'); }; /** * Inherit from base module, for shared methods and interface */ DoughBaseComponent.extend(ClearInput); /** * Set up and populate the model from the form inputs * @param {Promise} initialised */ ClearInput.prototype.init = function(initialised) { this._initialisedSuccess(initialised); }; ClearInput.prototype.updateResetButton = function() { var fn = this.$resetInput.val() === '' ? 'removeClass' : 'addClass'; this.$resetButton[fn]('is-active'); }; // We are progressively enhancing the form with JS. The CSS button, type 'reset' // resets the form faster than the JS can run, so we need to invoke reset() to ensure the correct behaviour. ClearInput.prototype.resetForm = function() { this.$el[0].reset(); this.updateResetButton(); }; return ClearInput; });
define(['jquery', 'DoughBaseComponent'], function($, DoughBaseComponent) { 'use strict'; var ClearInput, uiEvents = { 'keydown [data-dough-clear-input]' : 'updateResetButton', 'click [data-dough-clear-input-button]' : 'resetForm' }; ClearInput = function($el, config) { var _this = this; this.uiEvents = uiEvents; ClearInput.baseConstructor.call(this, $el, config); this.$resetInput = this.$el.find('[data-dough-clear-input]'); this.$resetButton = this.$el.find('[data-dough-clear-input-button]'); }; /** * Inherit from base module, for shared methods and interface */ DoughBaseComponent.extend(ClearInput); /** * Set up and populate the model from the form inputs * @param {Promise} initialised */ ClearInput.prototype.init = function(initialised) { this._initialisedSuccess(initialised); }; ClearInput.prototype.updateResetButton = function() { var fn = (this.$resetInput.val() == '') ? 'removeClass' : 'addClass'; this.$resetButton[fn]('is-active'); }; ClearInput.prototype.resetForm = function() { this.$el[0].reset(); this.updateResetButton(); }; return ClearInput; });
Make Mail Queueable by default
<?php namespace FlyingLuscas\BugNotifier\Drivers; use Illuminate\Support\Facades\Mail; use FlyingLuscas\BugNotifier\Message; class MailDriver extends Driver implements DriverInterface { /** * Send e-mail message. * * @param \FlyingLuscas\BugNotifier\Message $message * * @return void */ public function handle(Message $message) { $view = $this->config('view'); $addresses = $this->getEmailAddresses(); $subject = $message->getTitle(); $body = $message->getBody(); Mail::queue($view, [ 'body' => $body, 'subject' => $subject, ], function ($mail) use ($subject, $addresses) { $mail->subject($subject)->to($addresses); }); } /** * Get e-mail address list. * * @return array */ private function getEmailAddresses() { $address = $this->config('to.address'); if ($address) { return [$address]; } return $this->config('to'); } }
<?php namespace FlyingLuscas\BugNotifier\Drivers; use Illuminate\Support\Facades\Mail; use FlyingLuscas\BugNotifier\Message; class MailDriver extends Driver implements DriverInterface { /** * Send e-mail message. * * @param \FlyingLuscas\BugNotifier\Message $message * * @return void */ public function handle(Message $message) { $view = $this->config('view'); $addresses = $this->getEmailAddresses(); $subject = $message->getTitle(); $body = $message->getBody(); Mail::send($view, [ 'body' => $body, 'subject' => $subject, ], function ($mail) use ($subject, $addresses) { $mail->subject($subject)->to($addresses); }); } /** * Get e-mail address list. * * @return array */ private function getEmailAddresses() { $address = $this->config('to.address'); if ($address) { return [$address]; } return $this->config('to'); } }
Use number generator with seed
var instances = require('./../taillard'); var seed = require('./../seed-random'); var NEH = require('./../neh'); // Iterate over filtered Taillard instances var filteredInstances = instances.filter(50, 20); for(var i = 0; i < filteredInstances.length; i++) { // Overwrite Math.random by number generator with seed seed(filteredInstances[i].initialSeed, true); console.log(' name:', filteredInstances[i].name); console.log(' number of jobs:', filteredInstances[i].numberOfJobs); console.log(' number of machines:', filteredInstances[i].numberOfMachines); console.log(' initial seed:', filteredInstances[i].initialSeed); console.log(' lower bound:', filteredInstances[i].lowerBound); console.log(' upper bound:', filteredInstances[i].upperBound); console.log(' NEH makespan:', NEH.makespan(filteredInstances[i].data)); console.log('__________________________________________________'); }
var instances = require('./../taillard'); var NEH = require('./../neh'); var seed = require('./../seed-random'); // Iterate over filtered Taillard instances var filteredInstances = instances.filter(50, 20); for(var i = 0; i < filteredInstances.length; i++) { // Overwrite Math.random by number generator with seed seed(filteredInstances[i].initialSeed, true); console.log(' name:', filteredInstances[i].name); console.log(' number of jobs:', filteredInstances[i].numberOfJobs); console.log(' number of machines:', filteredInstances[i].numberOfMachines); console.log(' initial seed:', filteredInstances[i].initialSeed); console.log(' lower bound:', filteredInstances[i].lowerBound); console.log(' upper bound:', filteredInstances[i].upperBound); console.log(' NEH makespan:', NEH.makespan(filteredInstances[i].data)); console.log('__________________________________________________'); }
Add list with list test.
import pytest from eche.reader import read_str from eche.printer import print_str import math @pytest.mark.parametrize("test_input", [ '1', '-1', '0', str(math.pi), str(math.e) ]) def test_numbers(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ '*', '+', 'abc', 'test1', 'abc-def', ]) def test_eche_type_symbol(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ '((9 8))', '()', '(* 1 2)', '(+ (* 1 5) (/ 1 0))' ]) def test_eche_type_list(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ 'nil', ]) def test_nil(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ 'true', 'false', ]) def test_bool(test_input): assert print_str(read_str(test_input)) == test_input
import pytest from eche.reader import read_str from eche.printer import print_str import math @pytest.mark.parametrize("test_input", [ '1', '-1', '0', str(math.pi), str(math.e) ]) def test_numbers(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ '*', '+', 'abc', 'test1', 'abc-def', ]) def test_eche_type_symbol(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ '()', '(* 1 2)', '(+ (* 1 5) (/ 1 0))' ]) def test_eche_type_list(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ 'nil', ]) def test_nil(test_input): assert print_str(read_str(test_input)) == test_input @pytest.mark.parametrize("test_input", [ 'true', 'false', ]) def test_bool(test_input): assert print_str(read_str(test_input)) == test_input
Fix project name in license section
# Yith Library Web Client is a client for Yith Library Server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Web Client. # # Yith Library Web Client is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Web Client is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Web Client. If not, see <http://www.gnu.org/licenses/>. import os import os.path from paste.deploy import loadapp from waitress import serve basedir= os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join(basedir, 'production.ini') application = loadapp('config:%s' % conf_file) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) scheme = os.environ.get("SCHEME", "https") serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
# Yith Library Server is a password storage server. # Copyright (C) 2015 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Yith Library Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Yith Library Server. If not, see <http://www.gnu.org/licenses/>. import os import os.path from paste.deploy import loadapp from waitress import serve basedir= os.path.dirname(os.path.realpath(__file__)) conf_file = os.path.join(basedir, 'production.ini') application = loadapp('config:%s' % conf_file) if __name__ == "__main__": port = int(os.environ.get("PORT", 5000)) scheme = os.environ.get("SCHEME", "https") serve(application, host='0.0.0.0', port=port, url_scheme=scheme)
III-680: Use complete class name for Integer type hinting in docblocks to prevent IDE confusion with int.
<?php /** * @file */ namespace CultuurNet\UDB3\Search; use ValueObjects\Number\Integer; class Results { /** * @var array */ private $items; /** * @var Integer */ private $totalItems; /** * @param array $items * @param \ValueObjects\Number\Integer $totalItems */ public function __construct(array $items, Integer $totalItems) { $this->items = $items; $this->totalItems = $totalItems; } /** * @return array */ public function getItems() { return $this->items; } /** * @return \ValueObjects\Number\Integer */ public function getTotalItems() { return $this->totalItems; } }
<?php /** * @file */ namespace CultuurNet\UDB3\Search; use ValueObjects\Number\Integer; class Results { /** * @var array */ private $items; /** * @var Integer */ private $totalItems; /** * @param array $items * @param Integer $totalItems */ public function __construct(array $items, Integer $totalItems) { $this->items = $items; $this->totalItems = $totalItems; } /** * @return array */ public function getItems() { return $this->items; } /** * @return Integer */ public function getTotalItems() { return $this->totalItems; } }
Fix a bug in the clock runner
pull.component('clockRunKiller', function () { var s = this var g = s.generic var ls = s.localStorageAdapter return [ kickOff , toggleRun ] /* Initializes a new counter */ function kickOff () { makeMaster() s.periodControl.newPeriod('run') ls.resetState() ls.setRunning() } /* Makes a client the owner of the second counter */ function makeMaster () { s.intervalControler.newInterval('secondIncrement', shouldUpdateSeconds, 1000) s.intervalControler.newInterval('shouldDoNextPeriod', s.periodControl.shouldDoNextPeriod, 100) } /* Increments seconds if the clocks running */ function shouldUpdateSeconds () { if(ls.isRunning()) return ls.updateSeconds() } /* Toggles the clock runner */ function toggleRun () { makeMaster() return ls.isRunning() ? ls.removeRunning() : ls.setRunning() } }, [ 'generic' , 'intervalControler' , 'localStorageAdapter' , 'periodControl' ])
pull.component('clockRunKiller', function () { var s = this var g = s.generic var ls = s.localStorageAdapter return [ kickOff , toggleRun ] /* Initializes a new counter */ function kickOff () { makeMaster() s.periodControl.newPeriod('run') ls.resetState() ls.setRunning() } /* Makes a client the owner of the second counter */ function makeMaster () { s.intervalControler.newInterval('secondIncrement', shouldUpdateSeconds, 1000) s.intervalControler.newInterval('shouldDoNextPeriod', s.periodControl.shouldDoNextPeriod, 100) } /* Increments seconds if the clocks running */ function shouldUpdateSeconds () { if(ls.isRunning) return ls.updateSeconds() } /* Toggles the clock runner */ function toggleRun () { makeMaster() return ls.isRunning() ? ls.removeRunning() : ls.setRunning() } }, [ 'generic' , 'intervalControler' , 'localStorageAdapter' , 'periodControl' ])
Handle newlines in proposed json
<?php require_once("utilities.php"); $file = fopen("cached/proposed.json","w"); $count = 0; $result = doUnprotectedQuery("SELECT pv_id, pv_name, pv_lat, pv_lng, pv_images, pv_population, pv_dev_problem, DATE_FORMAT(pv_date_added, '%M %e, %Y') AS dateAdded FROM proposed_villages WHERE pv_promoted=0"); while ($row = $result->fetch_assoc()) { fwrite($file, ($count > 0 ? "," : '{ "type": "FeatureCollection", "features": ['). '{ "type": "Feature", "geometry": { "type": "Point", "coordinates": ['.$row['pv_lng'].', '.$row['pv_lat'].'] }, "properties": { "id": "'.$row['pv_id'].'", "name": "'.$row['pv_name'].'", "pictures": "'.$row['pv_images'].'", "date_added": "'.$row['dateAdded'].'", "dev_problem": "'.str_replace(array("\r\n", "\n", "\r"), ' ', $row['pv_dev_problem']).'", "population": "'.$row['pv_population'].'" } }'); $count++; } fwrite($file, "]}"); fclose($file); ?>
<?php require_once("utilities.php"); $file = fopen("cached/proposed.json","w"); $count = 0; $result = doUnprotectedQuery("SELECT pv_id, pv_name, pv_lat, pv_lng, pv_images, pv_population, pv_dev_problem, DATE_FORMAT(pv_date_added, '%M %e, %Y') AS dateAdded FROM proposed_villages WHERE pv_promoted=0"); while ($row = $result->fetch_assoc()) { fwrite($file, ($count > 0 ? "," : '{ "type": "FeatureCollection", "features": ['). '{ "type": "Feature", "geometry": { "type": "Point", "coordinates": ['.$row['pv_lng'].', '.$row['pv_lat'].'] }, "properties": { "id": "'.$row['pv_id'].'", "name": "'.$row['pv_name'].'", "pictures": "'.$row['pv_images'].'", "date_added": "'.$row['dateAdded'].'", "dev_problem": "'.$row['pv_dev_problem'].'", "population": "'.$row['pv_population'].'" } }'); $count++; } fwrite($file, "]}"); fclose($file); ?>
Rename class to match intent
from twisted.web.server import Site, Request class AddSecurityHeadersRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddSecurityHeadersRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddSecurityHeadersRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
from twisted.web.server import Site, Request class AddCSPHeaderRequest(Request): CSP_HEADER_VALUES = "default-src 'self'; style-src 'self' 'unsafe-inline'" def process(self): self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES) self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES) self.setHeader('X-Frame-Options', 'SAMEORIGIN') self.setHeader('X-XSS-Protection', '1; mode=block') self.setHeader('X-Content-Type-Options', 'nosniff') if self.isSecure(): self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains') Request.process(self) class PixelatedSite(Site): requestFactory = AddCSPHeaderRequest @classmethod def enable_csp_requests(cls): cls.requestFactory = AddCSPHeaderRequest @classmethod def disable_csp_requests(cls): cls.requestFactory = Site.requestFactory
Fix an import error. pylons.config doesn't exist anymore, use pylons.configuration --HG-- branch : trunk
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = g = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = c = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
"""Base objects to be exported for use in Controllers""" from paste.registry import StackedObjectProxy from pylons.config import config __all__ = ['app_globals', 'c', 'cache', 'config', 'g', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = g = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = c = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
Remove % wrappers for node environment variables, fix forEach print to only print first argument.
var fs = require('fs'); var environmentVariables = [ "WEBSITE_SITE_NAME", "WEBSITE_SKU", "WEBSITE_COMPUTE_MODE", "WEBSITE_HOSTNAME", "WEBSITE_INSTANCE_ID", "WEBSITE_NODE_DEFAULT_VERSION", "WEBSOCKET_CONCURRENT_REQUEST_LIMIT", "APPDATA", "TMP", "WEBJOBS_PATH", "WEBJOBS_NAME", "WEBJOBS_TYPE", "WEBJOBS_DATA_PATH", "WEBJOBS_RUN_ID", "WEBJOBS_SHUTDOWN_FILE" ] module.exports = function (context, req, res) { context.log('function triggered'); context.log(req); context.log('Environment Variables'); environmentVariables .map(getEnvironmentVarible) .forEach(function (x) { context.log(x); }); context.log('process.cwd()', process.cwd()); context.log('__dirname', __dirname); fs.writeFile('D:/local/Temp/message.txt', 'Hello Node.js', (err) => { if (err) throw err; context.log("It's saved!"); context.done(); }); } function getEnvironmentVarible(name) { return name + ": " + process.env[name]; }
var fs = require('fs'); var environmentVariables = [ "WEBSITE_SITE_NAME", "WEBSITE_SKU", "WEBSITE_COMPUTE_MODE", "WEBSITE_HOSTNAME", "WEBSITE_INSTANCE_ID", "WEBSITE_NODE_DEFAULT_VERSION", "WEBSOCKET_CONCURRENT_REQUEST_LIMIT", "%APPDATA%", "%TMP%" ] module.exports = function (context, req, res) { context.log('function triggered'); context.log(req); context.log('Environment Variables'); environmentVariables .map(getEnvironmentVarible) .forEach(context.log); context.log('process.cwd()', process.cwd()); context.log('__dirname', __dirname); fs.writeFile('D:/local/Temp/message.txt', 'Hello Node.js', (err) => { if (err) throw err; context.log("It's saved!"); context.done(); }); } function getEnvironmentVarible(name) { return name + ": " + process.env[name]; }
Add Bitters partials to Gulp paths to watch for changes Closes #207
var gulp = require("gulp"), autoprefix = require("gulp-autoprefixer"), sass = require("gulp-sass"), connect = require("gulp-connect"), bourbon = require("node-bourbon").includePaths; var paths = { scss: [ "./app/assets/stylesheets/**/*.scss", "./contrib/*.scss" ] }; gulp.task("sass", function () { return gulp.src(paths.scss) .pipe(sass({ includePaths: ["styles"].concat(bourbon) })) .pipe(autoprefix("last 2 versions")) .pipe(gulp.dest("./contrib")) .pipe(connect.reload()); }); gulp.task("connect", function() { connect.server({ root: "contrib", port: 8000, livereload: true }); }); gulp.task("default", ["sass", "connect"], function() { gulp.watch(paths.scss, ["sass"]); });
var gulp = require("gulp"), autoprefix = require("gulp-autoprefixer"), sass = require("gulp-sass"), connect = require("gulp-connect"), bourbon = require("node-bourbon").includePaths; var paths = { scss: "./contrib/*.scss" }; gulp.task("sass", function () { return gulp.src(paths.scss) .pipe(sass({ includePaths: ["styles"].concat(bourbon) })) .pipe(autoprefix("last 2 versions")) .pipe(gulp.dest("./contrib")) .pipe(connect.reload()); }); gulp.task("connect", function() { connect.server({ root: "contrib", port: 8000, livereload: true }); }); gulp.task("default", ["sass", "connect"], function() { gulp.watch(paths.scss, ["sass"]); });
Use default 'django' logger to facilitate logging configuration (default config enabled console output).
""" Import the required subclasses of :class:`~qrcode.image.base.BaseImage` from the qrcode library with a fallback to SVG format when the Pillow library is not available. """ import logging from qrcode.image.svg import SvgPathImage as _SvgPathImage logger = logging.getLogger('django') try: from qrcode.image.pil import PilImage as _PilImageOrFallback except ImportError: logger.info("Pillow is not installed. No support available for PNG format.") from qrcode.image.svg import SvgPathImage as _PilImageOrFallback SVG_FORMAT_NAME = 'svg' PNG_FORMAT_NAME = 'png' SvgPathImage = _SvgPathImage PilImageOrFallback = _PilImageOrFallback def has_png_support(): return PilImageOrFallback is not SvgPathImage def get_supported_image_format(image_format): image_format = image_format.lower() if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]: logger.warning('Unknown image format: %s' % image_format) image_format = SVG_FORMAT_NAME elif image_format == PNG_FORMAT_NAME and not has_png_support(): logger.warning("No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.") image_format = SVG_FORMAT_NAME return image_format
""" Import the required subclasses of :class:`~qrcode.image.base.BaseImage` from the qrcode library with a fallback to SVG format when the Pillow library is not available. """ import logging from qrcode.image.svg import SvgPathImage as _SvgPathImage logger = logging.getLogger(__name__) try: from qrcode.image.pil import PilImage as _PilImageOrFallback except ImportError: logger.info("Pillow is not installed. No support available for PNG format.") from qrcode.image.svg import SvgPathImage as _PilImageOrFallback SVG_FORMAT_NAME = 'svg' PNG_FORMAT_NAME = 'png' SvgPathImage = _SvgPathImage PilImageOrFallback = _PilImageOrFallback def has_png_support(): return PilImageOrFallback is not SvgPathImage def get_supported_image_format(image_format): image_format = image_format.lower() if image_format not in [SVG_FORMAT_NAME, PNG_FORMAT_NAME]: logger.warning('Unknown image format: %s' % image_format) image_format = SVG_FORMAT_NAME elif image_format == PNG_FORMAT_NAME and not has_png_support(): logger.warning("No support available for PNG format, SVG will be used instead. Please install Pillow for PNG support.") image_format = SVG_FORMAT_NAME return image_format
Update Sami theme as default.
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('*'); return new Sami($iterator, array( 'theme' => 'default', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__ . '/build/sami/%version%', 'cache_dir' => __DIR__ . '/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ));
<?php use Sami\Sami; use Sami\Version\GitVersionCollection; use Symfony\Component\Finder\Finder; $iterator = Finder::create() ->files() ->name('*.php') ->exclude('Resources') ->in($dir = 'src'); $versions = GitVersionCollection::create($dir) ->add('develop', 'develop branch') ->add('master', 'master branch') ->addFromTags('*'); return new Sami($iterator, array( 'theme' => 'enhanced', 'versions' => $versions, 'title' => 'AuthBucket\Bundle\OAuth2Bundle API', 'build_dir' => __DIR__ . '/build/sami/%version%', 'cache_dir' => __DIR__ . '/build/cache/sami/%version%', 'include_parent_data' => false, 'default_opened_level' => 3, ));
Functional: Fix mesos baymodel creation case Mesos expects a docker network driver type. Partially implements: blueprint mesos-functional-testing Change-Id: I74946b51c9cb852f016c6e265d1700ae8bc3aa17
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel', network_driver='docker') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from magnum.tests.functional.python_client_base import BayTest class TestBayModelResource(BayTest): coe = 'mesos' def test_baymodel_create_and_delete(self): self._test_baymodel_create_and_delete('test_mesos_baymodel') class TestBayResource(BayTest): coe = 'mesos' def test_bay_create_and_delete(self): baymodel_uuid = self._test_baymodel_create_and_delete( 'test_mesos_baymodel', delete=False, tls_disabled=True, network_driver='docker') self._test_bay_create_and_delete('test_mesos_bay', baymodel_uuid)
Clean content types table and don't load tags when running loaddata
import sys from django.apps import AppConfig from django.conf import settings from common.helpers.db import db_is_initialized class CommonConfig(AppConfig): name = 'common' def ready(self): self.display_missing_environment_variables() from common.helpers.tags import import_tags_from_csv if 'loaddata' in sys.argv: self.loaddata_clean() elif db_is_initialized(): import_tags_from_csv() def display_missing_environment_variables(self): missing_required_variables = [] for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items(): if not (hasattr(settings, key)): if value['error']: missing_required_variables.append(key) print(key + ' not set: ' + value['message']) if len(missing_required_variables) > 0: raise EnvironmentError('Required environment variables missing: ' + ','.join(missing_required_variables)) def loaddata_clean(self): from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete()
from django.apps import AppConfig from django.conf import settings from common.helpers.db import db_is_initialized class CommonConfig(AppConfig): name = 'common' def ready(self): self.display_missing_environment_variables() from common.helpers.tags import import_tags_from_csv if db_is_initialized(): import_tags_from_csv() def display_missing_environment_variables(self): missing_required_variables = [] for key, value in settings.ENVIRONMENT_VARIABLE_WARNINGS.items(): if not (hasattr(settings, key)): if value['error']: missing_required_variables.append(key) print(key + ' not set: ' + value['message']) if len(missing_required_variables) > 0: raise EnvironmentError('Required environment variables missing: ' + ','.join(missing_required_variables))
Disable now-unused Sentry performance traces
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb import 'core-js/stable'; import 'regenerator-runtime/runtime'; import * as Sentry from '@sentry/react'; import { Integrations } from '@sentry/tracing'; const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false'; if (isOnline && process.env.NODE_ENV !== 'test') { Sentry.init({ dsn: process.env.NEMO_SENTRY_DSN, integrations: [new Integrations.BrowserTracing()], // Uncomment to enable Sentry performance monitoring (disabled in favor of Scout). // Percentage between 0.0 - 1.0. //tracesSampleRate: 1.0, }); } // Support component names relative to this directory: const componentRequireContext = require.context('components', true); const ReactRailsUJS = require('react_ujs'); ReactRailsUJS.useContext(componentRequireContext);
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb import 'core-js/stable'; import 'regenerator-runtime/runtime'; import * as Sentry from '@sentry/react'; import { Integrations } from '@sentry/tracing'; const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false'; if (isOnline && process.env.NODE_ENV !== 'test') { Sentry.init({ dsn: process.env.NEMO_SENTRY_DSN, integrations: [new Integrations.BrowserTracing()], // Percentage between 0.0 - 1.0. tracesSampleRate: 1.0, }); } // Support component names relative to this directory: const componentRequireContext = require.context('components', true); const ReactRailsUJS = require('react_ujs'); ReactRailsUJS.useContext(componentRequireContext);
Use the proper column implementation.
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.query.given; import io.spine.query.CustomColumn; /** * Custom columns that define entity lifecycle. * * <p>Used in the smoke testing of entity query builders. */ public enum Lifecycle { ARCHIVED(new ArchivedColumn()), DELETED(new DeletedColumn()); private final CustomColumn<?, Boolean> column; Lifecycle(CustomColumn<?, Boolean> column) { this.column = column; } /** Returns the column declaration. */ public CustomColumn<?, Boolean> column() { return column; } }
/* * Copyright 2020, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.query.given; import io.spine.query.CustomColumn; /** * Custom columns that define entity lifecycle. * * <p>Used in the smoke testing of entity query builders. */ public enum Lifecycle { ARCHIVED(new ArchivedColumn()), DELETED(new ArchivedColumn()); private final CustomColumn<?, Boolean> column; Lifecycle(CustomColumn<?, Boolean> column) { this.column = column; } /** Returns the column declaration. */ public CustomColumn<?, Boolean> column() { return column; } }
Change name displayed for desktop streaming device in the media configuration panel.
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.device; import javax.media.*; import net.java.sip.communicator.impl.neomedia.imgstreaming.*; import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*; /** * Add ImageStreaming capture device. * * @author Sebastien Vincent */ public class ImageStreamingAuto { /** * Add capture devices. * * @throws Exception if problem when adding capture devices */ public ImageStreamingAuto() throws Exception { String name = "Experimental desktop streaming"; CaptureDeviceInfo devInfo = new CaptureDeviceInfo( name, new MediaLocator( ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name), DataSource.getFormats()); /* add to JMF device manager */ CaptureDeviceManager.addDevice(devInfo); CaptureDeviceManager.commit(); } }
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.neomedia.device; import javax.media.*; import net.java.sip.communicator.impl.neomedia.imgstreaming.*; import net.java.sip.communicator.impl.neomedia.jmfext.media.protocol.imgstreaming.*; /** * Add ImageStreaming capture device. * * @author Sebastien Vincent */ public class ImageStreamingAuto { /** * Add capture devices. * * @throws Exception if problem when adding capture devices */ public ImageStreamingAuto() throws Exception { String name = "Desktop streaming"; CaptureDeviceInfo devInfo = new CaptureDeviceInfo( name, new MediaLocator( ImageStreamingUtils.LOCATOR_PROTOCOL + ":" + name), DataSource.getFormats()); /* add to JMF device manager */ CaptureDeviceManager.addDevice(devInfo); CaptureDeviceManager.commit(); } }
Switch to a mutation timestamp
import logging from followthemoney import model from servicelayer.worker import Worker from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, task, entities): next_stage = task.context.get('next_stage') if next_stage is None or not len(entities): return stage = task.job.get_stage(next_stage) log.info("Sending %s entities to: %s", len(entities), next_stage) stage.queue({'entity_ids': entities}, task.context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task, manager.emitted)
import logging from followthemoney import model from servicelayer.worker import Worker from ingestors.manager import Manager log = logging.getLogger(__name__) class IngestWorker(Worker): """A long running task runner that uses Redis as a task queue""" def dispatch_next(self, task, entities): next_stage = task.context.get('next_stage') if next_stage is None: return stage = task.job.get_stage(next_stage) log.info("Sending %s entities to: %s", len(entities), next_stage) stage.queue({'entity_ids': entities}, task.context) def handle(self, task): manager = Manager(task.stage, task.context) entity = model.get_proxy(task.payload) log.debug("Ingest: %r", entity) manager.ingest_entity(entity) manager.close() self.dispatch_next(task, manager.emitted)
Remove test data from database after tests are run
var chai = require('chai'); var expect = chai.expect; var models = require('../server/db/models'); var request = require('request'); var localServerUri = 'http://127.0.0.1:3000/'; var GETUri = localServerUri + '?x=100.123456&y=-50.323&z=14.4244'; var testData = {x: 100.123456, y: -50.323, z: 14.4244, message: 'hello database!'}; describe('server to database integration', function() { after(function() { models.removeData('marks', 'x', 100.123459); models.removeData('messages', 'messageString', "'hello database!'"); }); it('should persist valid POST request to database', function(done) { request.post({url:localServerUri, form: testData}, function(err, response, body) { models.retrieve(testData, function(messages) { var messageString = messages[0].messageString; expect(messageString).to.equal(testData.message); done(); }); }); }); it('should GET messages from databases', function(done) { request(GETUri, function(err, response, body) { var messages = JSON.parse(response.body); expect(messages).to.be.a('array'); done(); }); }); });
var chai = require('chai'); var expect = chai.expect; var models = require('../server/db/models'); var request = require('request'); var localServerUri = 'http://127.0.0.1:3000/'; var GETUri = localServerUri + '?x=100.123456&y=-50.323&z=14.4244'; var testData = {x: 100.123456, y: -50.323, z: 14.4244, message: 'hello database!'}; describe('server to database integration', function() { it('should persist valid POST request to database', function(done) { request.post({url:localServerUri, form: testData}, function(err, response, body) { models.retrieve(testData, function(messages) { var messageString = messages[0].messageString; expect(messageString).to.equal(testData.message); done(); }); }); }); it('should GET messages from databases', function(done) { request(GETUri, function(err, response, body) { var messages = JSON.parse(response.body); expect(messages).to.be.a('array'); done(); }); }); });
Update generateToken() to return JSONResponse
<?php /** * ownCloud - oauth2 * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Jonathan Neugebauer * @copyright Jonathan Neugebauer 2016 */ namespace OCA\OAuth2\Controller; use OCP\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; use OCP\IRequest; use OCP\AppFramework\ApiController; class OAuthApiController extends ApiController { public function __construct($appName, IRequest $request) { parent::__construct($appName, $request); } /** * Implements the OAuth 2.0 Access Token Response. * * Is accessible by the client via the /index.php/apps/oauth2/token * * @return JSONResponse The Access Token or an empty JSON Object. * * @NoAdminRequired * @NoCSRFRequired * @PublicPage * @CORS */ public function generateToken($access_code) { if ($access_code === '123456789') { return new JSONResponse( [ 'access_token' => '2YotnFZFEjr1zCsicMWpAA', 'token_type' => 'Bearer' ] ); } return new JSONResponse(array(), Http::STATUS_BAD_REQUEST); } }
<?php /** * ownCloud - oauth2 * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Jonathan Neugebauer * @copyright Jonathan Neugebauer 2016 */ namespace OCA\OAuth2\Controller; use OCP\AppFramework\Http; use OCP\AppFramework\Http\DataResponse; use OCP\IRequest; use OCP\AppFramework\ApiController; class OAuthApiController extends ApiController { public function __construct($appName, IRequest $request) { parent::__construct($appName, $request); } /** * Implements the OAuth 2.0 Access Token Response. * * Is accessible by the client via the /index.php/apps/oauth2/token * * @NoAdminRequired * @NoCSRFRequired * @PublicPage * @CORS */ public function generateToken($access_code) { if ($access_code === '123456789') { return new DataResponse('token'); } return new DataResponse('', Http::STATUS_BAD_REQUEST); } }
Use different prop in test to prevent prop type warning
import React from 'react'; // eslint-disable-line no-unused-vars import { shallow } from 'enzyme'; import Button from '../Button'; import Icon from '../Icon'; describe('Button', () => { it('fires the onClick handler when clicked', () => { const onClick = jest.fn(); const button = shallow(<Button onClick={onClick} />); button.simulate('click'); expect(onClick).toBeCalled(); }); it('can show an Icon', () => { const withIcon = shallow(<Button icon='add' />); const withoutIcon = shallow(<Button />); expect(withIcon.find(Icon)).toBePresent(); expect(withoutIcon.find(Icon)).toBeEmpty(); }); it('can support real button attributes', () => { const button = shallow(<Button aria-pressed='false' />); expect(button.html()).toContain('aria-pressed'); }); describe('non element props', () => { it('should not pass down non element props being used elsewhere', () => { const button = shallow(<Button icon='foo' />); expect(button.html()).not.toContain('foo'); }); it('should not pass down non element props being used elsewhere', () => { const button = shallow(<Button actionText='foo' />); expect(button.html()).not.toContain('foo'); }); }); });
import React from 'react'; // eslint-disable-line no-unused-vars import { shallow } from 'enzyme'; import Button from '../Button'; import Icon from '../Icon'; describe('Button', () => { it('fires the onClick handler when clicked', () => { const onClick = jest.fn(); const button = shallow(<Button onClick={onClick} />); button.simulate('click'); expect(onClick).toBeCalled(); }); it('can show an Icon', () => { const withIcon = shallow(<Button icon='add' />); const withoutIcon = shallow(<Button />); expect(withIcon.find(Icon)).toBePresent(); expect(withoutIcon.find(Icon)).toBeEmpty(); }); it('can support real button attributes', () => { const button = shallow(<Button aria-pressed='false' />); expect(button.html()).toContain('aria-pressed'); }); describe('non element props', () => { it('should not pass down non element props being used elsewhere', () => { const button = shallow(<Button icon='foo' />); expect(button.html()).not.toContain('foo'); }); it('should not pass down non element props being used elsewhere', () => { const button = shallow(<Button isActive='foo' />); expect(button.html()).not.toContain('foo'); }); }); });
Fix bug with GH-1 for root-installations. The change made in dd0ecf4 fixed the URLs for Confluence installations in non-root paths (e.g., http://foo.example.com/confluence/*), but that broke root installations, because URI#resolve() interprets "//foo/bar" to mean that the host should become "foo". Instead of using getPath(), and appending a /-anchored RPC path, just pass a relative path to URI#resolve(). This should solve both problems.
package com.myyearbook.hudson.plugins.confluence; import java.net.URI; /** * Utility methods * * @author Joe Hansche <jhansche@myyearbook.com> */ public class Util { /** Relative path to resolve the XmlRpc endpoint URL */ private static final String XML_RPC_URL_PATH = "rpc/xmlrpc"; /** Relative path to resolve the SOAP endpoint URL */ private static final String SOAP_URL_PATH = "rpc/soap-axis/confluenceservice-v1"; /** * Convert a generic Confluence URL into the XmlRpc endpoint URL * * @param url * @return * @see #XML_RPC_URL_PATH */ public static String confluenceUrlToXmlRpcUrl(String url) { URI uri = URI.create(url); return uri.resolve(XML_RPC_URL_PATH).normalize().toString(); } /** * Convert a generic Confluence URL into the SOAP endpoint URL * * @param url * @return * @see #SOAP_URL_PATH */ public static String confluenceUrlToSoapUrl(String url) { URI uri = URI.create(url); return uri.resolve(SOAP_URL_PATH).normalize().toString(); } }
package com.myyearbook.hudson.plugins.confluence; import java.net.URI; import java.util.logging.Logger; /** * Utility methods * * @author Joe Hansche <jhansche@myyearbook.com> */ public class Util { private static final Logger LOGGER = Logger.getLogger(Util.class.getName()); /** Relative path to resolve the XmlRpc endpoint URL */ private static final String XML_RPC_URL_PATH = "/rpc/xmlrpc"; /** Relative path to resolve the SOAP endpoint URL */ private static final String SOAP_URL_PATH = "/rpc/soap-axis/confluenceservice-v1"; /** * Convert a generic Confluence URL into the XmlRpc endpoint URL * * @param url * @return * @see #XML_RPC_URL_PATH */ public static String confluenceUrlToXmlRpcUrl(String url) { URI uri = URI.create(url); return uri.resolve(uri.getPath() + XML_RPC_URL_PATH).normalize().toString(); } /** * Convert a generic Confluence URL into the SOAP endpoint URL * * @param url * @return * @see #SOAP_URL_PATH */ public static String confluenceUrlToSoapUrl(String url) { URI uri = URI.create(url); return uri.resolve(uri.getPath() + SOAP_URL_PATH).normalize().toString(); } }
Change to stacked inline for occurrences, also display location.
from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from mezzanine.core.admin import StackedDynamicInlineAdmin, DisplayableAdmin from fullcalendar.models import * class EventCategoryAdmin(admin.ModelAdmin): list_display = ('name',) class OccurrenceInline(StackedDynamicInlineAdmin): model = Occurrence extra = 1 fields = ('start_time', 'end_time', 'description', 'location') class EventAdmin(DisplayableAdmin): list_display = ('title', 'event_category') list_filter = ('event_category',) search_fields = ('title', 'description', 'content', 'keywords') fieldsets = ( (None, { "fields": [ "title", "status", ("publish_date", "expiry_date"), "event_category", "content" ] }), (_("Meta data"), { "fields": [ "_meta_title", "slug", ("description", "gen_description"), "keywords", "in_sitemap" ], "classes": ("collapse-closed",) }), ) inlines = [OccurrenceInline] admin.site.register(Event, EventAdmin) admin.site.register(EventCategory, EventCategoryAdmin)
from django.utils.translation import ugettext_lazy as _ from django.contrib import admin from mezzanine.core.admin import TabularDynamicInlineAdmin, DisplayableAdmin from fullcalendar.models import * class EventCategoryAdmin(admin.ModelAdmin): list_display = ('name',) class OccurrenceInline(TabularDynamicInlineAdmin): model = Occurrence extra = 1 fields = ('start_time', 'end_time', 'description') class EventAdmin(DisplayableAdmin): list_display = ('title', 'event_category') list_filter = ('event_category',) search_fields = ('title', 'description', 'content', 'keywords') fieldsets = ( (None, { "fields": [ "title", "status", ("publish_date", "expiry_date"), "event_category", "content" ] }), (_("Meta data"), { "fields": [ "_meta_title", "slug", ("description", "gen_description"), "keywords", "in_sitemap" ], "classes": ("collapse-closed",) }), ) inlines = [OccurrenceInline] admin.site.register(Event, EventAdmin) admin.site.register(EventCategory, EventCategoryAdmin)
Use production build of React when deploying
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const config = { entry: { 'bundle': './client/js/index.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.(ttf|eot|woff|jpe?g|svg|png)$/, loader: 'url-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { context: 'public', from: '**/*' } ]) ] }; if (process.env.NODE_ENV === 'production') { config.plugins = config.plugins.concat( new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true } }) ); } else { config.devtool = 'sourcemap'; } module.exports = config;
const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const config = { entry: { 'bundle': './client/js/index.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader' }, { test: /\.(ttf|eot|woff|jpe?g|svg|png)$/, loader: 'url-loader' } ] }, plugins: [ new CopyWebpackPlugin([ { context: 'public', from: '**/*' } ]) ] }; if (process.env.NODE_ENV === 'production') { config.plugins = config.plugins.concat( new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true } }) ); } else { config.devtool = 'sourcemap'; } module.exports = config;
Use branch name instead of username
#!/usr/bin/env python from __future__ import print_function import requests import argparse import os import subprocess import sys if 'DAALA_ROOT' not in os.environ: print("Please specify the DAALA_ROOT environment variable to use this tool.") sys.exit(1) keyfile = open('secret_key','r') key = keyfile.read().strip() daala_root = os.environ['DAALA_ROOT'] os.chdir(daala_root) branch = subprocess.check_output('git symbolic-ref -q --short HEAD',shell=True).strip() parser = argparse.ArgumentParser(description='Submit test to arewecompressedyet.com') parser.add_argument('-prefix',default=branch) args = parser.parse_args() commit = subprocess.check_output('git rev-parse HEAD',shell=True).strip() short = subprocess.check_output('git rev-parse --short HEAD',shell=True).strip() date = subprocess.check_output(['git','show','-s','--format=%ci',commit]).strip() date_short = date.split()[0]; user = args.prefix run_id = user+'-'+date_short+'-'+short print('Creating run '+run_id) r = requests.post("https://arewecompressedyet.com/submit/job", {'run_id': run_id, 'commit': commit, 'key': key}) print(r)
#!/usr/bin/env python from __future__ import print_function import requests import argparse import os import subprocess import sys if 'DAALA_ROOT' not in os.environ: print("Please specify the DAALA_ROOT environment variable to use this tool.") sys.exit(1) keyfile = open('secret_key','r') key = keyfile.read().strip() daala_root = os.environ['DAALA_ROOT'] os.chdir(daala_root) parser = argparse.ArgumentParser(description='Submit test to arewecompressedyet.com') parser.add_argument('-prefix',default=os.getlogin()) args = parser.parse_args() commit = subprocess.check_output('git rev-parse HEAD',shell=True).strip() short = subprocess.check_output('git rev-parse --short HEAD',shell=True).strip() date = subprocess.check_output(['git','show','-s','--format=%ci',commit]).strip() date_short = date.split()[0]; user = args.prefix run_id = user+'-'+date_short+'-'+short print('Creating run '+run_id) r = requests.post("https://arewecompressedyet.com/submit/job", {'run_id': run_id, 'commit': commit, 'key': key}) print(r)
Add error treatment for existing network
""" Main class from dcclient. Manages XML interaction, as well as switch and creates the actual networks """ import rpc from xml_manager.manager import ManagedXml from neutron.openstack.common import log as logger from oslo.config import cfg LOG = logger.getLogger(__name__) class Manager: def __init__(self): self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username, cfg.CONF.ml2_datacom.dm_password, cfg.CONF.ml2_datacom.dm_host, cfg.CONF.ml2_datacom.dm_method) self.xml = ManagedXml() def _update(self): self.rpc.send_xml(self.xml.xml.as_xml_text()) def create_network(self, vlan): """ Creates a new network on the switch, if it does not exist already. """ try: self.xml.addVlan(vlan) self._update() except: LOG.info("Trying to create already existing network %d:", vlan)
""" Main class from dcclient. Manages XML interaction, as well as switch and creates the actual networks """ import rpc from xml_manager.manager import ManagedXml from oslo.config import cfg class Manager: def __init__(self): self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username, cfg.CONF.ml2_datacom.dm_password, cfg.CONF.ml2_datacom.dm_host, cfg.CONF.ml2_datacom.dm_method) self.xml = ManagedXml() def _update(self): self.rpc.send_xml(self.xml.xml.as_xml_text()) def create_network(self, vlan): """ Creates a new network on the switch, if it does not exist already. """ self.xml.addVlan(vlan) self._update()
Prepend js, improving load times
<?php class Analytics_PageTool extends PageTool { /** * Google Analytics. * This simple PageTool doesn't have any functionality in the go() method. * Instead, pass the tracking code into the track() method. */ public function go($api, $dom, $template, $tool) { } /** * Injects the required JavaScript code where needed to start tracking using * Google Analytics. * * @param string $trackingCode Your Google Analytics account code, looks like * this: UA-12345678-1 */ public function track($trackingCode) { $js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js"); if($js === false) { throw new HttpError(500, "Google Analytics script failure"); } $js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js); $this->_dom["head"]->prependChild( "script", ["data-PageTool" => "Analytics"], $js ); } }#
<?php class Analytics_PageTool extends PageTool { /** * Google Analytics. * This simple PageTool doesn't have any functionality in the go() method. * Instead, pass the tracking code into the track() method. */ public function go($api, $dom, $template, $tool) { } /** * Injects the required JavaScript code where needed to start tracking using * Google Analytics. * * @param string $trackingCode Your Google Analytics account code, looks like * this: UA-12345678-1 */ public function track($trackingCode) { $js = file_get_contents(dirname(__FILE__) . "/Include/Analytics.tool.js"); if($js === false) { throw new HttpError(500, "Google Analytics script failure"); } $js = str_replace("{ANALYTICS_CODE}", $trackingCode, $js); $this->_dom["head"]->append( "script", ["data-PageTool" => "Analytics"], $js ); } }#
Fix article size in spinner
<!-- Spinner story --> <div> <div class="felix-featured-caption"><a href="<?php echo $article->getURL();?>"><?php echo $article->getTitle(); ?></a></div> <div class="felix-featured-image"> <?php if ($image = $article->getImage()) { ?> <a href="<?php echo $article->getURL();?>"> <img alt="<?php echo $image->getTitle();?>" src="<?php echo $image->getURL(1200);?>"> </a> <?php } else { ?> <a href="<?php echo $article->getURL();?>"> <img alt="" src="<?php echo IMAGE_URL.'650/300/'.DEFAULT_IMG_URI; ?>"> </a> <?php } ?> </div> <div class="felix-featured-subcaption"><?php echo $article->getTeaser();?></div> </div> <!-- End of spinner story -->
<!-- Spinner story --> <div> <div class="felix-featured-caption"><a href="<?php echo $article->getURL();?>"><?php echo $article->getTitle(); ?></a></div> <div class="felix-featured-image"> <?php if ($image = $article->getImage()) { ?> <a href="<?php echo $article->getURL();?>"> <img alt="<?php echo $image->getTitle();?>" src="<?php echo $image->getURL();?>"> </a> <?php } else { ?> <a href="<?php echo $article->getURL();?>"> <img alt="" src="<?php echo IMAGE_URL.'650/300/'.DEFAULT_IMG_URI; ?>"> </a> <?php } ?> </div> <div class="felix-featured-subcaption"><?php echo $article->getTeaser();?></div> </div> <!-- End of spinner story -->
Change fixture for image example.
import { ProseEditor, ProseEditorConfigurator, EditorSession, ProseEditorPackage, ImagePackage } from 'substance' /* Example document */ const fixture = function(tx) { let body = tx.get('body') tx.create({ id: 'p1', type: 'paragraph', content: "Insert a new image using the image tool." }) body.show('p1') tx.create({ id: 'i1', type: 'image', src: "https://pbs.twimg.com/profile_images/706616363599532032/b5z-Hw5g.jpg" }) body.show('i1') tx.create({ id: 'p2', type: 'paragraph', content: "Please note that images are not actually uploaded in this example. You would need to provide a custom file client that talks to an image store. See FileClientStub which reveals the API you have to implement." }) body.show('p2') tx.create({ id: 'i2', type: 'image', src: "https://pbs.twimg.com/profile_images/706616363599532032/b5z-Hw5g.jpg" }) body.show('i2') } /* Application */ let cfg = new ProseEditorConfigurator() cfg.import(ProseEditorPackage) cfg.import(ImagePackage) window.onload = function() { let doc = cfg.createArticle(fixture) let editorSession = new EditorSession(doc, { configurator: cfg }) ProseEditor.mount({ editorSession: editorSession }, document.body) }
import { ProseEditor, ProseEditorConfigurator, EditorSession, ProseEditorPackage, ImagePackage } from 'substance' /* Example document */ const fixture = function(tx) { let body = tx.get('body') tx.create({ id: 'p1', type: 'paragraph', content: "Insert a new image using the image tool." }) body.show('p1') tx.create({ id: 'i1', type: 'image', src: "http://substance.io/images/stencila.gif" }) body.show('i1') tx.create({ id: 'p2', type: 'paragraph', content: "Please note that images are not actually uploaded in this example. You would need to provide a custom file client that talks to an image store. See FileClientStub which reveals the API you have to implement." }) body.show('p2') } /* Application */ let cfg = new ProseEditorConfigurator() cfg.import(ProseEditorPackage) cfg.import(ImagePackage) window.onload = function() { let doc = cfg.createArticle(fixture) let editorSession = new EditorSession(doc, { configurator: cfg }) ProseEditor.mount({ editorSession: editorSession }, document.body) }
[User] Remove deprecated implementations of setDefaultOptions.
<?php namespace Clastic\SecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('clastic_security'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
<?php namespace Clastic\SecurityBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $treeBuilder->root('clastic_security'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
core: Fix ISO Domain List refresh NPE Fix ISO DomainList refresh NPE when no ISO domain is configured. Change-Id: Ied2b1490d8f66bb40f6f456d2d39bb05120e97d3 Bug-Url: https://bugzilla.redhat.com/1291202 Signed-off-by: Marek Libra <e8e92ef0eef30bdb5bafbacaf4ac8261fffd12ff@redhat.com>
package org.ovirt.engine.core.bll; import java.util.ArrayList; import java.util.List; import org.ovirt.engine.core.common.businessentities.storage.RepoImage; import org.ovirt.engine.core.common.queries.GetImagesListParametersBase; import org.ovirt.engine.core.compat.Guid; public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> { public GetImagesListQueryBase(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id. getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList()); } /** * @return The storage domain to get the images from */ protected abstract Guid getStorageDomainIdForQuery(); protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() { Guid storageDomainId = getStorageDomainIdForQuery(); if (Guid.Empty.equals(storageDomainId)) { return new ArrayList<>(); } return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList (storageDomainId, getParameters().getImageType(), getParameters().getForceRefresh()); } }
package org.ovirt.engine.core.bll; import java.util.List; import org.ovirt.engine.core.common.businessentities.storage.RepoImage; import org.ovirt.engine.core.common.queries.GetImagesListParametersBase; import org.ovirt.engine.core.compat.Guid; public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> { public GetImagesListQueryBase(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id. getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList()); } /** * @return The storage domain to get the images from */ protected abstract Guid getStorageDomainIdForQuery(); protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() { return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList (getStorageDomainIdForQuery(), getParameters().getImageType(), getParameters().getForceRefresh()); } }
Use a real model in test Fake object wasn't working anymore since this component is now loading more data.
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { setupMirage } from 'ember-cli-mirage/test-support'; module('Integration | Component | course sessions', function(hooks) { setupRenderingTest(hooks); setupMirage(hooks); test('it renders', async function(assert) { const title = '.title'; const school = this.server.create('school'); const course = this.server.create('course', { school }); const courseModel = await this.owner.lookup('service:store').find('course', course.id); this.set('course', courseModel); this.set('nothing', ()=>{}); await render(hbs`<CourseSessions @course={{course}} @sortBy="title" @setSortBy={{action nothing}} @filterBy={{null}} @setFilterBy={{action nothing}} />`); assert.dom(title).hasText('Sessions (0)'); }); });
import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | course sessions', function(hooks) { setupRenderingTest(hooks); test('it renders', async function(assert) { const title = '.title'; const course = EmberObject.create({ hasMany() { return { ids(){ return []; } }; } }); this.set('course', course); this.set('nothing', ()=>{}); await render(hbs`<CourseSessions @course={{course}} @sortBy="title" @setSortBy={{action nothing}} @filterBy={{null}} @setFilterBy={{action nothing}} />`); assert.dom(title).hasText('Sessions (0)'); }); });
Include more files inside the package.
from setuptools import setup, find_packages setup(name='DStarSniffer', version='pre-1.0', description='DStar repeater controller sniffer', url='http://github.com/elielsardanons/dstar-sniffer', author='Eliel Sardanons LU1ALY', author_email='eliel@eliel.com.ar', license='MIT', packages=find_packages(), keywords='hamradio dstar aprs icom kenwood d74', install_requires=[ 'aprslib', 'jinja2', ], include_package_data=True, package_data={'/' : ['dstar_sniffer/config/*.conf',]}, data_files=[ ('/etc/dstar_sniffer', [ 'dstar_sniffer/config/dstar_sniffer.conf', 'dstar_sniffer/config/logging.conf', 'dstar_sniffer/config/last_heard.html', ]) ], entry_points={ 'console_scripts': [ 'dstar_sniffer=dstar_sniffer.dstar_sniffer:main', ], } )
from setuptools import setup, find_packages setup(name='DStarSniffer', version='pre-1.0', description='DStar repeater controller sniffer', url='http://github.com/elielsardanons/dstar-sniffer', author='Eliel Sardanons LU1ALY', author_email='eliel@eliel.com.ar', license='MIT', packages=find_packages(), keywords='hamradio dstar aprs icom kenwood d74', install_requires=[ 'aprslib', 'jinja2', ], include_package_data=True, package_data={'/' : ['dstar_sniffer/config/*.conf',]}, data_files=[ ('/etc/dstar_sniffer', [ 'dstar_sniffer/config/dstar_sniffer.conf', 'dstar_sniffer/config/logging.conf' ]) ], entry_points={ 'console_scripts': [ 'dstar_sniffer=dstar_sniffer.dstar_sniffer:main', ], } )
Fix for timeout after finish.
'use strict'; exports.delayed = function delayed(ms, value) { return new Promise(resolve => setTimeout(() => resolve(value), ms)); }; exports.timeoutError = 'timeoutError'; /** * Waits a promise for specified timeout. * * @param {Promise} promiseToWait - promise to wait. * @param {number} ms - timeout in milliseconds * @returns {Promise} - promise which can be rejected with timeout or with error from promiseToWait. * or resolved with result of promiseToWait. */ exports.wait = function wait(promiseToWait, ms) { let rejectBecauseTimeout = true; return new Promise((resolve, reject) => { let timeoutId = null; promiseToWait.then((result) => { if (timeoutId) { clearTimeout(timeoutId); } rejectBecauseTimeout = false; resolve(result); }).catch((err) => { rejectBecauseTimeout = false; reject(err); }); timeoutId = setTimeout(() => { if (rejectBecauseTimeout) { reject(exports.timeoutError); } }, ms); }); };
'use strict'; exports.delayed = function delayed(ms, value) { return new Promise(resolve => setTimeout(() => resolve(value), ms)); }; exports.timeoutError = 'timeoutError'; /** * Waits a promise for specified timeout. * * @param {Promise} promiseToWait - promise to wait. * @param {number} ms - timeout in milliseconds * @returns {Promise} - promise which can be rejected with timeout or with error from promiseToWait. * or resolved with result of promiseToWait. */ exports.wait = function wait(promiseToWait, ms) { let rejectBecauseTimeout = true; return new Promise((resolve, reject) => { promiseToWait.then((result) => { rejectBecauseTimeout = false; resolve(result); }).catch((err) => { rejectBecauseTimeout = false; reject(err); }); setTimeout(() => { if (rejectBecauseTimeout) { reject(exports.timeoutError); } }, ms); }); };
Reformat HEADER_LENGTH calc slightly for readability
// Copyright (c) 2010 AFP Authors // This source code is released under the terms of the // MIT license. Please see the file LICENSE for license details. package afp import ( "os" "log" ) const CHAN_BUF_LEN = 64 //Constants to specify the type of a given filter const ( PIPE_SOURCE = iota PIPE_SINK PIPE_LINK ) const HEADER_LENGTH = ( 1 + // Version 1 + // Channels 1 + // SampleSize 4 + // SampleRate 4 + // FrameSize 8 // ContentLength ) type StreamHeader struct { Version int8 Channels int8 SampleSize int8 SampleRate int32 FrameSize int32 ContentLength int64 } type Context struct { HeaderSource <-chan StreamHeader HeaderSink chan<- StreamHeader Source <-chan [][]float32 Sink chan<- [][]float32 Verbose bool Err, Info *log.Logger } type Filter interface { GetType() int Init(*Context, []string) os.Error Start() Stop() os.Error }
// Copyright (c) 2010 AFP Authors // This source code is released under the terms of the // MIT license. Please see the file LICENSE for license details. package afp import ( "os" "log" ) const CHAN_BUF_LEN = 64 //Constants to specify the type of a given filter const ( PIPE_SOURCE = iota PIPE_SINK PIPE_LINK ) const HEADER_LENGTH = (1 + // Version 1 + // Channels 1 + // SampleSize 4 + // SampleRate 4 + // FrameSize 8) // ContentLength type StreamHeader struct { Version int8 Channels int8 SampleSize int8 SampleRate int32 FrameSize int32 ContentLength int64 } type Context struct { HeaderSource <-chan StreamHeader HeaderSink chan<- StreamHeader Source <-chan [][]float32 Sink chan<- [][]float32 Verbose bool Err, Info *log.Logger } type Filter interface { GetType() int Init(*Context, []string) os.Error Start() Stop() os.Error }
Use active flag instead of selected flag
/* * Copyright (c) 2014 mono * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ chrome.extension.onConnect.addListener(function(port) { port.onMessage.addListener(function(m) { switch (m.message) { case 'openInTab': chrome.tabs.create({url: m.url, active: false}); break; } }); });
/* * Copyright (c) 2014 mono * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ chrome.extension.onConnect.addListener(function(port) { port.onMessage.addListener(function(m) { switch (m.message) { case 'openInTab': chrome.tabs.create({url: m.url, selected: false}); break; } }); });
Fix encoding error preventing install While running tox the installation of icecake would succeed under Python 2.7.13 but fail under 3.5.2 with an encoding error while trying to read the long description from README.rst. py35 inst-nodeps: /icecake/.tox/dist/icecake-0.6.0.zip ERROR: invocation failed (exit code 1), logfile: /icecake/.tox/py35/log/py35-16.log ERROR: actionid: py35 msg: installpkg cmdargs: ['/icecake/.tox/py35/bin/pip', 'install', '-U', '--no-deps', '/icecake/.tox/dist/icecake-0.6.0.zip'] env: {'TERM': 'xterm', 'VIRTUAL_ENV': '/icecake/.tox/py35', 'SHLVL': '1', 'PYENV_HOOK_PATH': '/.pyenv/pyenv.d:/usr/local/etc/pyenv.d:/etc/pyenv.d:/usr/lib/pyenv/hooks:/.pyenv/plugins/pyenv-virtualenv/etc/pyenv.d', 'HOSTNAME': 'cdbe5b1470a0', 'PYENV_VERSION': '2.7.13:3.5.2', 'PYENV_DIR': '/icecake', 'PWD': '/icecake', 'PYTHONHASHSEED': '1135274721', 'PATH': '/icecake/.tox/py35/bin:/.pyenv/versions/2.7.13/bin:/.pyenv/libexec:/.pyenv/plugins/python-build/bin:/.pyenv/plugins/pyenv-virtualenv/bin:/.pyenv/shims:/.pyenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'HOME': '/root', 'PYENV_ROOT': '/.pyenv'} Processing ./.tox/dist/icecake-0.6.0.zip Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-x3boup3_-build/setup.py", line 29, in <module> long_description=open('README.rst').read(), File "/icecake/.tox/py35/lib/python3.5/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1462: ordinal not in range(128) ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-x3boup3_-build/
from setuptools import setup, find_packages from codec import open setup( # packaging information that is likely to be updated between versions name='icecake', version='0.6.0', packages=['icecake'], py_modules=['cli', 'templates', 'livejs'], entry_points=''' [console_scripts] icecake=icecake.cli:cli ''', install_requires=[ 'Click', 'Jinja2', 'Markdown', 'Pygments', 'python-dateutil', 'watchdog', 'Werkzeug', ], # pypy stuff that is not likely to change between versions url="https://github.com/cbednarski/icecake", author="Chris Bednarski", author_email="banzaimonkey@gmail.com", description="An easy and cool static site generator", license="MIT", long_description=open('README.rst', encoding="utf-8").read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ], keywords="static site generator builder icecake" )
from setuptools import setup, find_packages setup( # packaging information that is likely to be updated between versions name='icecake', version='0.6.0', packages=['icecake'], py_modules=['cli', 'templates', 'livejs'], entry_points=''' [console_scripts] icecake=icecake.cli:cli ''', install_requires=[ 'Click', 'Jinja2', 'Markdown', 'Pygments', 'python-dateutil', 'watchdog', 'Werkzeug', ], # pypy stuff that is not likely to change between versions url="https://github.com/cbednarski/icecake", author="Chris Bednarski", author_email="banzaimonkey@gmail.com", description="An easy and cool static site generator", license="MIT", long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ], keywords="static site generator builder icecake" )
Add a correct toString() method git-svn-id: 7e8def7d4256e953abb468098d8cb9b4faff0c63@5801 12255794-1b5b-4525-b599-b0510597569d
package com.arondor.common.reflection.bean.config; import java.util.Map; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Transient; import com.arondor.common.reflection.model.config.ElementConfiguration; import com.arondor.common.reflection.model.config.MapConfiguration; @Entity @DiscriminatorValue("MAP") public class MapConfigurationBean extends ElementConfigurationBean implements MapConfiguration { /** * */ private static final long serialVersionUID = 2968136864852828441L; public ElementConfigurationType getFieldConfigurationType() { return ElementConfigurationType.Map; } public MapConfigurationBean() { } // @ManyToMany(cascade = CascadeType.ALL) // , targetEntity = ElementConfigurationBean.class @Transient private Map<ElementConfiguration, ElementConfiguration> mapConfiguration; public Map<ElementConfiguration, ElementConfiguration> getMapConfiguration() { return mapConfiguration; } public void setMapConfiguration(Map<ElementConfiguration, ElementConfiguration> mapConfiguration) { this.mapConfiguration = mapConfiguration; } public String toString() { return "MapConfigurationBean[" + mapConfiguration.entrySet() + "]"; } }
package com.arondor.common.reflection.bean.config; import java.util.Map; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Transient; import com.arondor.common.reflection.model.config.ElementConfiguration; import com.arondor.common.reflection.model.config.MapConfiguration; @Entity @DiscriminatorValue("MAP") public class MapConfigurationBean extends ElementConfigurationBean implements MapConfiguration { /** * */ private static final long serialVersionUID = 2968136864852828441L; public ElementConfigurationType getFieldConfigurationType() { return ElementConfigurationType.Map; } public MapConfigurationBean() { } // @ManyToMany(cascade = CascadeType.ALL) // , targetEntity = ElementConfigurationBean.class @Transient private Map<ElementConfiguration, ElementConfiguration> mapConfiguration; public Map<ElementConfiguration, ElementConfiguration> getMapConfiguration() { return mapConfiguration; } public void setMapConfiguration(Map<ElementConfiguration, ElementConfiguration> mapConfiguration) { this.mapConfiguration = mapConfiguration; } }
Fix test data coming back as undefined.
import $ from 'jquery'; import getScrubbedData from './dataUtils'; import { testData } from '../../test/data/test-data'; import apiKey from '../../test/apiKey'; const getWeatherData = location => { if (parseInt(location, 10)) { return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${location}.json`) .then(data => { return getScrubbedData(data); }) .catch(error => console.log('catch', error)); } else { const cityStateArr = location.split(', '); return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${cityStateArr[1]}/${cityStateArr[0]}.json`) .then(data => { return getScrubbedData(data); }) .catch(error => console.log('catch', error)); } }; const getTestWeatherData = () => { return getScrubbedData(testData); }; export { getWeatherData, getTestWeatherData };
import $ from 'jquery'; import getScrubbedData from './dataUtils'; import testData from '../../test/data/test-data'; import apiKey from '../../test/apiKey'; const getWeatherData = location => { if (parseInt(location, 10)) { return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${location}.json`) .then(data => { return getScrubbedData(data); }) .catch(error => console.log('catch', error)); } else { const cityStateArr = location.split(', '); return $.get(`http://api.wunderground.com/api/${apiKey}/hourly/forecast10day/conditions/q/${cityStateArr[1]}/${cityStateArr[0]}.json`) .then(data => { return getScrubbedData(data); }) .catch(error => console.log('catch', error)); } }; const getTestWeatherData = () => { return getScrubbedData(testData); }; export { getWeatherData, getTestWeatherData };
Remove run method (useless) in Base class
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
"""The base command.""" import ConfigParser import os import putiopy class Base(object): """A base command.""" def __init__(self, options): self.options = options def run(self): raise NotImplementedError( 'You must implement the run() method yourself!') class BaseClient(Base): """A base client command.""" def __init__(self, options): # update options from config file config = ConfigParser.RawConfigParser() config.read(os.path.expanduser(options['--config'])) for section in config.sections(): for key, value in config.items(section): key = section + '.' + key options[key] = value Base.__init__(self, options) # define putio client self.client = putiopy.Client(options['Settings.oauth-token']) def run(self): raise NotImplementedError( 'You must implement the run() method yourself!')
Test for behaviour when badge does not exist
<?php namespace UoMCS\OpenBadges\Backend; class BadgeTest extends DatabaseTestCase { const BADGE_EXISTS_ID = 1; const BADGE_DOES_NOT_EXIST_ID = 99999; public function testBadgeExistsDB() { $badge = Badge::get(self::BADGE_EXISTS_ID); $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge'); $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']); } public function testBadgeDoesNotExistDB() { $badge = Badge::get(self::BADGE_DOES_NOT_EXIST_ID); $this->assertNull($badge); } public function testBadgesUrl() { $url = WEB_SERVER_BASE_URL . '/badges'; $client = new \Zend\Http\Client(); $client->setUri($url); $response = $client->send(); $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code'); $body = $response->getBody(); $json_body = json_decode($body, true); $this->assertNotNull($json_body, 'Body is not valid JSON'); } }
<?php namespace UoMCS\OpenBadges\Backend; class BadgeTest extends DatabaseTestCase { const BADGE_EXISTS_ID = 1; const BADGE_DOES_NOT_EXIST_ID = 99999; public function testBadgeExistsDB() { $badge = Badge::get(self::BADGE_EXISTS_ID); $this->assertInstanceOf('UoMCS\\OpenBadges\\Backend\\Badge', $badge, 'Could not fetch badge'); $this->assertEquals(self::BADGE_EXISTS_ID, $badge->data['id']); } public function testBadgesUrl() { $url = WEB_SERVER_BASE_URL . '/badges'; $client = new \Zend\Http\Client(); $client->setUri($url); $response = $client->send(); $this->assertTrue($response->isOk(), 'Accessing /badges did not return 2xx code'); $body = $response->getBody(); $json_body = json_decode($body, true); $this->assertNotNull($json_body, 'Body is not valid JSON'); } }
Disable caching so CSRF tokens are not cached.
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True) plugin_pool.register_plugin(FormDesignerPlugin)
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True) plugin_pool.register_plugin(FormDesignerPlugin)
Add srcId to db def
package main const ( setNames = "SET NAMES utf8" setLocPrefix = "SET @localPrefix='+48'" outboxTable = "SMSd_Outbox" recipientsTable = "SMSd_Recipients" inboxTable = "SMSd_Inbox" ) const createOutbox = `CREATE TABLE IF NOT EXISTS ` + outboxTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, time datetime NOT NULL, src varchar(16) NOT NULL, report boolean NOT NULL, del boolean NOT NULL, body text NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8` const createRecipients = `CREATE TABLE IF NOT EXISTS ` + recipientsTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, msgId int unsigned NOT NULL, number varchar(16) NOT NULL, dstId int unsigned NOT NULL, sent datetime NOT NULL, report datetime NOT NULL, PRIMARY KEY (id), FOREIGN KEY (msgId) REFERENCES ` + outboxTable + `(id) ON DELETE CASCADE, KEY dstId (dstId) ) ENGINE=InnoDB DEFAULT CHARSET=utf8` const createInbox = `CREATE TABLE IF NOT EXISTS ` + inboxTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, time datetime NOT NULL, number varchar(16) NOT NULL, srcId int unsigned NOT NULL, body text NOT NULL, PRIMARY KEY (id), KEY srcId (srcId) ) ENGINE=MyISAM DEFAULT CHARSET=utf8`
package main const ( setNames = "SET NAMES utf8" setLocPrefix = "SET @localPrefix='+48'" outboxTable = "SMSd_Outbox" recipientsTable = "SMSd_Recipients" inboxTable = "SMSd_Inbox" ) const createOutbox = `CREATE TABLE IF NOT EXISTS ` + outboxTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, time datetime NOT NULL, src varchar(16) NOT NULL, report boolean NOT NULL, del boolean NOT NULL, body text NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8` const createRecipients = `CREATE TABLE IF NOT EXISTS ` + recipientsTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, msgId int unsigned NOT NULL, number varchar(16) NOT NULL, dstId int unsigned NOT NULL, sent datetime NOT NULL, report datetime NOT NULL, PRIMARY KEY (id), FOREIGN KEY (msgId) REFERENCES ` + outboxTable + `(id) ON DELETE CASCADE, KEY dstId (dstId) ) ENGINE=InnoDB DEFAULT CHARSET=utf8` const createInbox = `CREATE TABLE IF NOT EXISTS ` + inboxTable + ` ( id int unsigned NOT NULL AUTO_INCREMENT, time datetime NOT NULL, number varchar(16) NOT NULL, body text NOT NULL, PRIMARY KEY (id) ) ENGINE=MyISAM DEFAULT CHARSET=utf8`
Update constant varriables to using const
const mongoose = require('mongoose') const userSchema = new mongoose.Schema({ id: { type: String, index: { unique: true } }, twitter_id: String, twitter_credentials: mongoose.Schema.Types.Mixed, auth0_id: String, login_tokens: [ String ], profile_image_url: String, data: mongoose.Schema.Types.Mixed, created_at: Date, updated_at: Date, last_street_id: Number }) userSchema.pre('save', function (next) { const now = new Date() this.updated_at = now this.created_at = this.created_at || now next() }) userSchema.methods.asJson = function (options, cb) { options = options || {} let json = { id: this.id } if (options.auth) { json.data = this.data json.createdAt = this.created_at json.updatedAt = this.updated_at } cb(null, json) } module.exports = mongoose.model('User', userSchema)
const mongoose = require('mongoose') const userSchema = new mongoose.Schema({ id: { type: String, index: { unique: true } }, twitter_id: String, twitter_credentials: mongoose.Schema.Types.Mixed, auth0_id: String, login_tokens: [ String ], profile_image_url: String, data: mongoose.Schema.Types.Mixed, created_at: Date, updated_at: Date, last_street_id: Number }) userSchema.pre('save', function (next) { let now = new Date() this.updated_at = now this.created_at = this.created_at || now next() }) userSchema.methods.asJson = function (options, cb) { options = options || {} let json = { id: this.id } if (options.auth) { json.data = this.data json.createdAt = this.created_at json.updatedAt = this.updated_at } cb(null, json) } module.exports = mongoose.model('User', userSchema)
Hide components if user is logged
import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; // =========== Components =========== import App from '../components/app'; import NotFound from '../components/public-pages/not-found'; // Products import Products from '../components/products/'; // Layout import Header from '../components/navigation/header'; import Footer from '../components/navigation/footer'; // authentication import Register from '../components/auth/register'; import SignIn from '../components/auth/sign-in'; import Profile from '../components/auth/profile'; // Hide order component import RequireAuth from '../components/auth/hoc/require-auth'; import HideAuth from '../components/auth/hoc/hide-auth'; export default ( <Router> <div> <Header /> <Switch> <Route exact path="/" component={App} /> <Route path="/register" component={HideAuth(Register)} /> <Route path="/sign_in" component={HideAuth(SignIn)} /> <Route path="/profile" component={RequireAuth(Profile)} /> <Route path="/products" component={HideAuth(Products)} /> <Route component={NotFound} /> </Switch> <footer /> </div> </Router> )
import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; // =========== Components =========== import App from '../components/app'; import NotFound from '../components/public-pages/not-found'; // Layout import Header from '../components/navigation/header'; import Footer from '../components/navigation/footer'; // authentication import Register from '../components/auth/register'; import SignIn from '../components/auth/sign-in'; import Profile from '../components/auth/profile'; export default ( <Router> <div> <Header /> <Switch> <Route exact path="/" component={App} /> <Route path="/register" component={Register} /> <Route path="/sign_in" component={SignIn} /> <Route path="/profile" component={Profile} /> <Route component={NotFound} /> </Switch> <footer /> </div> </Router> )
Fix for the burea page on Android 4.1
/* ========================================================================== Assign Code copied from the following with moderate modifications : - https://github.com/maslennikov/shallow-extend Copyright (c) 2014 Alexey Maslennikov ========================================================================== */ 'use strict'; /** * @param {Object} object - JavaScript object. * @returns {boolean} True if object is plain Javascript object. */ function _isPlainObject( object ) { return Object.prototype.toString.call( object ) === '[object Object]'; } /** * Copies properties of all sources to the destination object overriding its own * existing properties. When assigning from multiple sources, fields of every * next source will override same named fields of previous sources. * * @param {Object} destination object. * @returns {Object} assigned destination object. */ function assign( destination ) { destination = destination || {}; var hasOwnProp; for ( var i = 1; i < arguments.length; i++ ) { var source = arguments[i] || {}; hasOwnProp = Object.hasOwnProperty.bind( source ); for ( var key in source ) { if ( hasOwnProp( key ) ) { var value = source[key]; if ( _isPlainObject( value ) ) { assign( destination[key] = {}, value ); } else { destination[key] = source[key]; } } } } return destination; } // Expose public methods. module.exports = { assign: assign };
/* ========================================================================== Assign Code copied from the following with moderate modifications : - https://github.com/maslennikov/shallow-extend Copyright (c) 2014 Alexey Maslennikov ========================================================================== */ 'use strict'; /** * @param {Object} object - JavaScript object. * @returns {boolean} True if object is plain Javascript object. */ function _isPlainObject( object ) { return Object.prototype.toString.call( object ) === '[object Object]'; } /** * Copies properties of all sources to the destination object overriding its own * existing properties. When assigning from multiple sources, fields of every * next source will override same named fields of previous sources. * * @param {Object} destination object. * @returns {Object} assigned destination object. */ function assign( destination ) { destination = destination || {}; for ( var i = 1; i < arguments.length; i++ ) { var source = arguments[i] || {}; for ( var key in source ) { if ( source.hasOwnProperty( key ) ) { var value = source[key]; if ( _isPlainObject( value ) ) { assign( destination[key] = {}, value ); } else { destination[key] = source[key]; } } } } return destination; } // Expose public methods. module.exports = { assign: assign };
Use index instead of shifting data
window.AdventOfCode.Day8 = ( input ) => { input = input.split( ' ' ).map( x => +x ); let part1 = 0; let index = 0; const process = () => { const childrenSize = input[ index++ ]; const metadataSize = input[ index++ ]; let values = []; let value = 0; for( let i = childrenSize; i > 0; i-- ) { values.push( process() ); } const metadata = input.slice( index, index += metadataSize ); const metadataSum = metadata.reduce( ( a, b ) => a + b, 0 ); part1 += metadataSum; if( childrenSize > 0 ) { for( const i of metadata ) { value += values[ i - 1 ] || 0; } } else { value = metadataSum; } return value; }; const part2 = process(); return [ part1, part2 ]; };
window.AdventOfCode.Day8 = ( input ) => { input = input.split( ' ' ).map( x => +x ); let part1 = 0; const process = () => { const childrenSize = input.shift(); const metadataSize = input.shift(); let values = []; let value = 0; for( let i = childrenSize; i > 0; i-- ) { values.push( process() ); } const metadata = input.slice( 0, metadataSize ); const metadataSum = metadata.reduce( ( a, b ) => a + b, 0 ); part1 += metadataSum; if( childrenSize > 0 ) { for( const i of metadata ) { value += values[ i - 1 ] || 0; } } else { value = metadataSum; } input = input.slice( metadataSize ); return value; }; const part2 = process(); return [ part1, part2 ]; };
Fix https origin in CORS.
import express from 'express'; import leagueTips from 'league-tooltips'; import runTask from './cronTask'; import taskGenerator from './cronTasks/generator'; import config from './config'; import routes from './routes'; // ==== Server ==== const app = express(); app.use(leagueTips(config.key.riot, 'euw', { url: '/tooltips', fileName: 'league-tips.min.js', protocol: 'https', cors: { origin: 'https://lol-item-sets-generator.org/', methods: 'GET', headers: 'Content-Type' } })); app.use('/sprites', routes.sprites); app.use('/tooltips', routes.tooltips); app.use('/', routes.index); app.listen(config.port, () => { console.log('[SERVER] Listening on port ' + config.port); }); // ==== Generator ==== const version = require('../package.json').version; console.log(`[GENERATOR] Generator version : ${version}.`); runTask(taskGenerator, config.cron);
import express from 'express'; import leagueTips from 'league-tooltips'; import runTask from './cronTask'; import taskGenerator from './cronTasks/generator'; import config from './config'; import routes from './routes'; // ==== Server ==== const app = express(); app.use(leagueTips(config.key.riot, 'euw', { url: '/tooltips', fileName: 'league-tips.min.js', protocol: 'https', cors: { origin: 'lol-item-sets-generator.org', methods: 'GET', headers: 'Content-Type' } })); app.use('/sprites', routes.sprites); app.use('/tooltips', routes.tooltips); app.use('/', routes.index); app.listen(config.port, () => { console.log('[SERVER] Listening on port ' + config.port); }); // ==== Generator ==== const version = require('../package.json').version; console.log(`[GENERATOR] Generator version : ${version}.`); runTask(taskGenerator, config.cron);
feat(a11y): Add aria key-value pairs so that a bunch of magic strings can be removed.
(function rocketbelt(window, document) { window.rb = window.rb || {}; window.rb.getShortId = function getShortId() { // Break the id into 2 parts to provide enough bits to the random number. // This should be unique up to 1:2.2 bn. var firstPart = (Math.random() * 46656) | 0; var secondPart = (Math.random() * 46656) | 0; firstPart = ('000' + firstPart.toString(36)).slice(-3); secondPart = ('000' + secondPart.toString(36)).slice(-3); return firstPart + secondPart; }; window.rb.onDocumentReady = function onDocumentReady(fn) { if ( document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll) ) { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }; window.rb.aria = { 'current': 'aria-current', 'describedby': 'aria-describedby', 'disabled': 'aria-disabled', 'expanded': 'aria-expanded', 'haspopup': 'aria-haspopup', 'hidden': 'aria-hidden', 'invalid': 'aria-invalid', 'label': 'aria-label', 'labelledby': 'aria-labelledby', 'live': 'aria-live', 'role': 'role' }; })(window, document);
(function rocketbelt(window, document) { window.rb = window.rb || {}; window.rb.getShortId = function getShortId() { // Break the id into 2 parts to provide enough bits to the random number. // This should be unique up to 1:2.2 bn. var firstPart = (Math.random() * 46656) | 0; var secondPart = (Math.random() * 46656) | 0; firstPart = ('000' + firstPart.toString(36)).slice(-3); secondPart = ('000' + secondPart.toString(36)).slice(-3); return firstPart + secondPart; }; window.rb.onDocumentReady = function onDocumentReady(fn) { if ( document.readyState === 'complete' || (document.readyState !== 'loading' && !document.documentElement.doScroll) ) { fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }; })(window, document);
Put download stats behind !npmo feature flag
var P = require('bluebird'); var feature = require('../lib/feature-flags.js'); var MINUTE = 60; // seconds var MODIFIED_TTL = 1 * MINUTE; var DEPENDENTS_TTL = 30 * MINUTE; module.exports = function(request, reply) { var Package = require("../models/package").new(request); var Download = require("../models/download").new({ request: request, cache: require("../lib/cache") }); var context = { explicit: require("npm-explicit-installs") }; var actions = {}; actions.modified = Package.list({ sort: "modified", count: 12 }, MODIFIED_TTL); actions.dependents = Package.list({ sort: "dependents", count: 12 }, DEPENDENTS_TTL); if (!feature('npmo')) { actions.downloads = Download.getAll(); actions.totalPackages = Package.count().catch(function(err) { request.logger.error(err); return null; }); } P.props(actions).then(function(results) { context.modified = results.modified; context.dependents = results.dependents; context.downloads = results.downloads; context.totalPackages = results.totalPackages; reply.view('homepage', context); }).catch(function(err) { request.logger.error(err); reply.view('errors/internal', err); }); };
var P = require('bluebird'); var MINUTE = 60; // seconds var MODIFIED_TTL = 1 * MINUTE; var DEPENDENTS_TTL = 30 * MINUTE; module.exports = function(request, reply) { var Package = require("../models/package").new(request); var Download = require("../models/download").new({ request: request, cache: require("../lib/cache") }); var context = { explicit: require("npm-explicit-installs") }; var actions = { modified: Package.list({ sort: "modified", count: 12 }, MODIFIED_TTL), dependents: Package.list({ sort: "dependents", count: 12 }, DEPENDENTS_TTL), downloads: Download.getAll(), totalPackages: Package.count().catch(function(err) { request.logger.error(err); return null; }), }; P.props(actions).then(function(results) { context.modified = results.modified; context.dependents = results.dependents; context.downloads = results.downloads; context.totalPackages = results.totalPackages; reply.view('homepage', context); }).catch(function(err) { request.logger.error(err); reply.view('errors/internal', err); }); };
Fix RSS feed some more.
from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from extensions.models import Extension class LatestExtensionsFeed(Feed): title = "Latest extensions in GNOME Shell Extensions" link = "/" description = "The latest extensions in GNOME Shell Extensions" def items(self): return Extension.objects.visible().order_by('-pk')[:10] def item_title(self, item): return item.name def item_description(self, item): return item.description def item_link(self, item): return reverse('extensions-detail', kwargs=dict(pk=item.pk, slug=item.slug))
from django.contrib.syndication.views import Feed from django.core.urlresolvers import reverse from extensions.models import Extension class LatestExtensionsFeed(Feed): title = "Latest extensions in GNOME Shell Extensions" link = "/" description = "The latest extensions in GNOME Shell Extensions" def items(self): return Extension.objects.visible().order_by('pk')[-10:] def item_title(self, item): return item.name def item_description(self, item): return item.description def item_link(self, item): return reverse('extensions-detail', kwargs=dict(pk=item.pk, slug=item.slug))
Drop func annotations for the sake of Python 3.5
"""Version tools set.""" import os from setuptools_scm import get_version def get_version_from_scm_tag( *, root='.', relative_to=None, local_scheme='node-and-date', ): """Retrieve the version from SCM tag in Git or Hg.""" try: return get_version( root=root, relative_to=relative_to, local_scheme=local_scheme, ) except LookupError: return 'unknown' def cut_local_version_on_upload(version): """Return empty local version if uploading to PyPI.""" is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true' if is_pypi_upload: return '' import setuptools_scm.version # only available during setup time return setuptools_scm.version.get_local_node_and_date(version) def get_self_version(): """Calculate the version of the dist itself.""" return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
"""Version tools set.""" import os from setuptools_scm import get_version def get_version_from_scm_tag( *, root='.', relative_to=None, local_scheme='node-and-date', ) -> str: """Retrieve the version from SCM tag in Git or Hg.""" try: return get_version( root=root, relative_to=relative_to, local_scheme=local_scheme, ) except LookupError: return 'unknown' def cut_local_version_on_upload(version): """Return empty local version if uploading to PyPI.""" is_pypi_upload = os.getenv('PYPI_UPLOAD') == 'true' if is_pypi_upload: return '' import setuptools_scm.version # only available during setup time return setuptools_scm.version.get_local_node_and_date(version) def get_self_version(): """Calculate the version of the dist itself.""" return get_version_from_scm_tag(local_scheme=cut_local_version_on_upload)
Add responsive sharer to resources
<?php /* * Classic theme * Author: Jonathan Kim * Date: 30/12/2011 */ use FelixOnline\Core; if(!defined('THEME_DIRECTORY')) define('THEME_DIRECTORY', dirname(__FILE__)); if(!defined('THEME_NAME')) define('THEME_NAME', '2014'); if(!defined('THEME_URL')) define('THEME_URL', STANDARD_URL.'themes/'.THEME_NAME.'/'); global $hooks; /* * Load in theme specific functions */ require_once(THEME_DIRECTORY.'/core/functions.php'); /* * Set default site wide resources */ $this->resources = new Core\ResourceManager( /* CSS files */ array('foundation.css', 'felix.css', '../slick/slick.css', 'rrssb.css'), /* JS files */ array('vendor/jquery.js', 'foundation.min.js', 'foundation/foundation.reveal.js', '../slick/slick.js', 'script.js', 'rrssb.min.js') ); ?>
<?php /* * Classic theme * Author: Jonathan Kim * Date: 30/12/2011 */ use FelixOnline\Core; if(!defined('THEME_DIRECTORY')) define('THEME_DIRECTORY', dirname(__FILE__)); if(!defined('THEME_NAME')) define('THEME_NAME', '2014'); if(!defined('THEME_URL')) define('THEME_URL', STANDARD_URL.'themes/'.THEME_NAME.'/'); global $hooks; /* * Load in theme specific functions */ require_once(THEME_DIRECTORY.'/core/functions.php'); /* * Set default site wide resources */ $this->resources = new Core\ResourceManager( /* CSS files */ array('foundation.css', 'felix.css', '../slick/slick.css'), /* JS files */ array('vendor/jquery.js', 'foundation.min.js', 'foundation/foundation.reveal.js', '../slick/slick.js', 'script.js') ); ?>
Update methods to reflect platform information This updates the implementations of the os.type() and os.platform() methods to reflect more accurate system/platform information. os.type() has been updated to simply return 'React Native' os.platform() has been updated to return the current platform, either 'android', 'ios', or whatever else might be returned by Platform.OS
// original: https://github.com/CoderPuppy/os-browserify var { DeviceEventEmitter, NativeModules, Platform } = require('react-native'); var RNOS = NativeModules.RNOS; // update the osInfo var osInfo = { } DeviceEventEmitter.addListener('rn-os-info', function (info) { osInfo = info; }); exports.endianness = function () { return 'LE' }; exports.hostname = function () { if (typeof location !== 'undefined') { return location.hostname } else return ''; }; exports.loadavg = function () { return [] }; exports.uptime = function () { return 0 }; exports.freemem = function () { return Number.MAX_VALUE; }; exports.totalmem = function () { return Number.MAX_VALUE; }; exports.cpus = function () { return [] }; exports.type = function () { return 'React Native' }; exports.release = function () { if (typeof navigator !== 'undefined') { return navigator.appVersion; } return ''; }; exports.networkInterfaces = exports.getNetworkInterfaces = function () { return osInfo.networkInterfaces || RNOS.networkInterfaces }; exports.arch = function () { return 'javascript' }; exports.platform = function () { return Platform.OS }; exports.tmpdir = exports.tmpDir = function () { return '/tmp'; }; exports.EOL = '\n';
// original: https://github.com/CoderPuppy/os-browserify var { DeviceEventEmitter, NativeModules } = require('react-native'); var RNOS = NativeModules.RNOS; // update the osInfo var osInfo = { } DeviceEventEmitter.addListener('rn-os-info', function (info) { osInfo = info; }); exports.endianness = function () { return 'LE' }; exports.hostname = function () { if (typeof location !== 'undefined') { return location.hostname } else return ''; }; exports.loadavg = function () { return [] }; exports.uptime = function () { return 0 }; exports.freemem = function () { return Number.MAX_VALUE; }; exports.totalmem = function () { return Number.MAX_VALUE; }; exports.cpus = function () { return [] }; exports.type = function () { return 'Browser' }; exports.release = function () { if (typeof navigator !== 'undefined') { return navigator.appVersion; } return ''; }; exports.networkInterfaces = exports.getNetworkInterfaces = function () { return osInfo.networkInterfaces || RNOS.networkInterfaces }; exports.arch = function () { return 'javascript' }; exports.platform = function () { return 'browser' }; exports.tmpdir = exports.tmpDir = function () { return '/tmp'; }; exports.EOL = '\n';
Fix for done action bug
# coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import desiringgod_utils from user import user_actions PROMPT = "Here are today's articles from desiringgod.org!\nTap on any one to get the article!" class DGDevoAction(action_classes.Action): def identifier(self): return "/desiringgod" def name(self): return "Desiring God Articles" def description(self): return "Articles from DesiringGod.org" def resolve(self, userObj, msg): refs = desiringgod_utils.get_desiringgod() if refs is not None: refs.append({"title":user_actions.UserDoneAction().name(), "link":""}) options = [telegram_utils.make_button(text=ref["title"], fields={"url":ref["link"]}) for ref in refs] telegram_utils.send_url_keyboard(PROMPT, userObj.get_uid(), options, 1) return True def get(): return [DGDevoAction()]
# coding=utf8 # Local modules from common import debug from common.action import action_classes from common.telegram import telegram_utils from dailydevo import desiringgod_utils from user import user_actions PROMPT = "Here are today's articles from desiringgod.org!\nTap on any one to get the article!" class DGDevoAction(action_classes.Action): def identifier(self): return "/desiringgod" def name(self): return "Desiring God Articles" def description(self): return "Articles from DesiringGod.org" def resolve(self, userObj, msg): refs = desiringgod_utils.get_desiringgod() if refs is not None: done = {"title":user_actions.UserDoneAction.name(), "link":""} debug.log("Created done") refs.append(done) debug.log("Converting to buttons") options = [telegram_utils.make_button(text=ref["title"], fields={"url":ref["link"]}) for ref in refs] debug.log("Got the buttons: " + options) telegram_utils.send_url_keyboard(PROMPT, userObj.get_uid(), options, 1) return True def get(): return [DGDevoAction()]
Add default parameter limits to distribution to be overridden by implementing classes.
<?php namespace MathPHP\Probability\Distribution; use MathPHP\Functions\Support; abstract class Distribution { // Overridden by implementing classes const PARAMETER_LIMITS = []; /** * Constructor * * @param number ...$params */ public function __construct(...$params) { $new_params = static::PARAMETER_LIMITS; $i = 0; foreach ($new_params as $key => $value) { $this->$key = $params[$i]; $new_params[$key] = $params[$i]; $i++; } Support::checkLimits(static::PARAMETER_LIMITS, $new_params); } }
<?php namespace MathPHP\Probability\Distribution; use MathPHP\Functions\Support; abstract class Distribution { /** * Constructor * * @param number ...$params */ public function __construct(...$params) { $new_params = static::PARAMETER_LIMITS; $i = 0; foreach ($new_params as $key => $value) { $this->$key = $params[$i]; $new_params[$key] = $params[$i]; $i++; } Support::checkLimits(static::PARAMETER_LIMITS, $new_params); } }
Add quieter handlers for repl
var LastFmNode = require('./lib/lastfm').LastFmNode, repl = require('repl'), config = require('./config'), _ = require('underscore'); var echoHandler = function() { _(arguments).each(function(arg) { console.log(arg); }); }; var errorHandler = function(error) { console.log('Error: ' + error.message); }; var quietHandler = function() { }; var _echoHandlers = { error: errorHandler, success: echoHandler, lastPlayed: echoHandler, nowPlaying: echoHandler, scrobbled: echoHandler, stoppedPlaying: echoHandler }; var _quietHandlers = { error: errorHandler, success: quietHandler, lastPlayed: quietHandler, nowPlaying: quietHandler, scrobbled: quietHandler, stoppedPlaying: quietHandler } var lastfm = new LastFmNode({ api_key: config.api_key, secret: config.secret }); var context = repl.start().context; context.lastfm = lastfm; context._echoHandlers = _echoHandlers; context._quietHandlers = _quietHandlers;
var LastFmNode = require('./lib/lastfm').LastFmNode, repl = require('repl'), config = require('./config'), _ = require('underscore'); var echoHandler = function() { _(arguments).each(function(arg) { console.log(arg); }); }; var errorHandler = function(error) { console.log('Error: ' + error.message); }; var _echoHandlers = { error: errorHandler, success: echoHandler, lastPlayed: echoHandler, nowPlaying: echoHandler, scrobbled: echoHandler, stoppedPlaying: echoHandler }; var lastfm = new LastFmNode({ api_key: config.api_key, secret: config.secret }); var context = repl.start().context; context.lastfm = lastfm; context._echoHandlers = _echoHandlers;
Set docker log encoding to utf-8
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs, encoding="utf-8") stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
# stdlib import os from pathlib import Path from pathlib import PosixPath import subprocess # Make a log directory log_path = Path("logs") log_path.mkdir(exist_ok=True) # Get the github job name and create a directory for it job_name = os.getenv("GITHUB_JOB") job_path: PosixPath = log_path / job_name job_path.mkdir(exist_ok=True) # Get all the containers running (per job) containers = ( subprocess.check_output("docker ps --format '{{.Names}}'", shell=True) .decode("utf-8") .split() ) # Loop through the container ids and create a log file for each in the job directory for container in containers: # Get the container name container_name = container.replace("'", "") # Get the container logs container_logs = subprocess.check_output( "docker logs " + container_name, shell=True, stderr=subprocess.STDOUT ).decode("utf-8") path = job_path / container_name path.write_text(container_logs) stored_files = list(job_path.iterdir()) for file in stored_files: print(file) print("============Log export completed for job: ", job_name)
Add links to source code in documentation
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.viewcode", ] # The master toctree document. master_doc = 'index' # General information about the project. project = 'Mongo-Thingy' copyright = 'numberly' author = 'numberly' # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", ] # The master toctree document. master_doc = 'index' # General information about the project. project = 'Mongo-Thingy' copyright = 'numberly' author = 'numberly' # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster'
Change textarea vaule t output raw data
@php //php here @endphp <div class="note"> <div class="smart-editor"> <p> <input type="text" name="notes_title" class="col-fluid {{ $errors->first('notes_title', 'error') }}" placeholder="What the title of this note?" value="{{ old('notes_title', (isset($note->notes_title) ? $note->notes_title : '')) }}"> </p> <p class="smart-edit"> <textarea name="{{ $notes['selector'] or "notes_content" }}" id="adv-notes" class="notes">{!! old('notes_content', (isset($note->notes_content) ? $note->notes_content : '')) !!}</textarea> </p> <button class="btn btn-lg btn-primary" type="submit">Save Note</button> </div> </div> @push('scripts') @include('notes::partials.smart-notes-js') @endpush
@php //php here @endphp <div class="note"> <div class="smart-editor"> <p> <input name="notes_title" class="col-fluid {{ $errors->first('notes_title', 'error') }}" placeholder="Add the title of the Note here.." value="{{ old('notes_title', (isset($note->notes_title) ? $note->notes_title : '')) }}"> </p> <p class="smart-edit"> <textarea name="{{ $notes['selector'] or "notes_content" }}" id="adv-notes" class="notes">{{ old('notes_content', (isset($note->notes_content) ? $note->notes_content : '')) }}</textarea> </p> <button class="btn btn-lg btn-primary" type="submit">Save Note</button> </div> </div> @push('scripts') @include('notes::partials.smart-notes-js') @endpush
Change ICON to new loader format
define(['mac/palette2'], function(palette) { 'use strict'; return function(item) { return item.getBytes().then(function(bytes) { if (bytes.length !== 128 && bytes.length !== 256) { return Promise.reject('ICON resource expected to be 128 bytes, got ' + bytes.length); } item.withPixels(32, 32, function(pixelData) { var mask = bytes.length === 256 ? bytes.subarray(128, 256) : null; for (var ibyte = 0; ibyte < 128; ibyte++) { var databyte = bytes[ibyte], maskbyte = mask ? mask[ibyte] : 255; for (var ibit = 0; ibit < 8; ibit++) { var imask = 0x80 >> ibit; if (maskbyte & imask) { pixelData.set(palette[databyte & imask ? 1 : 0], (ibyte*8 + ibit) * 4); } } } }); }); }; });
define(['mac/palette2'], function(palette) { 'use strict'; return function(resource) { if (resource.data.length !== 128 && resource.data.length !== 256) { console.error('ICON resource expected to be 128 bytes, got ' + resource.data.length); return; } var img = document.createElement('CANVAS'); img.width = 32; img.height = 32; var ctx = img.getContext('2d'); var pix = ctx.createImageData(32, 32); var mask = resource.data.length === 256 ? resource.data.subarray(128, 256) : null; for (var ibyte = 0; ibyte < 128; ibyte++) { var databyte = resource.data[ibyte], maskbyte = mask ? mask[ibyte] : 255; for (var ibit = 0; ibit < 8; ibit++) { var imask = 0x80 >> ibit; if (maskbyte & imask) { pix.data.set(palette[databyte & imask ? 1 : 0], (ibyte*8 + ibit) * 4); } } } ctx.putImageData(pix, 0, 0); resource.image = {url: img.toDataURL(), width:32, height:32}; }; });
Update test to use new function.
const test = require('tap').test; const path = require('path'); const VirtualMachine = require('../../src/index'); const sb3 = require('../../src/serialization/sb3'); const readFileToBuffer = require('../fixtures/readProjectFile').readFileToBuffer; const projectPath = path.resolve(__dirname, '../fixtures/clone-cleanup.sb2'); test('serialize', t => { const vm = new VirtualMachine(); vm.loadProject(readFileToBuffer(projectPath)) .then(() => { const result = sb3.serialize(vm.runtime); // @todo Analyze t.type(JSON.stringify(result), 'string'); t.end(); }); }); test('deserialize', t => { const vm = new VirtualMachine(); sb3.deserialize('', vm.runtime).then(({targets}) => { // @todo Analyze t.type(targets, 'object'); t.end(); }); });
const test = require('tap').test; const path = require('path'); const VirtualMachine = require('../../src/index'); const sb3 = require('../../src/serialization/sb3'); const extract = require('../fixtures/extract'); const projectPath = path.resolve(__dirname, '../fixtures/clone-cleanup.sb2'); test('serialize', t => { const vm = new VirtualMachine(); vm.loadProject(extract(projectPath)) .then(() => { const result = sb3.serialize(vm.runtime); // @todo Analyze t.type(JSON.stringify(result), 'string'); t.end(); }); }); test('deserialize', t => { const vm = new VirtualMachine(); sb3.deserialize('', vm.runtime).then(({targets}) => { // @todo Analyze t.type(targets, 'object'); t.end(); }); });
Call main rather than start
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from time import sleep import unittest import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisTests(unittest.TestCase): app = cairis.bin.cairisd.main(['-d', '--unit-test']) sleep(1)
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from time import sleep import unittest import cairis.bin.cairisd __author__ = 'Robin Quetin' class CairisTests(unittest.TestCase): app = cairis.bin.cairisd.start(['-d', '--unit-test']) sleep(1)
Convert widget specs to jasmine 2.x syntax
define([ "public/assets/javascripts/lib/widgets/travel_insurance" ], function(TravelInsurance) { "use strict"; describe("TravelInsurance", function() { define("wnmock", function() { return {}; }); describe("pulling in the World Nomad widget", function() { var widget; beforeEach(function(done) { widget = new TravelInsurance({ path: "wnmock", callback: done }); widget.render() }); it("has loaded", function() { expect(widget.$el).toBeDefined(); }); }); describe("should return a promise when rendering", function() { var widget; beforeEach(function(done) { widget = new TravelInsurance({ path: "wnmock" }); widget.render().then(function() { done(); }); }); it("has resolved", function() { expect(widget.$el).toBeDefined(); }); }); }); });
require([ "public/assets/javascripts/lib/widgets/travel_insurance" ], function(TravelInsurance) { "use strict"; describe("TravelInsurance", function() { define("wnmock", function() { return {}; }); it("pulls in the world nomad widget", function() { var ready = false; runs(function() { var widget = new TravelInsurance({ path: "wnmock", callback: function() { ready = true; } }).render(); }); waitsFor(function() { return ready; }); runs(function() { expect(ready).toBeTruthy(); }); }); it("should return a promise when rendering", function() { var ready = false; runs(function() { var widget = new TravelInsurance({ path: "wnmock" }); widget.render().then(function() { ready = true; }); }); waitsFor(function() { return ready; }); runs(function() { expect(ready).toBeTruthy(); }); }); }); });
Make class final if private constructor git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1379860 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.jorphan.gui; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; /** * Utility class for Renderers */ public final class RendererUtils { private RendererUtils(){ // uninstantiable } public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){ final TableColumnModel columnModel = table.getColumnModel(); for(int i = 0; i < renderers.length; i++){ final TableCellRenderer rend = renderers[i]; if (rend != null) { columnModel.getColumn(i).setCellRenderer(rend); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.jorphan.gui; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; /** * Utility class for Renderers */ public class RendererUtils { private RendererUtils(){ // uninstantiable } public static void applyRenderers(final JTable table, final TableCellRenderer [] renderers){ final TableColumnModel columnModel = table.getColumnModel(); for(int i = 0; i < renderers.length; i++){ final TableCellRenderer rend = renderers[i]; if (rend != null) { columnModel.getColumn(i).setCellRenderer(rend); } } } }
Change BlinkyTape baud to 115200
import blinkycolor import serial class BlinkyTape(object): def __init__(self, port, baud_rate = 115200, pixel_count = 60): self._serial = serial.Serial(port, baud_rate) self._pixel_count = pixel_count self._pixels = [blinkycolor.BLACK] * self._pixel_count @property def pixel_count(self): return self._pixel_count def set_pixel(self, index, color): if index >= self._pixel_count: raise IndexError self._pixels[index] = color def set_pixels(self, pixels): if len(pixels) != self._pixel_count: raise ValueError self._pixels = pixels def update(self): UPDATE_VALUE = [255, 255, 255] for pixel in self._pixels: self._serial.write(pixel.raw) self._serial.write(UPDATE_VALUE) self._serial.flush()
import blinkycolor import serial class BlinkyTape(object): def __init__(self, port, baud_rate = 57600, pixel_count = 60): self._serial = serial.Serial(port, baud_rate) self._pixel_count = pixel_count self._pixels = [blinkycolor.BLACK] * self._pixel_count @property def pixel_count(self): return self._pixel_count def set_pixel(self, index, color): if index >= self._pixel_count: raise IndexError self._pixels[index] = color def set_pixels(self, pixels): if len(pixels) != self._pixel_count: raise ValueError self._pixels = pixels def update(self): UPDATE_VALUE = [255, 255, 255] for pixel in self._pixels: self._serial.write(pixel.raw) self._serial.write(UPDATE_VALUE) self._serial.flush()
refactor: Clean up test suite's common variables. Signed-off-by: Oleksii Fedorov <0263a738e29f7a423bda1d60ddbfb884af6a4010@gmail.com>
describe("Tic Tac Toe Game", function() { var playerOne = "X" var playerTwo = "O" var game beforeEach(function() { game = new Game() }) it("makes sure that player One starts", function() { var validTurn = game.put(playerOne) expect(validTurn).toEqual(true) }) it("makes sure that player Two does not start", function() { var validTurn = game.put(playerTwo) expect(validTurn).toEqual(false) }) it("makes sure that player Two makes second turn", function() { game.put(playerOne) validTurn = game.put(playerTwo) expect(validTurn).toEqual(true) }) it("is possible to put a mark only in empty cell", function() { var validTurn = game.put(playerOne, [3, 3]) expect(validTurn).toEqual(true) }) it("is not possible to put mark in occupied cell", function() { game.put(playerOne, [3, 3]) validTurn = game.put(playerTwo, [3, 3]) expect(validTurn).toEqual(false) }) })
describe("Tic Tac Toe Game", function() { it("makes sure that player One starts", function() { var game = new Game() var playerOne = "X" var playerTwo = "O" var validTurn = game.put(playerOne) expect(validTurn).toEqual(true) }) it("makes sure that player Two does not start", function() { var game = new Game() var playerOne = "X" var playerTwo = "O" var validTurn = game.put(playerTwo) expect(validTurn).toEqual(false) }) it("makes sure that player Two makes second turn", function() { var game = new Game() var playerOne = "X" var playerTwo = "O" game.put(playerOne) validTurn = game.put(playerTwo) expect(validTurn).toEqual(true) }) it("is possible to put a mark only in empty cell", function() { var game = new Game() var playerOne = "X" var playerTwo = "O" var cell = [3, 3] var validTurn = game.put(playerOne, cell) expect(validTurn).toEqual(true) }) it("is not possible to put mark in occupied cell", function() { var game = new Game() var playerOne = "X" var playerTwo = "O" var cell = [3, 3] game.put(playerOne, cell) validTurn = game.put(playerTwo, cell) expect(validTurn).toEqual(false) }) })
[GitHub] Use correct URL for API
import os import urllib import requests GITHUB_BASE_URI = os.environ.get('GITHUB_BASE_URI', 'https://github.com') GITHUB_API_BASE_URI = os.environ.get('GITHUB_API_BASE_URI', 'https://api.github.com') GITHUB_CLIENT_ID = os.environ['GITHUB_CLIENT_ID'] GITHUB_CLIENT_SECRET = os.environ['GITHUB_CLIENT_SECRET'] GITHUB_CALLBACK_URI = 'https://sotu.cocoapods.org/callback' def retrieve_access_token(code): parameters = { 'client_id': GITHUB_CLIENT_ID, 'client_secret': GITHUB_CLIENT_SECRET, 'code': code, } headers = { 'Accept': 'application/json', } response = requests.post(GITHUB_BASE_URI + '/login/oauth/access_token?' + urllib.urlencode(parameters), headers=headers) return response.json().get('access_token') def retrieve_account(access_token): return requests.get(GITHUB_API_BASE_URI + '/user?' + urllib.urlencode({'access_token': access_token})).json() def retrieve_email(access_token): emails = requests.get(GITHUB_API_BASE_URI + '/user/emails?' + urllib.urlencode({'access_token': access_token})).json() primary = next(e for e in emails if e['primary'] is True) return primary['email']
import os import urllib import requests GITHUB_BASE_URI = os.environ.get('GITHUB_BASE_URI', 'https://github.com') GITHUB_API_BASE_URI = os.environ.get('GITHUB_API_BASE_URI', 'https://api.github.com') GITHUB_CLIENT_ID = os.environ['GITHUB_CLIENT_ID'] GITHUB_CLIENT_SECRET = os.environ['GITHUB_CLIENT_SECRET'] GITHUB_CALLBACK_URI = 'https://sotu.cocoapods.org/callback' def retrieve_access_token(code): parameters = { 'client_id': GITHUB_CLIENT_ID, 'client_secret': GITHUB_CLIENT_SECRET, 'code': code, } headers = { 'Accept': 'application/json', } response = requests.post(GITHUB_BASE_URI + '/login/oauth/access_token?' + urllib.urlencode(parameters), headers=headers) return response.json().get('access_token') def retrieve_account(access_token): return requests.get(GITHUB_BASE_URI + '/user?' + urllib.urlencode({'access_token': access_token})).json() def retrieve_email(access_token): emails = requests.get(GITHUB_BASE_URI + '/user/emails?' + urllib.urlencode({'access_token': access_token})).json() primary = next(e for e in emails if e['primary'] is True) return primary['email']
Make integration test work again with usage of SSL
#!/usr/bin/env python import urllib.parse import urllib.request def create_player(username, password, email): url = 'https://localhost:3000/players' values = {'username' : username, 'password' : password, 'email' : email } data = urllib.parse.urlencode(values) data = data.encode('utf-8') # data should be bytes req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) the_page = response.read() print("Created user \'{}\' with password \'{}\' and email \'{}\'".format(username, password, email)) if __name__ == '__main__': create_player("chapmang", "password", "chapmang@dropshot.com") create_player("idlee", "deadparrot", "idlee@dropshot.com") create_player("gilliamt", "lumberjack", "gilliamt@dropshot.com") create_player("jonest", "trojanrabbit", "jonest@dropshot.com") create_player("cleesej", "generaldirection", "cleesej@dropshot.com") create_player("palinm", "fleshwound", "palinm@dropshot.com")
#!/usr/bin/env python import urllib.parse import urllib.request def create_player(username, password, email): url = 'http://localhost:3000/players' values = {'username' : username, 'password' : password, 'email' : email } data = urllib.parse.urlencode(values) data = data.encode('utf-8') # data should be bytes req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) the_page = response.read() print("Created user \'{}\' with password \'{}\' and email \'{}\'".format(username, password, email)) if __name__ == '__main__': create_player("chapmang", "password", "chapmang@dropshot.com") create_player("idlee", "deadparrot", "idlee@dropshot.com") create_player("gilliamt", "lumberjack", "gilliamt@dropshot.com") create_player("jonest", "trojanrabbit", "jonest@dropshot.com") create_player("cleesej", "generaldirection", "cleesej@dropshot.com") create_player("palinm", "fleshwound", "palinm@dropshot.com")
[misc] Mark new role as unstable API
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ package org.phenotips.translation; import org.xwiki.component.annotation.Role; import org.xwiki.stability.Unstable; /** * @version $Id$ */ @Unstable("New API introduced in 1.2") @Role public interface TranslationManager { /** * Get the translation corresponding to the given key, using the current locale. * * @param key the identifier of the message to retrieve * @param parameters optional parameters to be used in the translation * @return the message in the current locale, as plain text (all markup is stripped) */ String translate(String key, Object... parameters); }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/ */ package org.phenotips.translation; import org.xwiki.component.annotation.Role; /** * @version $Id$ */ @Role public interface TranslationManager { /** * Get the translation corresponding to the given key, using the current locale. * * @param key the identifier of the message to retrieve * @param parameters optional parameters to be used in the translation * @return the message in the current locale, as plain text (all markup is stripped) */ String translate(String key, Object... parameters); }
Add `publication_date` property to `Tip` model. BEFORE: We had a column in the DB, but no property on the model object. AFTER: We have that property in the model.
# -*- coding: utf-8 -*- """Defines the model 'layer' for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from sqlalchemy import func from flask.ext.sqlalchemy import BaseQuery from pytips import db class TipQuery(BaseQuery): def random_tip(self): """Retrieve a random ``Tip``.""" return self.order_by(func.random()).first() class Tip(db.Model): """Represents a 'tip' for display.""" query_class = TipQuery id = db.Column(db.Integer, primary_key=True) author_name = db.Column(db.String, nullable=False) author_url = db.Column(db.String(1024), nullable=False) url = db.Column(db.String(1024), unique=True, nullable=False) rendered_html = db.Column(db.String(1024), unique=True, nullable=False) publication_date = db.Column(db.DateTime(timezone=True), nullable=False) def __repr__(self): return '<Tip %r>' % self.url
# -*- coding: utf-8 -*- """Defines the model 'layer' for PyTips.""" from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import from __future__ import division from sqlalchemy import func from flask.ext.sqlalchemy import BaseQuery from pytips import db class TipQuery(BaseQuery): def random_tip(self): """Retrieve a random ``Tip``.""" return self.order_by(func.random()).first() class Tip(db.Model): """Represents a 'tip' for display.""" query_class = TipQuery id = db.Column(db.Integer, primary_key=True) author_name = db.Column(db.String, nullable=False) author_url = db.Column(db.String(1024), nullable=False) url = db.Column(db.String(1024), unique=True, nullable=False) rendered_html = db.Column(db.String(1024), unique=True, nullable=False) def __repr__(self): return '<Tip %r>' % self.url
Use auxilliary recursive method to eliminate need to create new strings via substring method
/* Write a recursive method that finds the number of occurrences of a specified letter in a string using the following method header: public static int count(String str, char a) For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string and a character, and displays the number of occurrences for the character in the string. */ import java.util.Scanner; public class E18_10 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s = input.nextLine(); System.out.print("Enter a character: "); char c = input.nextLine().charAt(0); System.out.println(count(s, c)); } public static int count(String str, char a) { return count(str, a, 0); } private static int count(String str, char a, int index) { if (index < str.length()) { int match = str.toLowerCase().charAt(index) == Character.toLowerCase(a) ? 1 : 0; return match + count(str, a, index + 1); } else { return 0; } } }
/* Write a recursive method that finds the number of occurrences of a specified letter in a string using the following method header: public static int count(String str, char a) For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string and a character, and displays the number of occurrences for the character in the string. */ import java.util.Scanner; public class E18_10 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String s = input.nextLine(); System.out.print("Enter a character: "); char c = input.nextLine().charAt(0); System.out.println(count(s, c)); } public static int count(String str, char a) { if (str.length() > 0) { int match = str.toLowerCase().charAt(0) == Character.toLowerCase(a) ? 1 : 0; return match + count(str.substring(1, str.length()), a); } else { return 0; } } }
Update comment of images table migration
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function(Blueprint $table) { $table->increments('id'); $table->integer('thread_id'); $table->string('url', 512); // complete url of the image $table->string('size', 64)->nullable(); // image size in bytes $table->string('name', 128)->nullable(); // name of image complete with the extension $table->integer('download_status')->default(0); // 0:not downloaded yet, 1:downloaded, 2:block, 3:modified, 4:skipped $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('images'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function(Blueprint $table) { $table->increments('id'); $table->integer('thread_id'); $table->string('url', 512); // complete url of the image $table->string('size', 64)->nullable(); // image size in bytes $table->string('name', 128)->nullable(); // name of image complete with the extension $table->integer('download_status')->default(0); // 0:not downloaded yet, 1:downloaded, 2:block, 3:modified $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('images'); } }
Update range to 6 figures
/* * Copyright 2015 Ryan Gilera. * * 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 com.github.daytron.revworks.ui.constants; /** * * @author Ryan Gilera */ public enum LoginValidationNum { STUDENT_ID_MIN_VALUE(100000), STUDENT_ID_MAX_VALUE(999999), STUDENT_ID_LENGTH(6), EMAIL_MAX_LENGTH(254), PASSWORD_MAX_LENGTH(16), PASSWORD_MIN_LENGTH(6) ; private final int value; private LoginValidationNum(int value) { this.value = value; } public int getValue() { return value; } }
/* * Copyright 2015 Ryan Gilera. * * 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 com.github.daytron.revworks.ui.constants; /** * * @author Ryan Gilera */ public enum LoginValidationNum { STUDENT_ID_MIN_VALUE(10000), STUDENT_ID_MAX_VALUE(99999), STUDENT_ID_LENGTH(5), EMAIL_MAX_LENGTH(254), PASSWORD_MAX_LENGTH(16), PASSWORD_MIN_LENGTH(6) ; private final int value; private LoginValidationNum(int value) { this.value = value; } public int getValue() { return value; } }
Add header background color based on config
import React from 'react'; import NavMenu from './NavMenu'; export default class Header extends React.Component { constructor(props) { super(props); } render() { let navMenu; if (this.props.config.headerMenuLinks.length > 0) { navMenu = <NavMenu links={this.props.config.headerMenuLinks} /> } return ( <header className="masthead" style={{backgroundColor: this.props.config.headerColor}}> <div className="container"> <a href={this.props.config.rootUrl} className="masthead-logo">{this.props.config.name}</a> {navMenu} </div> </header> ); } }
import React from 'react'; import NavMenu from './NavMenu'; export default class Header extends React.Component { constructor(props) { super(props); } render() { let navMenu; if (this.props.config.headerMenuLinks.length > 0) { navMenu = <NavMenu links={this.props.config.headerMenuLinks} /> } return ( <header className="masthead" style={{backgroundColor: '#4C5664'}}> <div className="container"> <a href={this.props.config.rootUrl} className="masthead-logo">{this.props.config.name}</a> {navMenu} </div> </header> ); } }
Use Docker API property in fixture
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(): yield None client = docker.from_env() for container in client.containers.list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
Change the console log level back to WARN
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.WARN NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
import os import re import sublime from .logger import * # get the directory path to this file; LIBS_DIR = os.path.dirname(os.path.abspath(__file__)) PLUGIN_DIR = os.path.dirname(LIBS_DIR) PACKAGES_DIR = os.path.dirname(PLUGIN_DIR) PLUGIN_NAME = os.path.basename(PLUGIN_DIR) # only Sublime Text 3 build after 3072 support tooltip TOOLTIP_SUPPORT = int(sublime.version()) >= 3072 # determine if the host is sublime text 2 IS_ST2 = int(sublime.version()) < 3000 # detect if quick info is available for symbol SUBLIME_WORD_MASK = 515 # set logging levels LOG_FILE_LEVEL = logging.WARN LOG_CONSOLE_LEVEL = logging.DEBUG NON_BLANK_LINE_PATTERN = re.compile("[\S]+") VALID_COMPLETION_ID_PATTERN = re.compile("[a-zA-Z_$\.][\w$\.]*\Z") # idle time length in millisecond IDLE_TIME_LENGTH = 20
Refresh disks on starting or stopping array
$(function() { var $array_controls = $('#array-controls'); $(document).on('click', '#array-controls a', function(e) { e.preventDefault(); var $btn = $(this), confirmed = true, action = $.trim($btn.text().toLowerCase()); if ((/stop/).test(action)) { confirmed = confirm('Really ' + action + '?'); } if (confirmed) { $btn.button('loading'); var xhr = $.post($(this).attr('href'), {}); xhr.success(function(data, textStatus, xhr) { $array_controls.find('.btn').toggleClass('hide'); if (window.location.pathname === "/disks") { window.reload; } }); xhr.complete(function(data, textStatus, xhr) { $btn.button('reset'); }); } }); });
$(function() { var $array_controls = $('#array-controls'); $(document).on('click', '#array-controls a', function(e) { e.preventDefault(); var $btn = $(this), confirmed = true, action = $.trim($btn.text().toLowerCase()); if ((/stop/).test(action)) { confirmed = confirm('Really ' + action + '?'); } if (confirmed) { $btn.button('loading'); var xhr = $.post($(this).attr('href'), {}); xhr.success(function(data, textStatus, xhr) { $array_controls.find('.btn').toggleClass('hide'); }); xhr.complete(function(data, textStatus, xhr) { $btn.button('reset'); }); } }); });