text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Hide feedback notification after 5 seconds (rather than 10)
Atmo.Views.NotificationHolder = Backbone.View.extend({ initialize: function() { Atmo.notifications.bind('add', this.add_notification, this); }, add_notification: function(model) { var x_close = $('<button/>', { type: 'button', 'class': 'close', 'data-dismiss' : 'alert', html: '&times' }); var alert_el = $('<div/>', { 'class': 'alert alert-info fade in', html: '<strong>' + model.get('header') + '</strong> ' + model.get('body') }); this.$el.html(alert_el.prepend(x_close)); // Automatically dismiss alert after 5 seconds if (model.get('sticky') == false) { setTimeout(function() { x_close.trigger('click'); }, 5*1000); } } });
Atmo.Views.NotificationHolder = Backbone.View.extend({ initialize: function() { Atmo.notifications.bind('add', this.add_notification, this); }, add_notification: function(model) { var x_close = $('<button/>', { type: 'button', 'class': 'close', 'data-dismiss' : 'alert', html: '&times' }); var alert_el = $('<div/>', { 'class': 'alert alert-info fade in', html: '<strong>' + model.get('header') + '</strong> ' + model.get('body') }); this.$el.html(alert_el.prepend(x_close)); // Automatically dismiss alert after 5 seconds if (model.get('sticky') == false) { setTimeout(function() { x_close.trigger('click'); }, 10*1000); } } });
Progressbar: Use new has/lacksClasses assertions for all class checks
(function( $ ) { module( "progressbar: methods" ); test( "destroy", function() { expect( 1 ); domEqual( "#progressbar", function() { $( "#progressbar" ).progressbar().progressbar( "destroy" ); }); }); test( "disable", function( assert ) { expect( 3 ); var element = $( "#progressbar" ).progressbar().progressbar( "disable" ); assert.hasClasses( element.progressbar( "widget" ), "ui-state-disabled" ); ok( element.progressbar( "widget" ).attr( "aria-disabled" ), "element gets aria-disabled" ); assert.hasClasses( element.progressbar( "widget" ), "ui-progressbar-disabled" ); }); test( "value", function() { expect( 3 ); var element = $( "<div>" ).progressbar({ value: 20 }); equal( element.progressbar( "value" ), 20, "correct value as getter" ); strictEqual( element.progressbar( "value", 30 ), element, "chainable as setter" ); equal( element.progressbar( "option", "value" ), 30, "correct value after setter" ); }); test( "widget", function() { expect( 2 ); var element = $( "#progressbar" ).progressbar(), widgetElement = element.progressbar( "widget" ); equal( widgetElement.length, 1, "one element" ); strictEqual( widgetElement[ 0 ], element[ 0 ], "same element" ); }); }( jQuery ) );
(function( $ ) { module( "progressbar: methods" ); test( "destroy", function() { expect( 1 ); domEqual( "#progressbar", function() { $( "#progressbar" ).progressbar().progressbar( "destroy" ); }); }); test( "disable", function() { expect( 3 ); var element = $( "#progressbar" ).progressbar().progressbar( "disable" ); ok( element.progressbar( "widget" ).hasClass( "ui-state-disabled" ), "element gets ui-state-disabled" ); ok( element.progressbar( "widget" ).attr( "aria-disabled" ), "element gets aria-disabled" ); ok( element.progressbar( "widget" ).hasClass( "ui-progressbar-disabled" ), "element gets ui-progressbar-disabled" ); }); test( "value", function() { expect( 3 ); var element = $( "<div>" ).progressbar({ value: 20 }); equal( element.progressbar( "value" ), 20, "correct value as getter" ); strictEqual( element.progressbar( "value", 30 ), element, "chainable as setter" ); equal( element.progressbar( "option", "value" ), 30, "correct value after setter" ); }); test( "widget", function() { expect( 2 ); var element = $( "#progressbar" ).progressbar(), widgetElement = element.progressbar( "widget" ); equal( widgetElement.length, 1, "one element" ); strictEqual( widgetElement[ 0 ], element[ 0 ], "same element" ); }); }( jQuery ) );
Use absolute imports to avoid module naming issues
from __future__ import absolute_import import os from settings import * db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
import os from settings import * db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't need secrets" if db == "sqlite": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } elif db == "postgres": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'inboxen', 'USER': 'postgres', }, } else: raise NotImplementedError("Please check tests/settings.py for valid DB values")
Add data: response to be manipulated in front end
var base = require('./base.js'); exports.assemble = { addSchedule: function (parameters) { var userEventEntry = { availability: JSON.stringify(parameters.availability), Users_id: parameters.usersid, Events_id: parameters.eventsid }; base.dbInsert('userevents', userEventEntry); return JSON.stringify({ msgType: 'updateSchedule', status: 'complete' }); }, viewUser: function (parameters) { var userReadInfo = { Users_id: parameters.usersid }; response = base.dbSelect('assemble' , 'users' , userReadInfo); return JSON.stringify({ msgType: 'readuser', data: response, status: 'read' }); };
var base = require('./base.js'); exports.assemble = { addSchedule: function (parameters) { var userEventEntry = { availability: JSON.stringify(parameters.availability), Users_id: parameters.usersid, Events_id: parameters.eventsid }; base.dbInsert('userevents', userEventEntry); return JSON.stringify({ msgType: 'updateSchedule', status: 'complete' }); }, viewUser: function (parameters) { var userReadInfo = { Users_id: parameters.usersid }; base.dbSelect('assemble' , 'users' , userReadInfo); return JSON.stringify({ msgType: 'readuser', status: 'read' }); };
Add back the webpack inline sourcemaps
var path = require('path'); var webpack = require('webpack'); module.exports = { plugins: [ new webpack.DefinePlugin({ "process.env": Object.keys(process.env).reduce(function(o, k) { o[k] = JSON.stringify(process.env[k]); return o; }, {}) }), ], devtool: '#inline-source-map', module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader?stage=0'], }, { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded&" + "includePaths[]=" + (path.resolve(__dirname, "./bower_components")) + "&" + "includePaths[]=" + (path.resolve(__dirname, "./node_modules")) }, ] } };
var path = require('path'); var webpack = require('webpack'); module.exports = { plugins: [ new webpack.DefinePlugin({ "process.env": Object.keys(process.env).reduce(function(o, k) { o[k] = JSON.stringify(process.env[k]); return o; }, {}) }), ], module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot-loader', 'babel-loader?stage=0'], }, { test: /\.scss$/, loader: "style!css!sass?outputStyle=expanded&" + "includePaths[]=" + (path.resolve(__dirname, "./bower_components")) + "&" + "includePaths[]=" + (path.resolve(__dirname, "./node_modules")) }, ] } };
Add route for line map editor
// -*- tab-width: 2 -*- var express = require('express') var router = express.Router() /* GET home page. */ router.get('/', function (req, res) { res.render('admin_home') }) router.get('/:competitionid', function (req, res) { res.render('competition_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/teams', function (req, res) { res.render('team_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/runs', function (req, res) { res.render('run_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/rounds', function (req, res) { res.render('round_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/line/editor', function (req, res) { res.render('line_editor', {id : req.params.competitionid}) }) router.get('/:competitionid/fields', function (req, res) { res.render('field_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/line/tilesets', function (req, res) { res.render('tileset_admin', {id : req.params.competitionid}) }) module.exports = router
// -*- tab-width: 2 -*- var express = require('express') var router = express.Router() /* GET home page. */ router.get('/', function (req, res) { res.render('admin_home') }) router.get('/:competitionid', function (req, res) { res.render('competition_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/teams', function (req, res) { res.render('team_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/runs', function (req, res) { res.render('run_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/rounds', function (req, res) { res.render('round_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/fields', function (req, res) { res.render('field_admin', {id : req.params.competitionid}) }) router.get('/:competitionid/line/tilesets', function (req, res) { res.render('tileset_admin', {id : req.params.competitionid}) }) module.exports = router
Improve the code coverage of /plugin/pkg/admission/deny
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package deny import ( "testing" "k8s.io/apiserver/pkg/admission" "k8s.io/kubernetes/pkg/api" ) func TestAdmission(t *testing.T) { handler := NewAlwaysDeny() err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, nil)) if err == nil { t.Error("Expected error returned from admission handler") } } func TestHandles(t *testing.T) { handler := NewAlwaysDeny() tests := []admission.Operation{admission.Create, admission.Connect, admission.Update, admission.Delete} for _, test := range tests { if !handler.Handles(test) { t.Errorf("Expected handling all operations, including: %v", test) } } }
/* Copyright 2014 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package deny import ( "testing" "k8s.io/apiserver/pkg/admission" "k8s.io/kubernetes/pkg/api" ) func TestAdmission(t *testing.T) { handler := NewAlwaysDeny() err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, nil)) if err == nil { t.Errorf("Expected error returned from admission handler") } }
Remove hard code prj root.
const app = require('./core/app'); const element = require('./core/element'); const plugin = require('./core/plugin'); const paths = require('./core/paths'); const vio = require('./core/vio'); const template = require('./core/template'); const config = require('./core/config'); const ast = require('./core/ast'); const refactor = require('./core/refactor'); const deps = require('./core/deps'); const handleCommand = require('./core/handleCommand'); // paths.setProjectRoot('/Users/pwang7/workspace/app-next/'); // paths.setProjectRoot('/Users/pwang7/workspace/rekit/packages/rekit-studio'); global.rekit = { core: { app, paths, plugin, element, vio, template, config, refactor, ast, deps, handleCommand, }, }; plugin.loadPlugins(); module.exports = global.rekit;
const app = require('./core/app'); const element = require('./core/element'); const plugin = require('./core/plugin'); const paths = require('./core/paths'); const vio = require('./core/vio'); const template = require('./core/template'); const config = require('./core/config'); const ast = require('./core/ast'); const refactor = require('./core/refactor'); const deps = require('./core/deps'); const handleCommand = require('./core/handleCommand'); paths.setProjectRoot('/Users/pwang7/workspace/app-next/'); // paths.setProjectRoot('/Users/pwang7/workspace/rekit/packages/rekit-studio'); global.rekit = { core: { app, paths, plugin, element, vio, template, config, refactor, ast, deps, handleCommand, }, }; plugin.loadPlugins(); module.exports = global.rekit;
Change 'language' to 'syntax', that is more precise terminology.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jsl # License: MIT # """This module exports the JSL plugin linter class.""" from SublimeLinter.lint import Linter class JSL(Linter): """Provides an interface to the jsl executable.""" syntax = ('javascript', 'html') cmd = 'jsl -stdin -nologo -nosummary' regex = r'''(?xi) # First line is (lineno): type: error message ^\((?P<line>\d+)\):.*?(?:(?P<warning>warning)|(?P<error>error)):\s*(?P<message>.+)$\r?\n # Second line is the line of code ^.*$\r?\n # Third line is a caret pointing to the position of the error ^(?P<col>[^\^]*)\^$ ''' multiline = True defaults = { '-conf:': None } selectors = { 'html': 'source.js.embedded.html' }
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-jsl # License: MIT # """This module exports the JSL plugin linter class.""" from SublimeLinter.lint import Linter class JSL(Linter): """Provides an interface to the jsl executable.""" language = ('javascript', 'html') cmd = 'jsl -stdin -nologo -nosummary' regex = r'''(?xi) # First line is (lineno): type: error message ^\((?P<line>\d+)\):.*?(?:(?P<warning>warning)|(?P<error>error)):\s*(?P<message>.+)$\r?\n # Second line is the line of code ^.*$\r?\n # Third line is a caret pointing to the position of the error ^(?P<col>[^\^]*)\^$ ''' multiline = True defaults = { '-conf:': None } selectors = { 'html': 'source.js.embedded.html' }
Fix flake8 errors: W391 blank line at end of file
import subprocess from thefuck.utils import for_app, replace_command, eager @for_app('ifconfig') def match(command): return 'error fetching interface information: Device not found' \ in command.stderr @eager def _get_possible_interfaces(): proc = subprocess.Popen(['ifconfig', '-a'], stdout=subprocess.PIPE) for line in proc.stdout.readlines(): line = line.decode() if line and line != '\n' and not line.startswith(' '): yield line.split(' ')[0] def get_new_command(command): interface = command.stderr.split(' ')[0][:-1] possible_interfaces = _get_possible_interfaces() return replace_command(command, interface, possible_interfaces)
import subprocess from thefuck.utils import for_app, replace_command, eager @for_app('ifconfig') def match(command): return 'error fetching interface information: Device not found' \ in command.stderr @eager def _get_possible_interfaces(): proc = subprocess.Popen(['ifconfig', '-a'], stdout=subprocess.PIPE) for line in proc.stdout.readlines(): line = line.decode() if line and line != '\n' and not line.startswith(' '): yield line.split(' ')[0] def get_new_command(command): interface = command.stderr.split(' ')[0][:-1] possible_interfaces = _get_possible_interfaces() return replace_command(command, interface, possible_interfaces)
OAK-3898: Add filter capabilities to the segment graph run mode Bump export version git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1725678 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. */ @Version("10.0.0") @Export(optional = "provide:=true") package org.apache.jackrabbit.oak.plugins.segment; import aQute.bnd.annotation.Export; import aQute.bnd.annotation.Version;
/* * 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. */ @Version("9.0.0") @Export(optional = "provide:=true") package org.apache.jackrabbit.oak.plugins.segment; import aQute.bnd.annotation.Export; import aQute.bnd.annotation.Version;
Reset color to default when color been has changed
import { FETCH_ASSETS, FETCH_ASSETS_FULFILLED, SET_CURRENT_ASSET, SET_CURRENT_COLOR } from '../constants/assets'; import keyBy from 'lodash/keyBy'; const initialState = { isLoading: false, data: {}, current: 'Hairstyles', currentColor: 'default' }; const reducer = (state = initialState, action) => { switch (action.type) { case FETCH_ASSETS: return { ...state, isLoading: true }; case FETCH_ASSETS_FULFILLED: const data = keyBy(action.payload.data.map(folder => ({ ...folder, colors: keyBy(folder.colors, 'id') })), 'id'); return { ...state, isLoading: false, data }; case SET_CURRENT_ASSET: return { ...state, current: action.payload, currentColor: initialState.currentColor }; case SET_CURRENT_COLOR: return { ...state, currentColor: action.payload }; default: return state; } }; export default reducer;
import { FETCH_ASSETS, FETCH_ASSETS_FULFILLED, SET_CURRENT_ASSET, SET_CURRENT_COLOR } from '../constants/assets'; import keyBy from 'lodash/keyBy'; const initialState = { isLoading: false, data: {}, current: 'Hairstyles', currentColor: 'default' }; const reducer = (state = initialState, action) => { switch (action.type) { case FETCH_ASSETS: return { ...state, isLoading: true }; case FETCH_ASSETS_FULFILLED: const data = keyBy(action.payload.data.map(folder => ({ ...folder, colors: keyBy(folder.colors, 'id') })), 'id'); return { ...state, isLoading: false, data }; case SET_CURRENT_ASSET: return { ...state, current: action.payload }; case SET_CURRENT_COLOR: return { ...state, currentColor: action.payload }; default: return state; } }; export default reducer;
Make it possible to manually override version numbers
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=os.getenv( 'PAGEKITE_VERSION', APPVER.replace('github', 'dev%d' % (120*int(time.time()/120)))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'], install_requires=['SocksipyChain >= 2.0.15'] )
#!/usr/bin/python import time from datetime import date from setuptools import setup from pagekite.common import APPVER import os try: # This borks sdist. os.remove('.SELF') except: pass setup( name="pagekite", version=APPVER.replace('github', 'dev%d' % (120*int(time.time()/120))), license="AGPLv3+", author="Bjarni R. Einarsson", author_email="bre@pagekite.net", url="http://pagekite.org/", description="""PageKite makes localhost servers visible to the world.""", long_description="""\ PageKite is a system for running publicly visible servers (generally web servers) on machines without a direct connection to the Internet, such as mobile devices or computers behind restrictive firewalls. PageKite works around NAT, firewalls and IP-address limitations by using a combination of tunnels and reverse proxies. Natively supported protocols: HTTP, HTTPS Any other TCP-based service, including SSH and VNC, may be exposed as well to clients supporting HTTP Proxies. """, packages=['pagekite', 'pagekite.ui', 'pagekite.proto'], scripts=['scripts/pagekite', 'scripts/lapcat', 'scripts/vipagekite'], install_requires=['SocksipyChain >= 2.0.15'] )
Move calls within Sitemap Xml controller
<?php class SitemapXML_Controller extends Page_Controller { private static $url_handlers = array( '' => 'GetSitemapXML' ); private static $allowed_actions = array( 'GetSitemapXML' ); public function init() { parent::init(); } public function GetSitemapXML() { $this->response->addHeader("Content-Type", "application/xml"); $this->getSiteTree(); $sitemap = new ArrayData(array( 'Pages' => $this->pages )); return $sitemap->renderWith('SitemapPages'); } private function getSiteTree() { $this->pages = SiteTree::get()->filter(array( 'ClassName:not' => 'ErrorPage' )); } }
<?php class SitemapXML_Controller extends Page_Controller { private static $url_handlers = array( '' => 'GetSitemapXML' ); private static $allowed_actions = array( 'GetSitemapXML' ); public function init() { $this->response->addHeader("Content-Type", "application/xml"); parent::init(); $this->getSiteTree(); } public function GetSitemapXML() { $sitemap = new ArrayData(array( 'Pages' => $this->pages )); return $sitemap->renderWith('SitemapPages'); } private function getSiteTree() { $this->pages = SiteTree::get()->filter(array( 'ClassName:not' => 'ErrorPage' )); } }
Add allowed and exposed headers to response headers for CORS
/* * SystemConfig.java * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SystemConfig { protected static final String CORS_MAPPING = "/**"; protected static final String CORS_ALLOWED_ORIGINS = "http://localhost:4200"; @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(final CorsRegistry registry) { registry.addMapping(CORS_MAPPING) .allowedOrigins(CORS_ALLOWED_ORIGINS) .allowedHeaders("*") .exposedHeaders(JwtFilter.HEADER_CLAIMS, JwtFilter.HEADER_CLAIMS_SUBJECT); } }; } }
/* * SystemConfig.java * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class SystemConfig { protected static final String CORS_MAPPING = "/**"; protected static final String CORS_ALLOWED_ORIGINS = "http://localhost:4200"; @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(final CorsRegistry registry) { registry.addMapping(CORS_MAPPING).allowedOrigins(CORS_ALLOWED_ORIGINS); } }; } }
Add reverse to data migration
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-03-04 23:14 from __future__ import unicode_literals import json from django.db import migrations def populate_default(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') for obj in ScriptParameter.objects.all(): try: obj.default = json.loads(obj._default) except Exception: obj.default = obj._default obj.save() def reverse_populate_default(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') for obj in ScriptParameter.objects.all(): obj._default = json.dumps(obj.default) obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0036_add-jsonfield'), ] operations = [ migrations.RunPython(populate_default, reverse_populate_default) ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-03-04 23:14 from __future__ import unicode_literals import json from django.db import migrations def populate_default(apps, schema_editor): ScriptParameter = apps.get_model('wooey', 'ScriptParameter') for obj in ScriptParameter.objects.all(): try: obj.default = json.loads(obj._default) except Exception: obj.default = obj._default obj.save() class Migration(migrations.Migration): dependencies = [ ('wooey', '0036_add-jsonfield'), ] operations = [ migrations.RunPython(populate_default) ]
Define PropertyReader interface and use it a couple of places.
package boardgame type State struct { //The version number of the state. Increments by one each time a Move is //applied. Version int //The schema version that this state object uses. This number will not //change often, but is useful to detect if the state was saved back when a //diferent schema was in use and needs to be migrated. Schema int //Game includes the non-user state for the game. Game GameState //Users contains a UserState object for each user in the game. Users []UserState } type JSONer interface { //Returns the canonical JSON representation of this object, suitable to //being communicated across the wire or saved in a DB. JSON() []byte } //Property reader is a way to read out properties on an object with unknown //shape. type PropertyReader interface { //Props returns a list of all property names that are defined for this //object. Props() []string //Prop returns the value for that property. Prop(name string) interface{} } //UserState represents the state of a game associated with a specific user. type UserState interface { //PlayerIndex encodes the index this user's state is in the containing //state object. PlayerIndex() int JSONer PropertyReader } //GameState represents the state of a game that is not associated with a //particular user. For example, the draw stack of cards, who the current //player is, and other properites. type GameState interface { JSONer PropertyReader }
package boardgame type State struct { //The version number of the state. Increments by one each time a Move is //applied. Version int //The schema version that this state object uses. This number will not //change often, but is useful to detect if the state was saved back when a //diferent schema was in use and needs to be migrated. Schema int //Game includes the non-user state for the game. Game GameState //Users contains a UserState object for each user in the game. Users []UserState } type JSONer interface { //Returns the canonical JSON representation of this object, suitable to //being communicated across the wire or saved in a DB. JSON() []byte } //UserState represents the state of a game associated with a specific user. type UserState interface { //PlayerIndex encodes the index this user's state is in the containing //state object. PlayerIndex() int JSONer } //GameState represents the state of a game that is not associated with a //particular user. For example, the draw stack of cards, who the current //player is, and other properites. type GameState interface { JSONer }
Fix 'file not found' when loading translation files.
const i18next = require('i18next'); const i18nextXHRBackend = require('i18next-xhr-backend'); const jqueryI18next = require('jquery-i18next'); i18next .use(i18nextXHRBackend) .init({ whitelist: ['en-US', 'pt-BR'], fallbackLng: 'en-US', debug: false, ns: ['deimos-issuer'], defaultNS: 'deimos-issuer', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { jqueryI18next.init(i18next, $); $('body').localize(); $('#language').change(function() { i18next.changeLanguage($('#language').val(), function() { ipcRenderer.send('language-change', $('#language').val()); $('body').localize(); }); }); }); function loadTranslations() { const language = remote.getGlobal('settings').language; $('#language').val(language); $('#language').trigger('change'); }
const i18next = require('i18next'); const i18nextXHRBackend = require('i18next-xhr-backend'); const jqueryI18next = require('jquery-i18next'); i18next .use(i18nextXHRBackend) .init({ fallbackLng: 'en-US', debug: false, ns: ['deimos-issuer'], defaultNS: 'deimos-issuer', backend: { loadPath: 'locales/{{lng}}/{{ns}}.json' } }, function(err, t) { jqueryI18next.init(i18next, $); $('body').localize(); $('#language').change(function() { i18next.changeLanguage($('#language').val(), function() { ipcRenderer.send('language-change', $('#language').val()); $('body').localize(); }); }); }); function loadTranslations() { const language = remote.getGlobal('settings').language; $('#language').val(language); $('#language').trigger('change'); }
Fix optimistic state for Player
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { ensureState } from 'redux-optimistic-ui' import { requestPlayNext } from 'store/modules/status' import { emitStatus, emitError, emitLeave, cancelStatus, mediaRequest, mediaRequestSuccess, mediaRequestError, } from '../../modules/player' const mapActionCreators = { emitStatus, emitError, emitLeave, cancelStatus, requestPlayNext, mediaRequest, mediaRequestSuccess, mediaRequestError, } // simplify player logic; if this reference changes on each // render it will cause an infinite loop of status updates const defaultQueueItem = { queueId: -1, } const mapStateToProps = (state) => { const { player, status } = state const queue = ensureState(state.queue) return { queueItem: queue.entities[player.queueId] || defaultQueueItem, volume: player.volume, isAtQueueEnd: player.isAtQueueEnd, isQueueEmpty: queue.result.length === 0, isPlaying: player.isPlaying, isFetching: player.isFetching, isErrored: typeof status.errors[status.queueId] !== 'undefined', // timestamp pass-through triggers status emission for each received command lastCommandAt: player.lastCommandAt, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
import PlayerController from './PlayerController' import { connect } from 'react-redux' import { requestPlayNext } from 'store/modules/status' import { emitStatus, emitError, emitLeave, cancelStatus, mediaRequest, mediaRequestSuccess, mediaRequestError, } from '../../modules/player' const mapActionCreators = { emitStatus, emitError, emitLeave, cancelStatus, requestPlayNext, mediaRequest, mediaRequestSuccess, mediaRequestError, } // simplify player logic; if this reference changes on each // render it will cause an infinite loop of status updates const defaultQueueItem = { queueId: -1, } const mapStateToProps = (state) => { const { player, queue, status } = state return { queueItem: queue.entities[player.queueId] || defaultQueueItem, volume: player.volume, isAtQueueEnd: player.isAtQueueEnd, isQueueEmpty: queue.result.length === 0, isPlaying: player.isPlaying, isFetching: player.isFetching, isErrored: typeof status.errors[status.queueId] !== 'undefined', // timestamp pass-through triggers status emission for each received command lastCommandAt: player.lastCommandAt, } } export default connect(mapStateToProps, mapActionCreators)(PlayerController)
[refactor] Fix test path in Validation test
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2018 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package xquery.validation; import org.exist.test.runner.XSuite; import org.junit.runner.RunWith; @RunWith(XSuite.class) @XSuite.XSuiteFiles({ "exist-core/src/test/xquery/validation" }) public class ValidationTests { }
/* * eXist Open Source Native XML Database * Copyright (C) 2001-2018 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package xquery.validation; import org.exist.test.runner.XSuite; import org.junit.runner.RunWith; @RunWith(XSuite.class) @XSuite.XSuiteFiles({ "src/test/xquery/validation" }) public class ValidationTests { }
Refactor the initialization a bit to make configuration easier.
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check_temp(self): if not self._last_response: self.get_info() if self._last_response['temp'] > self.alert_high: self.alert('Temperature max of %s exceeded. Currently %s' % (self.alert_high, self._last_response['temp'])) if self._last_response['temp'] < self.alert_low: self.alert('Temperature min of %s exceeded. Currently %s' % (self.alert_low, self._last_response['temp'])) def alert(self, message): print(message) if __name__ == '__main__': thermostat_ip = '10.0.1.53' # simple configuration - set the IP, nothing else. Print the alerts when they occur to stdout. Not very useful though... tw = TemperatureWatch() tw.thermostat_url = 'http://%s' % thermostat_ip tw.check_temp()
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check_temp(self): if not self._last_response: self.get_info() if self._last_response['temp'] > self.alert_high: self.alert('Temperature max of %s exceeded. Currently %s' % (self.alert_high, self._last_response['temp'])) if self._last_response['temp'] < self.alert_low: self.alert('Temperature min of %s exceeded. Currently %s' % (self.alert_low, self._last_response['temp'])) def alert(self, message): print(message) if __name__ == '__main__': tw = TemperatureWatch() tw.thermostat_url = 'http://10.0.1.52' tw.check_temp()
Change default data path to be a relative path although a relative path could be ambiguous, in most cases this a reasonable and convenient setting because you'll likely invoke the binary from the root directory of the app, and if you don't you can easily pass in a different setting.
package main import ( "flag" "fmt" "os" ) type Config struct { extractAddress string entitiesPath string logPath string } func NewConfig() *Config { cfg := new(Config) cfg.extractAddress = getenvDefault("EXTRACTOR_EXTRACT_ADDR", ":3096") cfg.entitiesPath = getenvDefault("EXTRACTOR_ENTITIES_PATH", "data/entities.jsonl") cfg.logPath = getenvDefault("EXTRACTOR_LOG_PATH", "STDERR") flag.Usage = usage flag.Parse() return cfg } func usage() { fmt.Fprintf(os.Stderr, "Usage: %s\n", os.Args[0]) helpstring := ` The following environment variables and defaults are available: EXTRACTOR_EXTRACT_ADDR=:3096 Address on which to serve extraction requests EXTRACTOR_ENTITIES_PATH=/var/apps/entity-extractor/data/entities.jsonl Path of file holding entities in jsonlines format EXTRACTOR_ERROR_LOG=STDERR File to log errors to (in JSON format) ` fmt.Fprintf(os.Stderr, helpstring) os.Exit(2) } func getenvDefault(key string, defaultVal string) string { val := os.Getenv(key) if val == "" { val = defaultVal } return val }
package main import ( "flag" "fmt" "os" ) type Config struct { extractAddress string entitiesPath string logPath string } func NewConfig() *Config { cfg := new(Config) cfg.extractAddress = getenvDefault("EXTRACTOR_EXTRACT_ADDR", ":3096") cfg.entitiesPath = getenvDefault("EXTRACTOR_ENTITIES_PATH", "/var/apps/entity-extractor/data/entities.jsonl") cfg.logPath = getenvDefault("EXTRACTOR_LOG_PATH", "STDERR") flag.Usage = usage flag.Parse() return cfg } func usage() { fmt.Fprintf(os.Stderr, "Usage: %s\n", os.Args[0]) helpstring := ` The following environment variables and defaults are available: EXTRACTOR_EXTRACT_ADDR=:3096 Address on which to serve extraction requests EXTRACTOR_ENTITIES_PATH=/var/apps/entity-extractor/data/entities.jsonl Path of file holding entities in jsonlines format EXTRACTOR_ERROR_LOG=STDERR File to log errors to (in JSON format) ` fmt.Fprintf(os.Stderr, helpstring) os.Exit(2) } func getenvDefault(key string, defaultVal string) string { val := os.Getenv(key) if val == "" { val = defaultVal } return val }
Fix include path and ascii / utf8 errors.
#!/usr/bin/python import sys import os import glob #sys.path.append(os.path.join(os.path.dirname(__file__), "gen-py")) sys.path.append(os.path.join(os.path.dirname(__file__),"gen-py/thrift_solr/")) sys.path.append(os.path.dirname(__file__) ) from thrift.transport import TSocket from thrift.server import TServer #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): #print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) #print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TThreadPoolServer(processor, listening_socket) print ("[Server] Started") server.serve()
#!/usr/bin/python import sys import glob sys.path.append("python_scripts/gen-py") sys.path.append("gen-py/thrift_solr/") from thrift.transport import TSocket from thrift.server import TServer #import thrift_solr import ExtractorService import sys import readability import readability def extract_with_python_readability( raw_content ): doc = readability.Document( raw_content ) return [ u'' + doc.short_title(), u'' + doc.summary() ] class ExtractorHandler: def extract_html( self, raw_html ): print raw_html #raw_html = raw_html.encode( 'utf-8' ) ret = extract_with_python_readability( raw_html ) print ret[1] return ret handler = ExtractorHandler() processor = ExtractorService.Processor(handler) listening_socket = TSocket.TServerSocket(port=9090) server = TServer.TThreadPoolServer(processor, listening_socket) print ("[Server] Started") server.serve()
Add Guest for Mail Receiver.
"use strict"; const debug = require("debug")("OSMBC:util:initialize"); const async = require("async"); const logger = require("../config.js").logger; const configModule = require("../model/config.js"); const userModule = require("../model/user.js"); const messageCenter = require("../notification/messageCenter.js"); const mailReceiver = require("../notification/mailReceiver.js"); const slackReceiver = require("../notification/slackReceiver.js"); // do not know where to place this stuff, // so i start here to have one initialisation function, which does all // Initialise Mail Module with all users function startMailReceiver(callback) { debug("startMailReceiver"); userModule.find({ access: "IN('full','guest')" }, function initUsers(err, result) { if (err) { return callback(new Error("Error during User Initialising for Mail " + err.message)); } mailReceiver.initialise(result); logger.info("Mail Receiver initialised."); return callback(); }); } function startSlackReceiver(param, callback) { debug("startSlackReceiver"); slackReceiver.initialise(callback); } exports.initialiseModules = function(callback) { debug("initialiseModules"); async.auto({ configModule: configModule.initialise, messageCenter: ["configModule", function(param, callback) { messageCenter.initialise(callback); }], startMailReceiver: startMailReceiver, startSlackReceiver: ["configModule", startSlackReceiver] }, callback); };
"use strict"; const debug = require("debug")("OSMBC:util:initialize"); const async = require("async"); const logger = require("../config.js").logger; const configModule = require("../model/config.js"); const userModule = require("../model/user.js"); const messageCenter = require("../notification/messageCenter.js"); const mailReceiver = require("../notification/mailReceiver.js"); const slackReceiver = require("../notification/slackReceiver.js"); // do not know where to place this stuff, // so i start here to have one initialisation function, which does all // Initialise Mail Module with all users function startMailReceiver(callback) { debug("startMailReceiver"); userModule.find({ access: "full" }, function initUsers(err, result) { if (err) { return callback(new Error("Error during User Initialising for Mail " + err.message)); } mailReceiver.initialise(result); logger.info("Mail Receiver initialised."); return callback(); }); } function startSlackReceiver(param, callback) { debug("startSlackReceiver"); slackReceiver.initialise(callback); } exports.initialiseModules = function(callback) { debug("initialiseModules"); async.auto({ configModule: configModule.initialise, messageCenter: ["configModule", function(param, callback) { messageCenter.initialise(callback); }], startMailReceiver: startMailReceiver, startSlackReceiver: ["configModule", startSlackReceiver] }, callback); };
Add place to store a user's token
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('email')->unique(); $table->string('password', 60); $table->string('avatar'); $table->string('token'); $table->text('calendar_id'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name')->unique(); $table->string('email')->unique(); $table->string('password', 60); $table->string('avatar'); $table->text('calendar_id'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Fix "Trying to get property of non-object"
@component('mail::message') # Dear {{ '@' . $user->username }}, moderator of [#{{ $category->name }}](https://voten.co/c/{{ $category->name }}?ref=email) During the beta phase, to keep the community clean and active, we are deleting all the inactive channels that haven't had any activities in the last 60 days. Your **#{{ $category->name }}** channel hasn't had any activities in **{{ optional($category->submissions()->orderBy('created_at', 'desc')->first())->created_at->diffInDays() }} days**. Thus, In case you intend to keep your channel alive, please start posting to it. Otherwise, just ignore this email. We'll begin deleting inactive channels a week after the date of sending this email. @component('mail::button', ['url' => config('app.url') . '/c/' . $category->name . '?ref=email']) Go to #{{ $category->name }} @endcomponent Thank you for being a Voten moderator!<br> The Voten Team @component('mail::subcopy') Need help? Check out our [Help Center](https://voten.co/help), ask [community](https://voten.co/c/VotenSupport), or hit us up on Twitter [@voten_co](https://twitter.com/voten_co). Want to give us feedback? Let us know what you think on our [feedback page](https://voten.co/feedback). @endcomponent @endcomponent
@component('mail::message') # Dear {{ '@' . $user->username }}, moderator of [#{{ $category->name }}](https://voten.co/c/{{ $category->name }}?ref=email) During the beta phase, to keep the community clean and active, we are deleting all the inactive channels that haven't had any activities in the last 60 days. Your **#{{ $category->name }}** channel hasn't had any activities in **{{ $category->submissions()->orderBy('created_at', 'desc')->first()->created_at->diffInDays() }} days**. Thus, In case you intend to keep your channel alive, please start posting to it. Otherwise, just ignore this email. We'll begin deleting inactive channels a week after the date of sending this email. @component('mail::button', ['url' => config('app.url') . '/c/' . $category->name . '?ref=email']) Go to #{{ $category->name }} @endcomponent Thank you for being a Voten moderator!<br> The Voten Team @component('mail::subcopy') Need help? Check out our [Help Center](https://voten.co/help), ask [community](https://voten.co/c/VotenSupport), or hit us up on Twitter [@voten_co](https://twitter.com/voten_co). Want to give us feedback? Let us know what you think on our [feedback page](https://voten.co/feedback). @endcomponent @endcomponent
Use `call()` to correctly assign `this` in handler The handler function's `this` should refer to the element to which the listener is bound, rather than the `window` object. This also ensures that `this` is equal to `e.currentTarget`.
/** * Module dependencies. */ var matches = require('matches-selector') , event = require('event'); /** * Delegate event `type` to `selector` * and invoke `fn(e)`. A callback function * is returned which may be passed to `.unbind()`. * * @param {Element} el * @param {String} selector * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, selector, type, fn, capture){ return event.bind(el, type, function(e){ if (matches(e.target, selector)) fn.call(el, e); }, capture); }; /** * Unbind event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.unbind = function(el, type, fn, capture){ event.unbind(el, type, fn, capture); };
/** * Module dependencies. */ var matches = require('matches-selector') , event = require('event'); /** * Delegate event `type` to `selector` * and invoke `fn(e)`. A callback function * is returned which may be passed to `.unbind()`. * * @param {Element} el * @param {String} selector * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, selector, type, fn, capture){ return event.bind(el, type, function(e){ if (matches(e.target, selector)) fn(e); }, capture); }; /** * Unbind event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ exports.unbind = function(el, type, fn, capture){ event.unbind(el, type, fn, capture); };
Remove unused imports in interpeter.
# -*- coding: utf-8 -*- from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
# -*- coding: utf-8 -*- from os.path import dirname, join from .evaluator import evaluate from .parser import parse, unparse, parse_multiple from .types import Environment def interpret(source, env=None): """ Interpret a DIY Lang program statement Accepts a program statement as a string, interprets it, and then returns the resulting DIY Lang expression as string. """ if env is None: env = Environment() return unparse(evaluate(parse(source), env)) def interpret_file(filename, env=None): """ Interpret a DIY Lang file Accepts the name of a DIY Lang file containing a series of statements. Returns the value of the last expression of the file. """ if env is None: env = Environment() with open(filename, 'r') as sourcefile: source = "".join(sourcefile.readlines()) asts = parse_multiple(source) results = [evaluate(ast, env) for ast in asts] return unparse(results[-1])
Update `create_user` method manager to require person
# Django from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, person, password='', **kwargs): user = self.model( email=email, person=person, password='', is_active=True, **kwargs ) user.save(using=self._db) return user def create_superuser(self, email, person, password, **kwargs): user = self.model( email=email, person=person, is_staff=True, is_active=True, **kwargs ) user.set_password(password) user.save(using=self._db) return user
# Django from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password='', **kwargs): user = self.model( email=email, password='', is_active=True, **kwargs ) user.save(using=self._db) return user def create_superuser(self, email, password, **kwargs): user = self.model( email=email, is_staff=True, is_active=True, **kwargs ) user.set_password(password) user.save(using=self._db) return user
Disable flatfile tests until atom tests complete.
#!/usr/bin/python import unittest from firmant.utils import get_module # Import this now to avoid it throwing errors. import pytz from firmant.configuration import settings from test.configuration import suite as configuration_tests from test.datasource.atom import suite as atom_tests from test.plugins.datasource.flatfile.atom import suite as flatfile_atom_tests from test.resolvers import suite as resolvers_tests if __name__ == '__main__': settings.reconfigure('test_settings') for plugin in settings['PLUGINS']: try: mod = get_module(plugin) except ImportError: raise suite = unittest.TestSuite() suite.addTests(configuration_tests) suite.addTests(atom_tests) #suite.addTests(flatfile_atom_tests) suite.addTests(resolvers_tests) unittest.TextTestRunner(verbosity=2).run(suite)
#!/usr/bin/python import unittest from firmant.utils import get_module # Import this now to avoid it throwing errors. import pytz from firmant.configuration import settings from test.configuration import suite as configuration_tests from test.datasource.atom import suite as atom_tests from test.plugins.datasource.flatfile.atom import suite as flatfile_atom_tests from test.resolvers import suite as resolvers_tests if __name__ == '__main__': settings.reconfigure('test_settings') for plugin in settings['PLUGINS']: try: mod = get_module(plugin) except ImportError: raise suite = unittest.TestSuite() suite.addTests(configuration_tests) suite.addTests(atom_tests) suite.addTests(flatfile_atom_tests) suite.addTests(resolvers_tests) unittest.TextTestRunner(verbosity=2).run(suite)
[1.9] Put Components.utils to a constant http://code.google.com/p/fbug/source/detail?r=11472
/* See license.txt for terms of usage */ define([], function() { //********************************************************************************************* // //Constants const Cu = Components.utils; // ********************************************************************************************* // // Firebug Trace - FBTrace var scope = {}; try { Cu["import"]("resource://fbtrace/firebug-trace-service.js", scope); } catch (err) { Cu.reportError("FBTrace is not installed, use empty implementation"); scope.traceConsoleService = { getTracer: function(prefDomain) { var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"]; var TraceObj = {}; for (var i=0; i<TraceAPI.length; i++) TraceObj[TraceAPI[i]] = function() {}; return TraceObj; } }; } // ********************************************************************************************* // return scope.traceConsoleService.getTracer("extensions.firebug"); // ********************************************************************************************* // });
/* See license.txt for terms of usage */ define([], function() { // ********************************************************************************************* // // Firebug Trace - FBTrace var scope = {}; try { Components.utils["import"]("resource://fbtrace/firebug-trace-service.js", scope); } catch (err) { Components.utils.reportError("FBTrace is not installed, use empty implementation"); scope.traceConsoleService = { getTracer: function(prefDomain) { var TraceAPI = ["dump", "sysout", "setScope", "matchesNode", "time", "timeEnd"]; var TraceObj = {}; for (var i=0; i<TraceAPI.length; i++) TraceObj[TraceAPI[i]] = function() {}; return TraceObj; } }; } // ********************************************************************************************* // return scope.traceConsoleService.getTracer("extensions.firebug"); // ********************************************************************************************* // });
Stop passing middlewares array to stack
/** * Builder.js * * @author: Harish Anchu <harishanchu@gmail.com> * @copyright Copyright (c) 2015-2016, QuorraJS. * @license See LICENSE.txt */ var StackedHttpKernel = require('./StackedHttpKernel'); function Builder() { /** * Stores middleware classes * * @type {Array} * @protected */ this.__specs = []; } Builder.prototype.push = function(spec) { if (typeof spec != 'function') { throw new Error("Spec error"); } this.__specs.push(spec); return this; }; Builder.prototype.resolve = function(app) { var next = app; var key; var spec; for(key = this.__specs.length -1; key >= 0; key--) { spec = this.__specs[key]; next = new spec(app, next); } return new StackedHttpKernel(next); }; module.exports = Builder;
/** * Builder.js * * @author: Harish Anchu <harishanchu@gmail.com> * @copyright Copyright (c) 2015-2016, QuorraJS. * @license See LICENSE.txt */ var StackedHttpKernel = require('./StackedHttpKernel'); function Builder() { /** * Stores middleware classes * * @type {Array} * @protected */ this.__specs = []; } Builder.prototype.push = function(spec) { if (typeof spec != 'function') { throw new Error("Spec error"); } this.__specs.push(spec); return this; }; Builder.prototype.resolve = function(app) { var next = app; var middlewares = [app]; var key; var spec; for(key = this.__specs.length -1; key >= 0; key--) { spec = this.__specs[key]; next = new spec(app, next); middlewares.unshift(next); } return new StackedHttpKernel(next, middlewares); }; module.exports = Builder;
Add @AwaitRule to integration test Done to ensure that Arquillian waits for the application to standup properly before executing the test method
/* * Copyright 2016-2017 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.openshift.booster; import java.net.URL; import com.jayway.restassured.RestAssured; import io.openshift.booster.service.GreetingProperties; import org.arquillian.cube.openshift.impl.enricher.AwaitRoute; import org.arquillian.cube.openshift.impl.enricher.RouteURL; import org.jboss.arquillian.junit.Arquillian; import org.junit.Before; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class OpenShiftIT extends AbstractBoosterApplicationTest { @AwaitRoute(path = "/health") @RouteURL("${app.name}") private URL baseURL; @Before public void setup() throws Exception { RestAssured.baseURI = baseURL + "api/greeting"; } protected GreetingProperties getProperties() { return new GreetingProperties(); } }
/* * Copyright 2016-2017 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.openshift.booster; import java.net.URL; import com.jayway.restassured.RestAssured; import io.openshift.booster.service.GreetingProperties; import org.arquillian.cube.openshift.impl.enricher.RouteURL; import org.jboss.arquillian.junit.Arquillian; import org.junit.Before; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class OpenShiftIT extends AbstractBoosterApplicationTest { @RouteURL("${app.name}") private URL baseURL; @Before public void setup() throws Exception { RestAssured.baseURI = baseURL + "api/greeting"; } protected GreetingProperties getProperties() { return new GreetingProperties(); } }
Tag version v1.0.0 -- first extracted version
from distutils.core import setup import os package_data = [] BASE_DIR = os.path.dirname(__file__) walk_generator = os.walk(os.path.join(BASE_DIR, "project_template")) paths_and_files = [(paths, files) for paths, dirs, files in walk_generator] for path, files in paths_and_files: prefix = path[path.find("project_template") + len("project_template/"):] if files: package_data.append(os.path.join(prefix, "*.*")) setup( name="armstrong.templates.tutorial", version="1.0.0", description="The tutorial project for Armstrong", long_description=open("README.rst").read(), author='Texas Tribune & Bay Citizen', author_email='dev@armstrongcms.org', packages=[ "armstrong.templates.tutorial", ], package_dir={ "armstrong.templates.tutorial": "project_template", }, package_data={ "armstrong.templates.tutorial": package_data, }, namespace_packages=[ "armstrong", "armstrong.templates", "armstrong.templates.tutorial", ], entry_points={ "armstrong.templates": [ "tutorial = armstrong.templates.tutorial", ], }, )
from distutils.core import setup import os package_data = [] BASE_DIR = os.path.dirname(__file__) walk_generator = os.walk(os.path.join(BASE_DIR, "project_template")) paths_and_files = [(paths, files) for paths, dirs, files in walk_generator] for path, files in paths_and_files: prefix = path[path.find("project_template") + len("project_template/"):] if files: package_data.append(os.path.join(prefix, "*.*")) setup( name="armstrong.templates.tutorial", version="1.0alpha.0", description="The tutorial project for Armstrong", long_description=open("README.rst").read(), author='Texas Tribune & Bay Citizen', author_email='dev@armstrongcms.org', packages=[ "armstrong.templates.tutorial", ], package_dir={ "armstrong.templates.tutorial": "project_template", }, package_data={ "armstrong.templates.tutorial": package_data, }, namespace_packages=[ "armstrong", "armstrong.templates", "armstrong.templates.tutorial", ], entry_points={ "armstrong.templates": [ "tutorial = armstrong.templates.tutorial", ], }, )
Remove workaround for issue with older python versions.
# Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp> # # 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. import setuptools import ryu.hooks ryu.hooks.save_orig() setuptools.setup(name='ryu', setup_requires=['pbr'], pbr=True)
# Copyright (C) 2011, 2012 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2011 Isaku Yamahata <yamahata at valinux co jp> # # 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. # a bug workaround. http://bugs.python.org/issue15881 try: import multiprocessing except ImportError: pass import setuptools import ryu.hooks ryu.hooks.save_orig() setuptools.setup(name='ryu', setup_requires=['pbr'], pbr=True)
Read what you're getting up front
import Rx from 'rx'; import {h} from '@cycle/dom'; export function labeledSlider(responses) { const events = intent(responses.DOM), DOM = view(model(responses, events)); return {DOM, events}; function intent(DOM) { return { newValue: DOM.select('.slider').events('input') .map(ev => ev.target.value) }; } function model({props}, {newValue}) { const initialValue$ = props.get('initial').first(), value$ = initialValue$.concat(newValue), props$ = props.getAll(); return Rx.Observable .combineLatest(props$, value$, (props, value) => ({props, value})); } function view(state$) { return state$ .map(({props: {label, unit, min, max}, value }) => h('div.labeled-slider', [ h('span.label', [label + ' ' + value + unit]), h('input.slider', {type: 'range', min, max, value}) ])); } }
import Rx from 'rx'; import {h} from '@cycle/dom'; export function labeledSlider(responses) { function intent(DOM) { return { newValue: DOM.select('.slider').events('input') .map(ev => ev.target.value) }; } function model({props}, {newValue}) { const initialValue$ = props.get('initial').first(), value$ = initialValue$.concat(newValue), props$ = props.getAll(); return Rx.Observable .combineLatest(props$, value$, (props, value) => ({props, value})); } function view(state$) { return state$ .map(({props: {label, unit, min, max}, value }) => h('div.labeled-slider', [ h('span.label', [label + ' ' + value + unit]), h('input.slider', {type: 'range', min, max, value}) ])); } const events = intent(responses.DOM), DOM = view(model(responses, events)); return {DOM, events}; }
Check that circle ci catches failures.
package com.realkinetic.app.gabby.repository.downstream.memory; import com.realkinetic.app.gabby.config.BaseConfig; import com.realkinetic.app.gabby.config.DefaultConfig; import com.realkinetic.app.gabby.config.MemoryConfig; import com.realkinetic.app.gabby.repository.BaseDownstream; import com.realkinetic.app.gabby.repository.DownstreamSubscription; import org.junit.Assert; import org.junit.Test; import java.util.logging.Logger; public class MemoryDownstreamTest extends BaseDownstream { private static final Logger LOG = Logger.getLogger(MemoryDownstreamTest.class.getName()); @Override protected DownstreamSubscription getDownstream() { final BaseConfig config = (BaseConfig) DefaultConfig.load(); config.setDownstreamTimeout(1); final MemoryConfig memoryConfig = new MemoryConfig(); memoryConfig.setMaxAccesses(10); config.setMemoryConfig(memoryConfig); return new MemoryDownstream(config, mm -> true); } @Override protected void createTopic(String topic) { // just like redis, this simply doesn't matter } @Test public void testFail() { Assert.fail(); } }
package com.realkinetic.app.gabby.repository.downstream.memory; import com.realkinetic.app.gabby.config.BaseConfig; import com.realkinetic.app.gabby.config.DefaultConfig; import com.realkinetic.app.gabby.config.MemoryConfig; import com.realkinetic.app.gabby.repository.BaseDownstream; import com.realkinetic.app.gabby.repository.DownstreamSubscription; import java.util.logging.Logger; public class MemoryDownstreamTest extends BaseDownstream { private static final Logger LOG = Logger.getLogger(MemoryDownstreamTest.class.getName()); @Override protected DownstreamSubscription getDownstream() { final BaseConfig config = (BaseConfig) DefaultConfig.load(); config.setDownstreamTimeout(1); final MemoryConfig memoryConfig = new MemoryConfig(); memoryConfig.setMaxAccesses(10); config.setMemoryConfig(memoryConfig); return new MemoryDownstream(config, mm -> true); } @Override protected void createTopic(String topic) { // just like redis, this simply doesn't matter } }
Make filter_by_district more strict - don't show anything to unconfigured users
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): # superusers and managers see everything if (user.is_superuser or hasattr(user, 'coordinator') and user.coordinator.is_manager): return qs # don't show anything to unconfigured users if not hasattr(user, 'coordinator') or not user.coordinator.district: return qs.none() kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs)
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from locations.models import District class Coordinator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_manager = models.BooleanField() district = models.ForeignKey(District, verbose_name=_('District'), blank=True, null=True) def filter_by_district(qs, user, lookup): if (user.is_superuser or not hasattr(user, 'coordinator') or user.coordinator.is_manager): return qs kwargs = { lookup: user.coordinator.district } return qs.filter(**kwargs)
Make server listen on port 80
require('app-module-path').addPath(__dirname); var express = require('express'); var passport = require('passport'); var session = require('express-session'); var app = express(); var inventory_router = require('api/inventory.js'); var reservations_router = require('api/reservations.js'); var auth = require('api/auth.js'); var users_router = require('api/users.js'); var auth_router = auth.router; var ensureAuthenticated = auth.ensureAuthenticated; /* Setup session middleware */ app.use(session({ secret: 'a secret key', cookie: { secure: false } })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', auth_router); /* Auth requests aren't behind the authentication barrier themselves */ app.use('/public', express.static('public')); /* For serving the login page, etc. */ app.get('/', (req, res) => { if(req.user) { res.redirect('/inventory.html'); } else { res.redirect('/public/login.html'); } }); /* API requests below this need to be authenticated */ app.use(ensureAuthenticated); app.use('/api', users_router); app.use('/api', inventory_router); app.use('/api', reservations_router); app.use(express.static('static')); app.listen(80, () => { console.log("Server listening on port 3000."); });
require('app-module-path').addPath(__dirname); var express = require('express'); var passport = require('passport'); var session = require('express-session'); var app = express(); var inventory_router = require('api/inventory.js'); var reservations_router = require('api/reservations.js'); var auth = require('api/auth.js'); var users_router = require('api/users.js'); var auth_router = auth.router; var ensureAuthenticated = auth.ensureAuthenticated; /* Setup session middleware */ app.use(session({ secret: 'a secret key', cookie: { secure: false } })); app.use(passport.initialize()); app.use(passport.session()); app.use('/api', auth_router); /* Auth requests aren't behind the authentication barrier themselves */ app.use('/public', express.static('public')); /* For serving the login page, etc. */ app.get('/', (req, res) => { if(req.user) { res.redirect('/inventory.html'); } else { res.redirect('/public/login.html'); } }); /* API requests below this need to be authenticated */ app.use(ensureAuthenticated); app.use('/api', users_router); app.use('/api', inventory_router); app.use('/api', reservations_router); app.use(express.static('static')); app.listen(3000, () => { console.log("Server listening on port 3000."); });
[Readability] Rename method name (avoid abbreviation) AND: * Remove redundant comment + update doc block comment. * Change "isAlreadyExecuted" method visibility to private (don't need to be public!).
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Include / Class */ namespace PH7; use PH7\Framework\Http\Http; use Teapot\StatusCode; abstract class Cron extends Framework\Cron\Run\Cron { public function __construct() { parent::__construct(); $this->isAlreadyExecuted(); } /** * Check the delay and see if the cron has already been executed. * * @return void If cron has already been executed, the script stops with exit() function and an explanatory message. * * @throws Framework\Http\Exception */ private function isAlreadyExecuted() { if (!$this->checkDelay()) { Http::setHeadersByCode(StatusCode::FORBIDDEN); exit(t('This cron has already been executed.')); } } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / Include / Class */ namespace PH7; use PH7\Framework\Http\Http; use Teapot\StatusCode; abstract class Cron extends Framework\Cron\Run\Cron { public function __construct() { parent::__construct(); // Check delay $this->isAlreadyExec(); } /** * Check if the cron has already been executed. * * @return void If cron has already been executed, the script stops with exit() function and an explanatory message. * * @throws Framework\Http\Exception */ public function isAlreadyExec() { if (!$this->checkDelay()) { Http::setHeadersByCode(StatusCode::FORBIDDEN); exit(t('This cron has already been executed.')); } } }
Remove unused array of model
var MaapError = require("./utils/MaapError"); const EventEmitter = require("events"); const util = require("util"); /** * Set dsl's store and point to access at the any engine defined in MaaS. * Token inherits from EventEmitter. Any engine create own events to * comunicate with the other engines. The only once own event of Token is * "update". The event "update" is emit when the new model to be register * into the token. The event send the follow object : * ``` * { * models: Model[] * } * ``` * `status.models` is the array with the last models loaded. * * * @history * | Name | Action performed | Date | * | --- | --- | --- | * | Andrea Mantovani | Create class | 2016-06-01 | * * @author Andrea Mantovani * @license MIT */ var Token = function () { this.status = { models: [] }; EventEmitter.call(this); }; util.inherits(Token, EventEmitter); /** * @description * Send the notifies for each observer attached at the token with the model loaded. * @param model {Model} * The model to store */ Token.prototype.register = function (model) { this.status.model = model; this.emit("update", this.status); }; module.exports = Token;
var MaapError = require("./utils/MaapError.js"); const EventEmitter = require('events'); const util = require('util'); /** * Set dsl's store and point to access at the any engine defined in MaaS. * Token inherits from EventEmitter. Any engine create own events to * comunicate with the other engines. The only once own event of Token is * "update". The event "update" is emit when the new model to be register * into the token. * * @history * | Name | Action performed | Date | * | --- | --- | --- | * | Andrea Mantovani | Create class | 2016-06-01 | * * @author Andrea Mantovani * @license MIT */ var Token = function () { this.modelRegistry = []; this.status = { model: [] }; EventEmitter.call(this); }; util.inherits(Token, EventEmitter); /** * @description * Extract the models stored in the token. * @return {Model[]} */ Token.prototype.extract = function () { return this.modelRegistry; }; /** * @description * Save into this token the model extracted from the dsl file and * send the notifies for each observer attached at the token. * @param model {Model} * The model to store */ Token.prototype.register = function (model) { this.modelRegistry.push(model); this.status.model = model; this.emit("update"); }; module.exports = Token;
Add optional parameters for symfony2/cache-clear Add optional parameters for symfony2/cache-clear task like --no-warmup.
<?php /* * This file is part of the Magallanes package. * * (c) Andrés Montañez <andres@andresmontanez.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mage\Task\BuiltIn\Symfony2; use Mage\Task\BuiltIn\Symfony2\SymfonyAbstractTask; /** * Task for Clearing the Cache * * Example of usage: * symfony2/cache-clear: { env: dev } * symfony2/cache-clear: { env: dev, optional: --no-warmup } * * @author Andrés Montañez <andres@andresmontanez.com> * @author Samuel Chiriluta <samuel4x4@gmail.com> */ class CacheClearTask extends SymfonyAbstractTask { /** * (non-PHPdoc) * @see \Mage\Task\AbstractTask::getName() */ public function getName() { return 'Symfony v2 - Cache Clear [built-in]'; } /** * Clears the Cache * @see \Mage\Task\AbstractTask::run() */ public function run() { // Options $env = $this->getParameter('env', 'dev'); $optional = $this->getParameter('optional', ''); $command = $this->getAppPath() . ' cache:clear --env=' . $env . ' ' . $optional; $result = $this->runCommand($command); return $result; } }
<?php /* * This file is part of the Magallanes package. * * (c) Andrés Montañez <andres@andresmontanez.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mage\Task\BuiltIn\Symfony2; use Mage\Task\BuiltIn\Symfony2\SymfonyAbstractTask; /** * Task for Clearing the Cache * * @author Andrés Montañez <andres@andresmontanez.com> */ class CacheClearTask extends SymfonyAbstractTask { /** * (non-PHPdoc) * @see \Mage\Task\AbstractTask::getName() */ public function getName() { return 'Symfony v2 - Cache Clear [built-in]'; } /** * Clears the Cache * @see \Mage\Task\AbstractTask::run() */ public function run() { // Options $env = $this->getParameter('env', 'dev'); $command = $this->getAppPath() . ' cache:clear --env=' . $env; $result = $this->runCommand($command); return $result; } }
Use pathlib to read ext.conf
import pathlib from mopidy import config, exceptions, ext __version__ = "1.2.2" class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["upnp_browse_limit"] = config.Integer(minimum=0) schema["upnp_lookup_limit"] = config.Integer(minimum=0) schema["upnp_search_limit"] = config.Integer(minimum=0) schema["dbus_start_session"] = config.String() return schema def setup(self, registry): from .backend import dLeynaBackend registry.add("backend", dLeynaBackend) def validate_environment(self): try: import dbus # noqa except ImportError: raise exceptions.ExtensionError("Cannot import dbus")
import os from mopidy import config, exceptions, ext __version__ = "1.2.2" class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return config.read(os.path.join(os.path.dirname(__file__), "ext.conf")) def get_config_schema(self): schema = super().get_config_schema() schema["upnp_browse_limit"] = config.Integer(minimum=0) schema["upnp_lookup_limit"] = config.Integer(minimum=0) schema["upnp_search_limit"] = config.Integer(minimum=0) schema["dbus_start_session"] = config.String() return schema def setup(self, registry): from .backend import dLeynaBackend registry.add("backend", dLeynaBackend) def validate_environment(self): try: import dbus # noqa except ImportError: raise exceptions.ExtensionError("Cannot import dbus")
Add missing import of insecurity lib
const utils = require('../lib/utils') const insecurity = require('../lib/insecurity') const challenges = require('../data/datacache').challenges const db = require('../data/mongodb') module.exports = function trackOrder () { return (req, res) => { const id = insecurity.sanitizeProcessExit(utils.trunc(decodeURIComponent(req.params.id), 40)) if (utils.notSolved(challenges.reflectedXssChallenge) && utils.contains(id, '<iframe src="javascript:alert(`xss`)">')) { utils.solve(challenges.reflectedXssChallenge) } db.orders.find({ $where: "this.orderId === '" + id + "'" }).then(order => { const result = utils.queryResultToJson(order) if (utils.notSolved(challenges.noSqlOrdersChallenge) && result.data.length > 1) { utils.solve(challenges.noSqlOrdersChallenge) } if (result.data[0] === undefined) { result.data[0] = { orderId: id } } res.json(result) }, () => { res.status(400).json({ error: 'Wrong Param' }) }) } }
const utils = require('../lib/utils') const challenges = require('../data/datacache').challenges const db = require('../data/mongodb') module.exports = function trackOrder () { return (req, res) => { const id = insecurity.sanitizeProcessExit(utils.trunc(decodeURIComponent(req.params.id), 40)) if (utils.notSolved(challenges.reflectedXssChallenge) && utils.contains(id, '<iframe src="javascript:alert(`xss`)">')) { utils.solve(challenges.reflectedXssChallenge) } db.orders.find({ $where: "this.orderId === '" + id + "'" }).then(order => { const result = utils.queryResultToJson(order) if (utils.notSolved(challenges.noSqlOrdersChallenge) && result.data.length > 1) { utils.solve(challenges.noSqlOrdersChallenge) } if (result.data[0] === undefined) { result.data[0] = { orderId: id } } res.json(result) }, () => { res.status(400).json({ error: 'Wrong Param' }) }) } }
Change 'share' method in service provider to 'singleton' to support L5.4
<?php namespace Rossedman\Teamwork; use GuzzleHttp\Client as Guzzle; use Illuminate\Support\ServiceProvider; class TeamworkServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton('rossedman.teamwork', function($app) { $client = new \Rossedman\Teamwork\Client(new Guzzle, $app['config']->get('services.teamwork.key'), $app['config']->get('services.teamwork.url') ); return new \Rossedman\Teamwork\Factory($client); }); $this->app->bind('Rossedman\Teamwork\Factory', 'rossedman.teamwork'); } }
<?php namespace Rossedman\Teamwork; use GuzzleHttp\Client as Guzzle; use Illuminate\Support\ServiceProvider; class TeamworkServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app['rossedman.teamwork'] = $this->app->share(function($app) { $client = new \Rossedman\Teamwork\Client(new Guzzle, $app['config']->get('services.teamwork.key'), $app['config']->get('services.teamwork.url') ); return new \Rossedman\Teamwork\Factory($client); }); $this->app->bind('Rossedman\Teamwork\Factory', 'rossedman.teamwork'); } }
Revert "Prevent link processing for dropdowns" This reverts commit 2cb937a4405627c94c05c391dd610b85ba7e1cad.
'use strict'; /** * client **/ /** * client.common **/ /*global $, _, nodeca, window, document*/ /** * client.common.init() * * Assigns all necessary event listeners and handlers. * * * ##### Example * * nodeca.client.common.init(); **/ module.exports = function () { nodeca.io.init(); $(function () { // Bootstrap.Collapse calls e.preventDefault() only when there's no // data-target attribute. We don't want URL to be changed, so we are // forcing prevention of default behavior. $('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) { e.preventDefault(); }); // // Observe quicksearch focus to tweak icon style // $('.navbar-search .search-query') .focus(function (){ $(this).next('div').addClass('focused'); }) .blur(function (){ $(this).next('div').removeClass('focused'); }); }); // history intercepts clicks on all `a` elements, // so we initialize it as later as possible to have // "lowest" priority of handlers nodeca.client.common.init.history(); };
'use strict'; /** * client **/ /** * client.common **/ /*global $, _, nodeca, window, document*/ /** * client.common.init() * * Assigns all necessary event listeners and handlers. * * * ##### Example * * nodeca.client.common.init(); **/ module.exports = function () { nodeca.io.init(); $(function () { // Bootstrap.Collapse calls e.preventDefault() only when there's no // data-target attribute. We don't want URL to be changed, so we are // forcing prevention of default behavior. $('body').on('click.collapse.data-api', '[data-toggle=collapse]', function ( e ) { e.preventDefault(); }); // Bootstrap.Dropdown don't calls e.preventDefault() by default $('body').on('click.dropdown.data-api', '[data-toggle=dropdown]', function ( e ) { e.preventDefault(); }); // // Observe quicksearch focus to tweak icon style // $('.navbar-search .search-query') .focus(function (){ $(this).next('div').addClass('focused'); }) .blur(function (){ $(this).next('div').removeClass('focused'); }); }); // history intercepts clicks on all `a` elements, // so we initialize it as later as possible to have // "lowest" priority of handlers nodeca.client.common.init.history(); };
Fix lambda invoke with no payload
'use strict' const { config, Lambda } = require('aws-sdk') const { stringify } = JSON config.update({ accessKeyId: 'ABC', secretAccessKey: 'SECRET', }) const lambda = new Lambda({ apiVersion: '2015-03-31', endpoint: 'http://localhost:3000', }) exports.noPayload = async function noPayload() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.testHandler = async function testHandler() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', Payload: stringify({ foo: 'bar' }), } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.invokedHandler = async function invokedHandler(event) { return { event, } }
'use strict' const { config, Lambda } = require('aws-sdk') const { stringify } = JSON config.update({ accessKeyId: 'ABC', secretAccessKey: 'SECRET', }) const lambda = new Lambda({ apiVersion: '2015-03-31', endpoint: 'http://localhost:3000', }) exports.noPayload = async function noPayload() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.testHandler = async function testHandler() { const params = { FunctionName: 'lambda-invoke-tests-dev-invokedHandler', InvocationType: 'RequestResponse', Payload: stringify({ event: { foo: 'bar' } }), } const response = await lambda.invoke(params).promise() return { body: stringify(response), statusCode: 200, } } exports.invokedHandler = async function invokedHandler(event) { return { event, } }
Use .code instead of .name for type references in code bodies
package de.japkit.roo.japkit.web; import org.springframework.format.FormatterRegistrar; import org.springframework.format.FormatterRegistry; import de.japkit.annotations.ParamNames; import de.japkit.metaannotations.Method; import de.japkit.metaannotations.Template; import de.japkit.roo.base.web.EntityConverterUtil; import de.japkit.roo.base.web.LabelProvider; @Template public abstract class ControllerFormatterMembers implements FormatterRegistrar, LabelProvider<FormBackingObject> { @Method(imports={EntityConverterUtil.class} , bodyCode="EntityConverterUtil.registerConverters(#{fbo.code}.class, registry, crudOperations(), this);") @ParamNames("registry") @Override public void registerFormatters(FormatterRegistry registry) { //EntityConverterUtil.registerConverters(FormBackingObject.class, registry, crudOperations(), this); } //TODO @Method(bodyCode="return \"ID: \" + entity.getId();") @Override @ParamNames("entity") public String getLabel(FormBackingObject entity) { return null; } }
package de.japkit.roo.japkit.web; import org.springframework.format.FormatterRegistrar; import org.springframework.format.FormatterRegistry; import de.japkit.annotations.ParamNames; import de.japkit.metaannotations.Method; import de.japkit.metaannotations.Template; import de.japkit.roo.base.web.EntityConverterUtil; import de.japkit.roo.base.web.LabelProvider; @Template public abstract class ControllerFormatterMembers implements FormatterRegistrar, LabelProvider<FormBackingObject> { @Method(imports={EntityConverterUtil.class} , bodyCode="EntityConverterUtil.registerConverters(#{fbo.name}.class, registry, crudOperations(), this);") @ParamNames("registry") @Override public void registerFormatters(FormatterRegistry registry) { //EntityConverterUtil.registerConverters(FormBackingObject.class, registry, crudOperations(), this); } //TODO @Method(bodyCode="return \"ID: \" + entity.getId();") @Override @ParamNames("entity") public String getLabel(FormBackingObject entity) { return null; } }
Hide decryption success dialog from screen recorders * MOPPAND-610
package ee.ria.DigiDoc.android.utils.widget; import android.app.Dialog; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import androidx.annotation.NonNull; import ee.ria.DigiDoc.R; import ee.ria.DigiDoc.android.Activity; import ee.ria.DigiDoc.android.utils.SecureUtil; public class NotificationDialog extends Dialog { public NotificationDialog(@NonNull Activity context) { super(context); SecureUtil.markAsSecure(getWindow()); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); setContentView(R.layout.success_notification_dialog); Button okButton = findViewById(R.id.okButton); okButton.setOnClickListener(v -> { CheckBox checkBox = (CheckBox) findViewById(R.id.successNotificationDontShowAgain); if (checkBox.isChecked()) { context.getSettingsDataStore().setShowSuccessNotification(false); } dismiss(); }); } }
package ee.ria.DigiDoc.android.utils.widget; import android.app.Dialog; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import androidx.annotation.NonNull; import ee.ria.DigiDoc.R; import ee.ria.DigiDoc.android.Activity; public class NotificationDialog extends Dialog { public NotificationDialog(@NonNull Activity context) { super(context); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); setContentView(R.layout.success_notification_dialog); Button okButton = findViewById(R.id.okButton); okButton.setOnClickListener(v -> { CheckBox checkBox = (CheckBox) findViewById(R.id.successNotificationDontShowAgain); if (checkBox.isChecked()) { context.getSettingsDataStore().setShowSuccessNotification(false); } dismiss(); }); } }
Print error if it exists
package cli import ( "bytes" "testing" ) func TestFlagC(t *testing.T) { var in, out, err bytes.Buffer c := CLI{ In: &in, Out: &out, Err: &err, } args := []string{"-c", "echo aaa"} code := c.Run(args) if code != 0 { t.Errorf("Run: got %v, want %v", code, 0) } if got, want := out.String(), "aaa\n"; got != want { t.Errorf("output: got %v, want %v", got, want) } if e := err.String(); e != "" { t.Errorf("error: %v", e) } } func TestArgs(t *testing.T) { var in, out, err bytes.Buffer c := CLI{ In: &in, Out: &out, Err: &err, } args := []string{"testdata/basic.coco"} code := c.Run(args) if code != 0 { t.Errorf("Run: got %v, want %v", code, 0) } if got, want := out.String(), "aaa\nbbb\n"; got != want { t.Errorf("output: got %v, want %v", got, want) } if e := err.String(); e != "" { t.Errorf("error: %v", e) } }
package cli import ( "bytes" "testing" ) func TestFlagC(t *testing.T) { var in, out, err bytes.Buffer c := CLI{ In: &in, Out: &out, Err: &err, } args := []string{"-c", "echo aaa"} code := c.Run(args) if code != 0 { t.Errorf("Run: got %v, want %v", code, 0) } if got, want := out.String(), "aaa\n"; got != want { t.Errorf("output: got %v, want %v", got, want) } } func TestArgs(t *testing.T) { var in, out, err bytes.Buffer c := CLI{ In: &in, Out: &out, Err: &err, } args := []string{"testdata/basic.coco"} code := c.Run(args) if code != 0 { t.Errorf("Run: got %v, want %v", code, 0) } if got, want := out.String(), "aaa\nbbb\n"; got != want { t.Errorf("output: got %v, want %v", got, want) } }
Use long instead of Long when appropriate
package cgeo.geocaching; import java.util.ArrayList; import java.util.List; public class cgSearch { private long id; private List<String> geocodes = new ArrayList<String>(); public String error = null; public String url = ""; public String[] viewstates = null; public int totalCnt = 0; public cgSearch() { id = System.currentTimeMillis(); // possible collisions here - not guaranteed to be unique } public long getCurrentId() { return id; } public List<String> getGeocodes() { return geocodes; } public int getCount() { return geocodes.size(); } public void addGeocode(String geocode) { if (geocodes == null) { geocodes = new ArrayList<String>(); } geocodes.add(geocode); } }
package cgeo.geocaching; import java.util.ArrayList; import java.util.List; public class cgSearch { private Long id = null; private List<String> geocodes = new ArrayList<String>(); public String error = null; public String url = ""; public String[] viewstates = null; public int totalCnt = 0; public cgSearch() { id = System.currentTimeMillis(); // possible collisions here - not guaranteed to be unique } public Long getCurrentId() { return id; } public List<String> getGeocodes() { return geocodes; } public int getCount() { return geocodes.size(); } public void addGeocode(String geocode) { if (geocodes == null) { geocodes = new ArrayList<String>(); } geocodes.add(geocode); } }
Move Journal to it's own repo.
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.wire; import org.jetbrains.annotations.NotNull; @FunctionalInterface public interface WriteMarshallable { WriteMarshallable EMPTY = wire -> { // nothing }; /** * Write data to the wire * * @param wire to write to. */ void writeMarshallable(@NotNull WireOut wire); }
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.wire; @FunctionalInterface public interface WriteMarshallable { WriteMarshallable EMPTY = wire -> { // nothing }; /** * Write data to the wire * * @param wire to write to. */ void writeMarshallable(WireOut wire); }
Add to download links ng-csv
var path = require('path'); var rootPath = path.normalize(__dirname + '/../../'); module.exports = { local: { baseUrl: 'http://localhost:3030', db: 'mongodb://localhost/rp_local', rootPath: rootPath, port: process.env.PORT || 3030 }, staging : { baseUrl: 'http://dev.resourceprojects.org', //db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true', db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true', rootPath: rootPath, port: process.env.PORT || 80 } };
var path = require('path'); var rootPath = path.normalize(__dirname + '/../../'); module.exports = { local: { baseUrl: 'http://localhost:3051', db: 'mongodb://localhost/rp_local', rootPath: rootPath, port: process.env.PORT || 3051 }, staging : { baseUrl: 'http://dev.resourceprojects.org', //db: '@aws-us-east-1-portal.14.dblayer.com:10669/rp_dev?ssl=true', db: '@aws-us-east-1-portal.14.dblayer.com:10669,aws-us-east-1-portal.13.dblayer.com:10499/rp_dev?ssl=true', rootPath: rootPath, port: process.env.PORT || 80 } };
Read datadict file as-is, without type-guessing
import pandas as pd def load_datadict(filepath, trim_index=True, trim_all=False): df = pd.read_csv(filepath, index_col=0, dtype=object) if trim_index: df.index = df.index.to_series().str.strip() if trim_all: df = df.applymap(lambda x: x.strip() if type(x) is str else x) return df def insert_rows_at(main_df, index_name, inserted_df, insert_before=False): # Not checking if index exists because that will be apparent from error # NOTE: This will not work with duplicate indices pre_df = main_df.loc[:index_name] post_df = main_df.loc[index_name:] # Both pre_ and post_ contain the value at index_name, so one needs to # drop it if not insert_before: pre_df = pre_df.drop(index_name) else: post_df = post_df.drop(index_name) return pd.concat([pre_df, inserted_df, post_df], axis=0)
import pandas as pd def load_datadict(filepath, trim_index=True, trim_all=False): df = pd.read_csv(filepath, index_col=0) if trim_index: df.index = df.index.to_series().str.strip() if trim_all: df = df.applymap(lambda x: x.strip() if type(x) is str else x) return df def insert_rows_at(main_df, index_name, inserted_df, insert_before=False): # Not checking if index exists because that will be apparent from error # NOTE: This will not work with duplicate indices pre_df = main_df.loc[:index_name] post_df = main_df.loc[index_name:] # Both pre_ and post_ contain the value at index_name, so one needs to # drop it if not insert_before: pre_df = pre_df.drop(index_name) else: post_df = post_df.drop(index_name) return pd.concat([pre_df, inserted_df, post_df], axis=0)
Add factory to avoid referring to impl classes from other modules
/******************************************************************************** * Copyright (c) 2019 Stephane Bastian * * This program and the accompanying materials are made available under the 2 * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 3 * * Contributors: 4 * Stephane Bastian - initial API and implementation ********************************************************************************/ package io.vertx.ext.auth.authorization; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.MultiMap; import io.vertx.ext.auth.User; import io.vertx.ext.auth.authorization.impl.AuthorizationContextImpl; /** * The AuthorizationContext contains properties that can be used to match * authorizations. * * @author <a href="mail://stephane.bastian.dev@gmail.com">Stephane Bastian</a> * */ @VertxGen public interface AuthorizationContext { /** * Factory for Authorization Context * @param user a user * @return a AuthorizationContext instance */ static AuthorizationContext create(User user) { return new AuthorizationContextImpl(user); } /** * Get the authenticated user * * @return the user */ User user(); /** * @return a Multimap containing variable names and values that can be resolved * at runtime by {@link Authorization}Authorizations */ MultiMap variables(); }
/******************************************************************************** * Copyright (c) 2019 Stephane Bastian * * This program and the accompanying materials are made available under the 2 * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 3 * * Contributors: 4 * Stephane Bastian - initial API and implementation ********************************************************************************/ package io.vertx.ext.auth.authorization; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.MultiMap; import io.vertx.ext.auth.User; /** * The AuthorizationContext contains properties that can be used to match * authorizations. * * @author <a href="mail://stephane.bastian.dev@gmail.com">Stephane Bastian</a> * */ @VertxGen public interface AuthorizationContext { /** * Get the authenticated user * * @return the user */ User user(); /** * @return a Multimap containing variable names and values that can be resolved * at runtime by {@link Authorization}Authorizations */ MultiMap variables(); }
[Taxon][Image] Add validation for taxon image code uniqueness
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Core\Model; use Sylius\Component\Resource\Model\CodeAwareInterface; use Sylius\Component\Resource\Model\ResourceInterface; /** * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com> */ interface ImageInterface extends ResourceInterface, CodeAwareInterface { /** * @return bool */ public function hasFile(); /** * @return null|\SplFileInfo */ public function getFile(); /** * @param \SplFileInfo $file */ public function setFile(\SplFileInfo $file); /** * @return string */ public function getPath(); /** * @param string $path */ public function setPath($path); /** * @return ImageAwareInterface */ public function getOwner(); /** * @param ImageAwareInterface $owner */ public function setOwner(ImageAwareInterface $owner = null); }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Component\Core\Model; use Sylius\Component\Resource\Model\ResourceInterface; use Sylius\Component\Resource\Model\TimestampableInterface; /** * @author Grzegorz Sadowski <grzegorz.sadowski@lakion.com> */ interface ImageInterface extends ResourceInterface { /** * @return string */ public function getCode(); /** * @param string $code */ public function setCode($code); /** * @return bool */ public function hasFile(); /** * @return null|\SplFileInfo */ public function getFile(); /** * @param \SplFileInfo $file */ public function setFile(\SplFileInfo $file); /** * @return string */ public function getPath(); /** * @param string $path */ public function setPath($path); /** * @return ImageAwareInterface */ public function getOwner(); /** * @param ImageAwareInterface $owner */ public function setOwner(ImageAwareInterface $owner = null); }
Remove code that was causing a problem running syncdb. Code seems to be redundant anyway.
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') # # resource model # class Resource(models.Model): path = models.CharField(max_length=128) content = models.TextField(blank=True) content_type = models.CharField(max_length=128, blank=True) class Meta: ordering = ('path',) def __unicode__(self): return self.path def save(self, **kwargs): self.path = self.path.strip('/') if not self.content_type: self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain' super(Resource, self).save(**kwargs) # # update resources when models are saved # def save_handler(sender, **kwargs): reg = kwargs['instance'] wellknown.register( reg.path, content=reg.content, content_type=reg.content_type, update=True ) post_save.connect(save_handler, sender=Resource)
from django.db import models from django.db.models.signals import post_save import mimetypes import wellknown # # create default host-meta handler # from wellknown.resources import HostMeta wellknown.register('host-meta', handler=HostMeta(), content_type='application/xrd+xml') # # resource model # class Resource(models.Model): path = models.CharField(max_length=128) content = models.TextField(blank=True) content_type = models.CharField(max_length=128, blank=True) class Meta: ordering = ('path',) def __unicode__(self): return self.path def save(self, **kwargs): self.path = self.path.strip('/') if not self.content_type: self.content_type = mimetypes.guess_type(self.path)[0] or 'text/plain' super(Resource, self).save(**kwargs) # # update resources when models are saved # def save_handler(sender, **kwargs): reg = kwargs['instance'] wellknown.register( reg.path, content=reg.content, content_type=reg.content_type, update=True ) post_save.connect(save_handler, sender=Resource) # # cache resources # for res in Resource.objects.all(): wellknown.register(res.path, content=res.content, content_type=res.content_type)
Test DatadogMetricsBackend against datadog's get_hostname This fixes tests in Travis since the hostname returned is different
from __future__ import absolute_import from mock import patch from datadog.util.hostname import get_hostname from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=get_hostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=get_hostname(), )
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('datadog.threadstats.base.ThreadStats.increment') def test_incr(self, mock_incr): self.backend.incr('foo', instance='bar') mock_incr.assert_called_once_with( 'sentrytest.foo', 1, tags=['instance:bar'], host=socket.gethostname(), ) @patch('datadog.threadstats.base.ThreadStats.timing') def test_timing(self, mock_timing): self.backend.timing('foo', 30, instance='bar') mock_timing.assert_called_once_with( 'sentrytest.foo', 30, sample_rate=1, tags=['instance:bar'], host=socket.gethostname(), )
Use enum instead of boolean to hold state.
package dk.kleistsvendsen; import com.google.inject.Inject; public class GameTimer implements IGameTimer { private ITicSource ticSource_; private long startTic_; private long pauseTic_; private enum State { IDLE, PAUSED, RUNNING } private State running_; @Inject public GameTimer(ITicSource ticSource) { running_ = State.IDLE; ticSource_ = ticSource; startTic_ = 0; pauseTic_ = 0; } @Override public long timePlayed() { if (running_ == State.RUNNING) { return ticSource_.tic() -startTic_; } else { return pauseTic_ - startTic_; } } @Override public void pauseTimer() { pauseTic_ = ticSource_.tic(); running_ = State.PAUSED; } @Override public void startTimer() { running_ = State.RUNNING; ticSource_.tic(); } @Override public void resetTimer() { } }
package dk.kleistsvendsen; import com.google.inject.Inject; public class GameTimer implements IGameTimer { private ITicSource ticSource_; private long startTic_; private long pauseTic_; private boolean running_; @Inject public GameTimer(ITicSource ticSource) { running_ = false; ticSource_ = ticSource; startTic_ = 0; pauseTic_ = 0; } @Override public long timePlayed() { if (running_) { return ticSource_.tic() -startTic_; } else { return pauseTic_ - startTic_; } } @Override public void pauseTimer() { pauseTic_ = ticSource_.tic(); running_ = false; } @Override public void startTimer() { running_ = true; ticSource_.tic(); } @Override public void resetTimer() { } }
Install url from the right place.
import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "nanospider", version = "0.1.0", author = "Andrew Pendleton", author_email = "apendleton@sunlightfoundation.com", description = "A tiny caching link-follower built on gevent, lxml, and scrapelib", license = "BSD", keywords = "spider gevent lxml scrapelib", url = "http://github.com/sunlightlabs/nanospider/", packages=find_packages(), long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], install_requires = [ "requests", "gevent", "scrapelib", "lxml", "url>=0.1.3", ], dependency_links=[ "git+https://github.com/seomoz/url-py.git#egg=url-0.1.3", ], )
import os from setuptools import setup, find_packages # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "nanospider", version = "0.1.0", author = "Andrew Pendleton", author_email = "apendleton@sunlightfoundation.com", description = "A tiny caching link-follower built on gevent, lxml, and scrapelib", license = "BSD", keywords = "spider gevent lxml scrapelib", url = "http://github.com/sunlightlabs/nanospider/", packages=find_packages(), long_description=read('README.md'), classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], install_requires = [ "requests", "gevent", "scrapelib", "lxml", "url>=0.1.2dev", ], dependency_links=[ "git+https://github.com/seomoz/url-py.git#egg=url-0.1.2dev", ], )
Split command line tests into individuals
import sys from px import px from unittest.mock import patch @patch('px.px.install') def test_cmdline_install(mock): args = ['px', '--install'] px._main(args) mock.assert_called_once_with(args) @patch("px.px_top.top") def test_cmdline_top(mock): px._main(['px', '--top']) mock.assert_called_once() @patch("px.px_top.top") def test_cmdline_ptop(mock): px._main(['ptop']) mock.assert_called_once() @patch("builtins.print") def test_cmdline_help(mock): px._main(['px', '--help']) mock.assert_called_once_with(px.__doc__) # FIXME: Test --version # FIXME: Test 'px 1' # FIXME: Test 'px root' # FIXME: Test just 'px'
import sys from px import px from unittest.mock import patch def test_main(): args = ['px', '--install'] with patch("px.px.install") as install_mock: px._main(args) install_mock.assert_called_once_with(args) with patch("px.px_top.top") as top_mock: px._main(['px', '--top']) top_mock.assert_called_once() with patch("px.px_top.top") as top_mock: px._main(['ptop']) top_mock.assert_called_once() with patch("builtins.print") as print_mock: px._main(['px', '--help']) print_mock.assert_called_once_with(px.__doc__) # FIXME: Test --version # FIXME: Test 'px 1' # FIXME: Test 'px root' # FIXME: Test just 'px'
Test using tmp media root
""" Test some of the basic model use cases """ from django.test import TestCase from django.core.files.storage import DefaultStorage from candidates.tests.helpers import TmpMediaRootMixin from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TmpMediaRootMixin, TestCase): def setUp(self): self.storage = DefaultStorage() PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
""" Test some of the basic model use cases """ from django.test import TestCase from .factories import PartyFactory, PartyEmblemFactory class TestPartyModels(TestCase): def setUp(self): PartyFactory.reset_sequence() def test_party_str(self): party = PartyFactory() self.assertEqual(str(party), "Party 0 (PP0)") def test_party_emblem(self): party = PartyFactory() PartyEmblemFactory.create_batch(3, party=party) self.assertEqual(party.emblems.count(), 3) self.assertTrue( party.emblems.first().image.url.startswith( "/media/emblems/PP0/0_example" ) ) # Add a default image and assert it's the deafult on the party PartyEmblemFactory(party=party, __sequence=99, default=True) self.assertTrue( party.default_emblem.image.url.startswith( "/media/emblems/PP0/99_example" ) )
Use SHA-256 for the encryption.
package org.sagebionetworks.bridge.crypto; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jasypt.encryption.StringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.salt.RandomSaltGenerator; public class BridgeEncryptor implements StringEncryptor { private final StringEncryptor encryptor; public BridgeEncryptor(String password) { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setProvider(new BouncyCastleProvider()); encryptor.setAlgorithm("PBEWITHSHA256AND256BITAES-CBC-BC"); encryptor.setPassword(password); encryptor.setSaltGenerator(new RandomSaltGenerator()); this.encryptor = encryptor; } public String encrypt(String string) { return encryptor.encrypt(string); } public String decrypt(String string) { return encryptor.decrypt(string); } }
package org.sagebionetworks.bridge.crypto; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jasypt.encryption.StringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.salt.RandomSaltGenerator; public class BridgeEncryptor implements StringEncryptor { private final StringEncryptor encryptor; public BridgeEncryptor(String password) { StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setProvider(new BouncyCastleProvider()); encryptor.setAlgorithm("PBEWITHSHAAND256BITAES-CBC-BC"); encryptor.setPassword(password); encryptor.setSaltGenerator(new RandomSaltGenerator()); this.encryptor = encryptor; } public String encrypt(String string) { return encryptor.encrypt(string); } public String decrypt(String string) { return encryptor.decrypt(string); } }
Move to generated tracker name Change-Id: I1ac24a9278fcfc3a0cc81add5fede9f2435c17ef
/* * Copyright Google Inc. All Rights Reserved. * * 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.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); mTracker = analytics.newTracker(R.xml.global_tracker); } return mTracker; } }
/* * Copyright Google Inc. All Rights Reserved. * * 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.google.samples.quickstart.analytics; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Logger; import com.google.android.gms.analytics.Tracker; /** * This is a subclass of {@link Application} used to provide shared objects for this app, such as * the {@link Tracker}. */ public class AnalyticsApplication extends Application { private Tracker mTracker; /** * Gets the default {@link Tracker} for this {@link Application}. * @return tracker */ synchronized public Tracker getDefaultTracker() { if (mTracker == null) { GoogleAnalytics analytics = GoogleAnalytics.getInstance(this); analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE); mTracker = analytics.newTracker(R.xml.tracker); } return mTracker; } }
Rename test for Publish operator.
package Publish import ( "runtime" "testing" "time" "github.com/stretchr/testify/assert" ) func TestPublishRefCount(t *testing.T) { scheduler := NewGoroutine() ch := make(chan int, 30) s := FromChanInt(ch).Publish().RefCount().SubscribeOn(scheduler) a := []int{} b := []int{} asub := s.SubscribeNext(func(n int) { a = append(a, n) }, SubscribeOn(scheduler)) bsub := s.SubscribeNext(func(n int) { b = append(b, n) }, SubscribeOn(scheduler)) ch <- 1 ch <- 2 ch <- 3 // make sure the channel gets enough time to be fully processed. for i := 0; i < 10; i++ { time.Sleep(20 * time.Millisecond) runtime.Gosched() } asub.Unsubscribe() assert.True(t, asub.Closed()) ch <- 4 close(ch) bsub.Wait() assert.Equal(t, []int{1, 2, 3}, a) assert.Equal(t, []int{1, 2, 3, 4}, b) //assert.True(t, false, "force fail") }
package Publish import ( "runtime" "testing" "time" "github.com/stretchr/testify/assert" ) func TestShare(t *testing.T) { scheduler := NewGoroutine() ch := make(chan int, 30) s := FromChanInt(ch).Publish().RefCount().SubscribeOn(scheduler) a := []int{} b := []int{} asub := s.SubscribeNext(func(n int) { a = append(a, n) }, SubscribeOn(scheduler)) bsub := s.SubscribeNext(func(n int) { b = append(b, n) }, SubscribeOn(scheduler)) ch <- 1 ch <- 2 ch <- 3 // make sure the channel gets enough time to be fully processed. for i := 0; i < 10; i++ { time.Sleep(20 * time.Millisecond) runtime.Gosched() } asub.Unsubscribe() assert.True(t, asub.Closed()) ch <- 4 close(ch) bsub.Wait() assert.Equal(t, []int{1, 2, 3}, a) assert.Equal(t, []int{1, 2, 3, 4}, b) //assert.True(t, false, "force fail") }
Refactor a lightweight Mock class.
import unittest from event import Event class Mock: def __init__(self): self.called = False self.params = () def __call__(self, *args, **kwargs): self.called = True self.params = (args, kwargs) class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): listener = Mock() event = Event() event.connect(listener) event.fire() self.assertTrue(listener.called) def test_a_listener_is_passed_correct_parameters(self): listener = Mock() event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), listener.params)
import unittest from event import Event class EventTest(unittest.TestCase): def test_a_listener_is_notified_when_event_is_raised(self): called = False def listener(): nonlocal called called = True event = Event() event.connect(listener) event.fire() self.assertTrue(called) def test_a_listener_is_passed_correct_parameters(self): params = () def listener(*args, **kwargs): nonlocal params params = (args, kwargs) event = Event() event.connect(listener) event.fire(5, shape="square") self.assertEquals(((5, ), {"shape": "square"}), params)
Move drawing manager call to be in front of the background
var p5 = require('p5'); var sketch = function (p) { var Receiver = require('./Receiver.js'); var receiver = new Receiver(); var Processor = require('./Processor.js'); var processor = new Processor(); var DrawingManager = require('./DrawingManager.js'); var dM = new DrawingManager(p); p.setup = function() { receiver.connect(); receiver.on('received', function(data) { console.log("Pulsar: received: " + data); var drawing = processor.createDrawing(data); dM.add(drawing); // give to drawing manager }) p.createCanvas(p.windowWidth, p.windowHeight); } p.draw = function() { p.background(0); p.textSize(15); p.fill(175); p.textStyle(p.BOLD); var verWidth = p.textWidth("PULSAR - v0.0.1"); p.text("PULSAR - v0.0.1", p.windowWidth - verWidth - 10, p.windowHeight - 10); dM.drawAll(); } p.windowResized = function() { p.resizeCanvas(p.windowWidth, p.windowHeight); } } var myp5 = new p5(sketch);
var p5 = require('p5'); var sketch = function (p) { var Receiver = require('./Receiver.js'); var receiver = new Receiver(); var Processor = require('./Processor.js'); var processor = new Processor(); var DrawingManager = require('./DrawingManager.js'); var dM = new DrawingManager(p); p.setup = function() { receiver.connect(); receiver.on('received', function(data) { console.log("Pulsar: received: " + data); var drawing = processor.createDrawing(data); dM.add(drawing); // give to drawing manager }) p.createCanvas(p.windowWidth, p.windowHeight); } p.draw = function() { dM.drawAll(); p.background(0); p.textSize(15); p.fill(150); p.textStyle(p.BOLD); var verWidth = p.textWidth("PULSAR - v0.0.1"); p.text("PULSAR - v0.0.1", p.windowWidth - verWidth - 10, p.windowHeight - 10); } p.windowResized = function() { p.resizeCanvas(p.windowWidth, p.windowHeight); } } var myp5 = new p5(sketch);
Fix the config table seeder It should include the "extensions_enabled" key which is read when initializing all extensions.
<?php namespace Flarum\Core\Seeders; use Illuminate\Database\Seeder; use DB; class ConfigTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $config = [ 'api_url' => 'http://flarum.dev/api', 'base_url' => 'http://flarum.dev', 'forum_title' => 'Flarum Demo Forum', 'welcome_message' => 'Flarum is now at a point where you can have basic conversations, so here is a little demo for you to break.', 'welcome_title' => 'Welcome to Flarum Demo Forum', 'extensions_enabled' => '[]', ]; DB::table('config')->insert(array_map(function ($key, $value) { return compact('key', 'value'); }, array_keys($config), $config)); } }
<?php namespace Flarum\Core\Seeders; use Illuminate\Database\Seeder; use DB; class ConfigTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $config = [ 'api_url' => 'http://flarum.dev/api', 'base_url' => 'http://flarum.dev', 'forum_title' => 'Flarum Demo Forum', 'welcome_message' => 'Flarum is now at a point where you can have basic conversations, so here is a little demo for you to break.', 'welcome_title' => 'Welcome to Flarum Demo Forum' ]; DB::table('config')->insert(array_map(function ($key, $value) { return compact('key', 'value'); }, array_keys($config), $config)); } }
Handle invalid client credentials properly.
<?php namespace Northstar\Auth\Repositories; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use Northstar\Auth\Entities\ClientEntity; use Northstar\Models\Client; class ClientRepository implements ClientRepositoryInterface { /** * Get a client. * * @param string $clientIdentifier The client's identifier * @param string $grantType The grant type used * @param null|string $clientSecret The client's secret (if sent) * * @return \League\OAuth2\Server\Entities\ClientEntityInterface */ public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null) { // Fetch client from the database & make OAuth2 entity $model = Client::where('app_id', $clientIdentifier)->first(); if(! $model) { return null; } return new ClientEntity($model); } }
<?php namespace Northstar\Auth\Repositories; use League\OAuth2\Server\Repositories\ClientRepositoryInterface; use Northstar\Auth\Entities\ClientEntity; use Northstar\Models\Client; class ClientRepository implements ClientRepositoryInterface { /** * Get a client. * * @param string $clientIdentifier The client's identifier * @param string $grantType The grant type used * @param null|string $clientSecret The client's secret (if sent) * * @return \League\OAuth2\Server\Entities\ClientEntityInterface */ public function getClientEntity($clientIdentifier, $grantType, $clientSecret = null) { // Fetch client from the database & make OAuth2 entity $model = Client::where('app_id', $clientIdentifier)->first(); $client = new ClientEntity($model); return $client; } }
Tidy up the PHP version message
<?php /* Plugin Name: Comment Timeout Plugin URI: http://bitbucket.org/jammycakes/comment-timeout/ Description: Automatically closes comments on blog entries after a user-configurable period of time. It has options which allow you to keep the discussion open for longer on older posts which have had recent comments accepted, or to place a fixed limit on the total number of comments in the discussion. Activate the plugin and go to <a href="options-general.php?page=comment-timeout">Options &gt;&gt; Comment Timeout</a> to configure. Version: 2.1.1 Author: James McKay Author URI: http://jamesmckay.net/ */ define('COMMENT_TIMEOUT_VERSION', '2.1.1'); if (version_compare(phpversion(), '5.0', '<')) { add_action('admin_notices', create_function('', 'echo \'<div class="error">' + '<p>Comment Timeout no longer supports PHP 4. ' + 'Please upgrade your server to PHP 5.2 or later.</p></div>\';' ) ); } else { require_once(dirname(__FILE__) . '/comment-timeout/class.core.php'); }
<?php /* Plugin Name: Comment Timeout Plugin URI: http://bitbucket.org/jammycakes/comment-timeout/ Description: Automatically closes comments on blog entries after a user-configurable period of time. It has options which allow you to keep the discussion open for longer on older posts which have had recent comments accepted, or to place a fixed limit on the total number of comments in the discussion. Activate the plugin and go to <a href="options-general.php?page=comment-timeout">Options &gt;&gt; Comment Timeout</a> to configure. Version: 2.1.1 Author: James McKay Author URI: http://jamesmckay.net/ */ define('COMMENT_TIMEOUT_VERSION', '2.1.1'); if (version_compare(phpversion(), '5.0', '<')) { add_action('admin_notices', create_function('', 'echo \'<div class="error"><p>Comment Timeout no longer supports PHP 4. Please upgrade your server to PHP 5.2 or later.</p></div>\';')); } else { require_once(dirname(__FILE__) . '/comment-timeout/class.core.php'); }
Remove unused dining API method
package com.pennapps.labs.pennmobile.api; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class DiningAPI { protected OkHttpClient client; protected String BASE_URL = "http://api.pennlabs.org/dining/"; public DiningAPI(OkHttpClient client) { this.client = client; } public JSONObject getAPIData(String urlPath) { Request request = new Request.Builder() .url(BASE_URL + urlPath) .header("Content-Type", "application/json") .build(); try { Response response = client.newCall(request).execute(); return new JSONObject(response.body().string()); } catch (JSONException | IOException ignored) { return null; } } public JSONObject getDailyMenu(int hallID) { return getAPIData("daily_menu/" + hallID); } }
package com.pennapps.labs.pennmobile.api; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; public class DiningAPI { protected OkHttpClient client; protected String BASE_URL = "http://api.pennlabs.org/dining/"; public DiningAPI(OkHttpClient client) { this.client = client; } public JSONObject getAPIData(String urlPath) { Request request = new Request.Builder() .url(BASE_URL + urlPath) .header("Content-Type", "application/json") .build(); try { Response response = client.newCall(request).execute(); return new JSONObject(response.body().string()); } catch (JSONException | IOException ignored) { return null; } } public JSONObject getVenues() { return getAPIData("venues"); } public JSONObject getDailyMenu(int hallID) { return getAPIData("daily_menu/" + hallID); } }
Test fixes and style adjustments
var test = require('tape') var es2015 = require('babel-preset-es2015') var es2015Loose = require('../index') var LOOSE = {loose: true} var PREFIX = 'transform-es2015-' var SHOULD_BE_LOOSE = [ PREFIX + 'template-literals', PREFIX + 'classes', PREFIX + 'computed-properties', PREFIX + 'for-of', PREFIX + 'spread', PREFIX + 'destructuring', PREFIX + 'modules-commonjs' ] function getPluginEntry(name) { var plugin = require('babel-plugin-' + name) for (var loosePlugin of es2015Loose.plugins) { if (loosePlugin === plugin || loosePlugin[0] === plugin) { return loosePlugin } } return false } SHOULD_BE_LOOSE.forEach(function(name) { test(name, function(t) { t.plan(3) var entry = getPluginEntry(name) t.ok(entry, 'Entry for ' + name + ' should exist') t.ok(Array.isArray(entry), 'Entry for ' + name + ' should be an Array') t.deepEqual(entry[1], LOOSE, 'Entry for ' + name + ' should specify {loose:true}') }) });
var test = require('tape'), es2015 = require('babel-preset-es2015'), es2015Loose = require('..'); var LOOSE = { loose: true }; var PREFIX = 'transform-es2015-'; var SHOULD_BE_LOOSE = [ PREFIX+'template-literals', PREFIX+'classes', PREFIX+'computed-properties', PREFIX+'for-of', PREFIX+'spread', PREFIX+'destructuring', PREFIX+'modules-commonjs' ]; function getPluginEntry(name) { var plugin = require('../node_modules/babel-preset-es2015/node_modules/babel-plugin-'+name); for (var i=es2015Loose.plugins.length; i--; ) { var p = es2015Loose.plugins[i]; if (p===plugin || p[0]===plugin) { return p; } } return false; } SHOULD_BE_LOOSE.forEach(function(name) { test(name, function(t) { t.plan(3); var entry = getPluginEntry(name); t.ok(entry, 'Entry for '+name+' should exist'); t.ok(Array.isArray(entry), 'Entry for '+name+' should be an Array'); t.deepEqual(entry[1], LOOSE, 'Entry for '+name+' should specify {loose:true}'); }); });
Fix default template of order received notification Order lines were rendered on a single line. Fix that by adding a line break after each order line.
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }} Received" MESSAGE_BODY_TEMPLATE = """ Thank you for your order, {{ order.customer }}! Your order has been received and will be processed as soon as possible. For reference, here's a list of your order's contents. {% for line in order.lines.all() %} {%- if line.taxful_total_price %} * {{ line.quantity }} x {{ line.text }} - {{ line.taxful_total_price|money }} {% endif -%} {%- endfor %} Order Total: {{ order.taxful_total_price|money }} {% if not order.is_paid() %} Please note that no record of your order being paid currently exists. {% endif %} Thank you for shopping with us! """.strip()
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. MESSAGE_SUBJECT_TEMPLATE = "{{ order.shop }} - Order {{ order.identifier }} Received" MESSAGE_BODY_TEMPLATE = """ Thank you for your order, {{ order.customer }}! Your order has been received and will be processed as soon as possible. For reference, here's a list of your order's contents. {% for line in order.lines.all() %} {%- if line.taxful_total_price -%} * {{ line.quantity }} x {{ line.text }} - {{ line.taxful_total_price|money }} {%- endif -%} {%- endfor %} Order Total: {{ order.taxful_total_price|money }} {% if not order.is_paid() %} Please note that no record of your order being paid currently exists. {% endif %} Thank you for shopping with us! """.strip()
Remove name since it's redundant, show just asset name and download count
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("INPUT"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); submit.setAttribute("value", "Consultar descargas de última versión"); p.appendChild(label); form.appendChild(p); form.appendChild(submit); aside.appendChild(form); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) { var assetName = json.assets[0].name; var downloadCount = json.assets[0].download_count; alert(assetName + " " + downloadCount); }); }); });
document.getElementById("ayuda").setAttribute("aria-current", "page"); var aside = document.getElementById("complementario"); var form = document.createElement("FORM"); var p = document.createElement("P"); var label = document.createElement("LABEL"); label.setAttribute("for", "repo"); t = document.createTextNode("cuenta/repositorio de GitHub"); label.appendChild(t); var input = document.createElement("INPUT"); input.setAttribute("type", "text"); input.setAttribute("id", "repo"); input.setAttribute("name", "repo"); label.appendChild(input); var submit = document.createElement("INPUT"); submit.setAttribute("id", "submit"); submit.setAttribute("type", "button"); submit.setAttribute("value", "Consultar descargas de última versión"); p.appendChild(label); form.appendChild(p); form.appendChild(submit); aside.appendChild(form); $(document).ready(function () { $("#submit").click(function () { $.getJSON("https://api.github.com/repos/" + input.value + "/releases/latest", function(json) { var name = json.name; var assetName = json.assets[0].name; var downloadCount = json.assets[0].download_count; alert(name + " " + assetName + " " + downloadCount); }); }); });
Add license and Source Code url
from distutils.core import setup setup(name="zutil", version='0.1.5', description="Utilities used for generating zCFD control dictionaries", author="Zenotech", author_email="support@zenotech.com", license="MIT", url="https://zcfd.zenotech.com/", project_urls={ "Source Code": "https://github.com/zCFD/zutil/", }, packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"], install_requires=[ 'ipython<6.0', 'Fabric', 'ipywidgets', 'matplotlib', 'numpy', 'pandas', 'PyYAML' ], extras_require={ "mpi": ["mpi4py"] } )
from distutils.core import setup setup(name="zutil", version='0.1.5', description="Utilities used for generating zCFD control dictionaries", author="Zenotech", author_email="support@zenotech.com", url="https://zcfd.zenotech.com/", packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"], install_requires=[ 'ipython<6.0', 'Fabric', 'ipywidgets', 'matplotlib', 'numpy', 'pandas', 'PyYAML' ], extras_require={ "mpi": ["mpi4py"] } )
Change the name in the javascript plugin to the correct name from the native code
/*global cordova, module*/ var exec = require("cordova/exec") var JWTAuth = { /* * Returns the stored user email. * Can return null if the user is not signed in. */ getUserEmail: function (successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "getUserEmail", []); }, /* * Signs the user in and returns the signed in user email. */ signIn: function(successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "signIn", []); }, getJWT: function(successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "getJWT", []); }, } module.exports = JWTAuth;
/*global cordova, module*/ var exec = require("cordova/exec") var JWTAuth = { /* * Returns the stored user email. * Can return null if the user is not signed in. */ getUserEmail: function (successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "getSignedInEmail", [level, message]); }, /* * Signs the user in and returns the signed in user email. */ signIn: function(successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "signIn", []); }, getJWT: function(successCallback, errorCallback) { exec(successCallback, errorCallback, "JWTAuth", "getJWT", []); }, } module.exports = JWTAuth;
[ADD] Add /login as a valid route during the race
import React from 'react'; import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'; import NotFoundPage from '../../../pages/NotFound'; import AppContainer from '../../../../../../lib/react/components/AppContainer'; import Login from '../../components/Login'; import Dashboard from './Dashboard'; class Race extends React.Component { render() { return ( <BrowserRouter> <AppContainer> <Switch> <Route exact path='/'> <Login notAnimated/> </Route> <Route exact path='/login'> <Login notAnimated/> </Route> <Route path='/dashboard' component={Dashboard}/> <Route component={NotFoundPage}/> </Switch> </AppContainer> </BrowserRouter> ); } } export default Race;
import React from 'react'; import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'; import NotFoundPage from '../../../pages/NotFound'; import AppContainer from '../../../../../../lib/react/components/AppContainer'; import Login from '../../components/Login'; import Dashboard from './Dashboard'; class Race extends React.Component { render() { return ( <BrowserRouter> <AppContainer> <Switch> <Route exact path='/'> <Login notAnimated/> </Route> <Route path='/dashboard' component={Dashboard}/> <Route component={NotFoundPage}/> </Switch> </AppContainer> </BrowserRouter> ); } } export default Race;
Remove pointless converting of arguments object to an array since alert.js doesn't seem to care that it's not really an array.
var EXPORTED_SYMBOLS = ["GM_notification"]; var Cc = Components.classes; var Ci = Components.interfaces; // The first time this runs, we check if nsIAlertsService is installed and // works. If it fails, we re-define notify to use a chrome window. // We check to see if nsIAlertsService works because of the case where Growl // is not installed. See also https://bugzilla.mozilla.org/show_bug.cgi?id=597165 function notify() { try { Cc["@mozilla.org/alerts-service;1"] .getService(Ci.nsIAlertsService) .showAlertNotification.apply(null, arguments); } catch (e) { notify = function() { Cc['@mozilla.org/embedcomp/window-watcher;1'] .getService(Ci.nsIWindowWatcher) .openWindow(null, 'chrome://global/content/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null) .arguments = arguments; }; notify.apply(null, arguments); } } function GM_notification(aMsg, aTitle) { var title = aTitle ? "" + aTitle : "Greasemonkey"; var message = aMsg ? "" + aMsg : ""; notify( "chrome://greasemonkey/skin/icon32.png", title, message, false, "", null); };
var EXPORTED_SYMBOLS = ["GM_notification"]; var Cc = Components.classes; var Ci = Components.interfaces; // The first time this runs, we check if nsIAlertsService is installed and // works. If it fails, we re-define notify to use a chrome window. // We check to see if nsIAlertsService works because of the case where Growl // is not installed. See also https://bugzilla.mozilla.org/show_bug.cgi?id=597165 function notify() { try { Cc["@mozilla.org/alerts-service;1"] .getService(Ci.nsIAlertsService) .showAlertNotification.apply(null, arguments); } catch (e) { notify = function() { Cc['@mozilla.org/embedcomp/window-watcher;1'] .getService(Ci.nsIWindowWatcher) .openWindow(null, 'chrome://global/content/alerts/alert.xul', '_blank', 'chrome,titlebar=no,popup=yes', null) .arguments = Array.prototype.slice.call(arguments); }; notify.apply(null, arguments); } } function GM_notification(aMsg, aTitle) { var title = aTitle ? "" + aTitle : "Greasemonkey"; var message = aMsg ? "" + aMsg : ""; notify( "chrome://greasemonkey/skin/icon32.png", title, message, false, "", null); };
Allow to override the controller used for excetion handling
<?php namespace Flint\Provider; use Symfony\Component\HttpKernel\EventListener\ExceptionListener; use Flint\Controller\ControllerResolver; use Silex\Application; /** * @package Flint */ class FlintServiceProvider implements \Silex\ServiceProviderInterface { /** * {@inheritDoc} */ public function register(Application $app) { $app['exception_controller'] = 'Flint\\Controller\\ExceptionController::showAction'; $app['exception_handler'] = $app->share(function ($app) { return new ExceptionListener($app['exception_controller'], $app['logger']); }); $app->extend('resolver', function ($resolver, $app) { return new ControllerResolver($resolver, $app); }); $app->extend('twig.loader.filesystem', function ($loader, $app) { $loader->addPath(__DIR__ . '/../Resources/views', 'Flint'); return $loader; }); } /** * {@inheritDoc} */ public function boot(Application $app) { } }
<?php namespace Flint\Provider; use Symfony\Component\HttpKernel\EventListener\ExceptionListener; use Flint\Controller\ControllerResolver; use Silex\Application; /** * @package Flint */ class FlintServiceProvider implements \Silex\ServiceProviderInterface { /** * {@inheritDoc} */ public function register(Application $app) { $app['exception_handler'] = $app->share(function ($app) { return new ExceptionListener('Flint\\Controller\\ExceptionController::showAction', $app['logger']); }); $app->extend('resolver', function ($resolver, $app) { return new ControllerResolver($resolver, $app); }); $app->extend('twig.loader.filesystem', function ($loader, $app) { $loader->addPath(__DIR__ . '/../Resources/views', 'Flint'); return $loader; }); } /** * {@inheritDoc} */ public function boot(Application $app) { } }
Implement backport of logging package for 2.6 debugging 3
import logging from logging import * class Logger(logging.Logger): def getChild(self, suffix): """ (copied from module "logging" for Python 3.4) Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
import logging from logging import * class Logger26(logging.getLoggerClass()): def getChild(self, suffix): """ (copied from module "logging" for Python 3.4) Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger('abc').getChild('def.ghi') is the same as logging.getLogger('abc.def.ghi') It's useful, for example, when the parent logger is named using __name__ rather than a literal string. """ if self.root is not self: suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix) logging.setLoggerClass(Logger26)
Remove unused numpy input (codacy)
#!/usr/bin/env python3 """ Utilities to compute the power of a device """ from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit __all__ = ["current_by_power", "power_by_current_and_voltage"] def current_by_power(power="25 W", voltage="230 V") -> Unit("A"): """ Given a device's power (or RMS power) and the voltage (or RMS voltage) it runs on, compute how much current it will draw. """ power = normalize_numeric(power) voltage = normalize_numeric(voltage) return power / voltage def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"): """ Given a device's current (or RMS current) and the voltage (or RMS current) it runs on, compute its power """ current = normalize_numeric(current) voltage = normalize_numeric(voltage) return current * voltage
#!/usr/bin/env python3 """ Utilities to compute the power of a device """ from UliEngineering.EngineerIO import normalize_numeric from UliEngineering.Units import Unit import numpy as np __all__ = ["current_by_power", "power_by_current_and_voltage"] def current_by_power(power="25 W", voltage="230 V") -> Unit("A"): """ Given a device's power (or RMS power) and the voltage (or RMS voltage) it runs on, compute how much current it will draw. """ power = normalize_numeric(power) voltage = normalize_numeric(voltage) return power / voltage def power_by_current_and_voltage(current="1.0 A", voltage="230 V") -> Unit("W"): """ Given a device's current (or RMS current) and the voltage (or RMS current) it runs on, compute its power """ current = normalize_numeric(current) voltage = normalize_numeric(voltage) return current * voltage
Set DEBUG = False in production
from local_settings import * DEBUG = False ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
from local_settings import * settings.DEBUG = False ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': 'user', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # REST framework settings REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } # Mandrill email settings EMAIL_HOST = 'smtp.mandrillapp.com' from secrets import EMAIL_HOST_USER, EMAIL_HOST_PASSWORD EMAIL_PORT = '587' EMAIL_USE_TLS = True
Convert into a class to match the other handlers.
# This is a software index handler that gives a score based on the # number of mentions in open access articles. It uses the CORE # aggregator (http://core.ac.uk/) to search the full text of indexed # articles. # # Inputs: # - identifier (String) # # Outputs: # - score (Number) # - description (String) import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' class core_handler: def get_score(self, identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score def get_description(self): return 'mentions in Open Access articles (via http://core.ac.uk/)'
import requests, json, urllib SEARCH_URL = 'http://core.kmi.open.ac.uk/api/search/' API_KEY = 'FILL THIS IN' def getCOREMentions(identifier, **kwargs): """Return the number of mentions in CORE and a descriptor, as a tuple. Needs an API key, which can be obtained here: http://core.ac.uk/api-keys/register""" params = { 'api_key': API_KEY, 'format': 'json', } params.update(kwargs) response = requests.get(SEARCH_URL + urllib.quote_plus(identifier), params=params) response.raise_for_status() results = response.json() score = results['ListRecords'][0]['total_hits'] return score, 'mentions in Open Access articles (via http://core.ac.uk/)'
Increment version to 1.0.5. Resync code base after machine crash.
import sys import os from setuptools import setup long_description = open('README.rst').read() classifiers = [ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] setup_kwargs = dict( name='powershift-cli', version='1.0.5', description='Pluggable command line client for OpenShift.', long_description=long_description, url='https://github.com/getwarped/powershift-cli', author='Graham Dumpleton', author_email='Graham.Dumpleton@gmail.com', license='BSD', classifiers=classifiers, keywords='openshift kubernetes', packages=['powershift', 'powershift.cli'], package_dir={'powershift': 'src/powershift'}, package_data={'powershift.cli': ['completion-bash.sh']}, entry_points = {'console_scripts':['powershift = powershift.cli:main']}, install_requires=['click'], ) setup(**setup_kwargs)
import sys import os from setuptools import setup long_description = open('README.rst').read() classifiers = [ 'Development Status :: 4 - Beta', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ] setup_kwargs = dict( name='powershift-cli', version='1.0.4', description='Pluggable command line client for OpenShift.', long_description=long_description, url='https://github.com/getwarped/powershift-cli', author='Graham Dumpleton', author_email='Graham.Dumpleton@gmail.com', license='BSD', classifiers=classifiers, keywords='openshift kubernetes', packages=['powershift', 'powershift.cli'], package_dir={'powershift': 'src/powershift'}, package_data={'powershift.cli': ['completion-bash.sh']}, entry_points = {'console_scripts':['powershift = powershift.cli:main']}, install_requires=['click'], ) setup(**setup_kwargs)
Increase time between channel topic updates
package net.dirtydeeds.discordsoundboard.async; import net.dirtydeeds.discordsoundboard.service.SoundboardBot; import net.dirtydeeds.discordsoundboard.utils.*; public class PeriodicLambdas { public static PeriodicLambdaJob askForDonation() { return new PeriodicLambdaJob(Reusables::sendDonationMessage, Periodic.EVERY_TWO_DAYS); } public static PeriodicLambdaJob cleanOldBotMessages() { return new PeriodicLambdaJob(SoundboardBot::clearPreviousMessages, Periodic.EVERY_SIX_HOURS); } public static PeriodicLambdaJob changeToRandomGame() { return new PeriodicLambdaJob(Reusables::setRandomGame, Periodic.EVERY_TWO_MINUTES); } public static PeriodicLambdaJob changeBotChannelTopic() { return new PeriodicLambdaJob(Reusables::setRandomTopicForPublicChannels, Periodic.EVERY_SIX_HOURS); } }
package net.dirtydeeds.discordsoundboard.async; import net.dirtydeeds.discordsoundboard.service.SoundboardBot; import net.dirtydeeds.discordsoundboard.utils.*; public class PeriodicLambdas { public static PeriodicLambdaJob askForDonation() { return new PeriodicLambdaJob(Reusables::sendDonationMessage, Periodic.EVERY_TWO_DAYS); } public static PeriodicLambdaJob cleanOldBotMessages() { return new PeriodicLambdaJob(SoundboardBot::clearPreviousMessages, Periodic.EVERY_SIX_HOURS); } public static PeriodicLambdaJob changeToRandomGame() { return new PeriodicLambdaJob(Reusables::setRandomGame, Periodic.EVERY_TWO_MINUTES); } public static PeriodicLambdaJob changeBotChannelTopic() { return new PeriodicLambdaJob(Reusables::setRandomTopicForPublicChannels, Periodic.EVERY_HOUR); } }
Enable security for OPTIONS to anyone
package vaccination.security; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
package vaccination.security; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, PATCH"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "*"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
Extend from image instead of sprite
import Phaser from 'phaser'; import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles'; import { clone } from '../../utils'; import tween from './tween'; export default class extends Phaser.Image { constructor(game, x, y, sprite, frame, id, objectType) { const alignedCoords = alignToGrid({ x, y }); x = alignedCoords.x; y = alignedCoords.y; super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); // use a bunch of different properties to hopefully achieve a unique id this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1); this.objectType = objectType || 'generic'; this.timers = []; this.tile = {}; this.setTile(); } move(nextPixelCoord, callback) { this.moving = true; tween.call(this, nextPixelCoord, 35, function() { this.moving = false; this.setTile(); if (callback) callback.call(this); }); } setTile() { this.tile = tile.call(this); } destroy() { super.destroy(); this.destroyed = true; } }
import Phaser from 'phaser'; import { tile, nextTile, alignToGrid, pixelToTile } from '../../tiles'; import { clone } from '../../utils'; import tween from './tween'; export default class extends Phaser.Sprite { constructor(game, x, y, sprite, frame, id, objectType) { const alignedCoords = alignToGrid({ x, y }); x = alignedCoords.x; y = alignedCoords.y; super(game, x, y, sprite, frame); this.anchor.setTo(0.5, 0.5); // use a bunch of different properties to hopefully achieve a unique id this.id = id || this.key + this.frame + this.x + this.y + (Math.floor(Math.random() * 100) + 1); this.objectType = objectType || 'generic'; this.timers = []; this.tile = {}; this.setTile(); } move(nextPixelCoord, callback) { this.moving = true; tween.call(this, nextPixelCoord, 35, function() { this.moving = false; this.setTile(); if (callback) callback.call(this); }); } setTile() { this.tile = tile.call(this); } destroy() { super.destroy(); this.destroyed = true; } }
Add a long type backfill for PY3 compat PY3 combined the long and int types which makes some compiler operations difficult. Adding a backfill to help with PY2/PY3 compat. Signed-off-by: Kevin Conway <3473c1f185ca03eadc40ad288d84425b54fd7d57@gmail.com>
"""Compatibility helpers for Py2 and Py3.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys class VERSION(object): """Stand in for sys.version_info. The values from sys only have named parameters starting in PY27. This allows us to use named parameters for all versions of Python. """ major, minor, micro, releaselevel, serial = sys.version_info PY2 = VERSION.major == 2 PY25 = PY2 and VERSION.minor == 5 PY26 = PY2 and VERSION.minor == 6 PY27 = PY2 and VERSION.minor == 7 PY3 = not PY2 PY31 = PY3 and VERSION.minor == 1 PY32 = PY3 and VERSION.minor == 2 PY33 = PY3 and VERSION.minor == 3 py34 = PY3 and VERSION.minor == 4 # Provide a nice range function for py2. try: range = xrange except NameError: pass # Provide a long type for py3. try: long = long except NameError: long = int
"""Compatibility helpers for Py2 and Py3.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import sys class VERSION(object): """Stand in for sys.version_info. The values from sys only have named parameters starting in PY27. This allows us to use named parameters for all versions of Python. """ major, minor, micro, releaselevel, serial = sys.version_info PY2 = VERSION.major == 2 PY25 = PY2 and VERSION.minor == 5 PY26 = PY2 and VERSION.minor == 6 PY27 = PY2 and VERSION.minor == 7 PY3 = not PY2 PY31 = PY3 and VERSION.minor == 1 PY32 = PY3 and VERSION.minor == 2 PY33 = PY3 and VERSION.minor == 3 py34 = PY3 and VERSION.minor == 4 # Provide a nice range function for py2. try: range = xrange except NameError: pass
Move config HTML generation to separate helper function.
<?php /** * @file * Contains linclark\MicrodataPhpTest */ namespace linclark\MicrodataPHP; /** * Tests the MicrodataPHP functionality. */ class MicrodataPhpTest extends \PHPUnit_Framework_TestCase { /** * Tests parsing a sample html document. */ public function testParseMicroData() { $config = $this->getConfig('person.html'); $microdata = new MicrodataPhp($config); $data = $microdata->obj(); $name = $data->items[0]->properties['name'][0]; $this->assertEquals($name, "Jane Doe", "The name matches."); } /** * @expectedException \InvalidArgumentException */ public function testConstructorNoUrlOrHtml() { $config = array(); new MicrodataPhp($config); } protected function getConfig($file) { return array('html' => file_get_contents(__DIR__ . '/../data/' . $file)); } }
<?php /** * @file * Contains linclark\MicrodataPhpTest */ namespace linclark\MicrodataPHP; /** * Tests the MicrodataPHP functionality. */ class MicrodataPhpTest extends \PHPUnit_Framework_TestCase { /** * Tests parsing a sample html document. */ public function testParseMicroData() { $config = array('html' => file_get_contents(__DIR__ . '/../data/person.html')); $microdata = new MicrodataPhp($config); $data = $microdata->obj(); $name = $data->items[0]->properties['name'][0]; $this->assertEquals($name, "Jane Doe", "The name matches."); } /** * @expectedException \InvalidArgumentException */ public function testConstructorNoUrlOrHtml() { $config = array(); new MicrodataPhp($config); } }
Add default tabbar as null
/* eslint-disable react/forbid-prop-types */ import React, { useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { useNavigation } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; const DEFAULT_TAB_CONFIG = { options: { tabBarVisible: false } }; const Tab = createBottomTabNavigator(); /** * Simple TabNavigator component managing lazily loaded * tabs of components. Slightly different from a regular tab navigator: * Managed declaratively through passing props rather than imperatively * using functions on the navigation ref. * * @prop {Array} tabs An array of components for each tab. * @prop {Number} currentTabIndex The index of the tab to show. */ export const TabNavigator = ({ tabs, currentTabIndex }) => { const navigatorRef = useRef(useNavigation()); // When `currentTabIndex` changes, dispatch an action to trigger a switch on the // base navigation component to the passed tab index. useEffect(() => navigatorRef.current.navigate(String(currentTabIndex)), [currentTabIndex]); return ( <Tab.Navigator tabBar={() => null}> {tabs.map((tab, idx) => ( <Tab.Screen {...DEFAULT_TAB_CONFIG} name={`${idx}`} key={tab.name} component={tab.component} /> ))} </Tab.Navigator> ); }; TabNavigator.propTypes = { tabs: PropTypes.array.isRequired, currentTabIndex: PropTypes.number.isRequired, };
/* eslint-disable react/forbid-prop-types */ import React, { useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { useNavigation } from '@react-navigation/native'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; const DEFAULT_TAB_CONFIG = { options: { tabBarVisible: false } }; const Tab = createBottomTabNavigator(); /** * Simple TabNavigator component managing lazily loaded * tabs of components. Slightly different from a regular tab navigator: * Managed declaratively through passing props rather than imperatively * using functions on the navigation ref. * * @prop {Array} tabs An array of components for each tab. * @prop {Number} currentTabIndex The index of the tab to show. */ export const TabNavigator = ({ tabs, currentTabIndex }) => { const navigatorRef = useRef(useNavigation()); // When `currentTabIndex` changes, dispatch an action to trigger a switch on the // base navigation component to the passed tab index. useEffect(() => navigatorRef.current.navigate(String(currentTabIndex)), [currentTabIndex]); return ( <Tab.Navigator> {tabs.map((tab, idx) => ( <Tab.Screen {...DEFAULT_TAB_CONFIG} name={`${idx}`} key={tab.name} component={tab.component} /> ))} </Tab.Navigator> ); }; TabNavigator.propTypes = { tabs: PropTypes.array.isRequired, currentTabIndex: PropTypes.number.isRequired, };
Use from_date to construct from year, month, day.
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar == other.calendar and self.date == other.date class Calendar(object): def from_date(self, date): return DateWithCalendar(self.__class__, date) class ProlepticGregorianCalendar(Calendar): def date(self, year, month, day): d = date(year, month, day) return self.from_date(d) class JulianCalendar(Calendar): def date(self, year, month, day): d = date(year, month, day) d = d + timedelta(days=10) return self.from_date(d)
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar == other.calendar and self.date == other.date class Calendar(object): def from_date(self, date): return DateWithCalendar(self.__class__, date) class ProlepticGregorianCalendar(Calendar): def date(self, year, month, day): d = date(year, month, day) return self.from_date(d) class JulianCalendar(Calendar): def date(self, year, month, day): d = date(year, month, day) d = d + timedelta(days=10) return DateWithCalendar(JulianCalendar, d)
Update code style of doc generator
const fs = require('fs'); const markdox = require('markdox'); const sources = [ '../src/index.js', '../src/apis/users.js', '../src/apis/organizations.js', '../src/apis/memberships.js', '../src/apis/sourceimages.js', '../src/apis/operations.js', '../src/apis/stacks.js', '../src/apis/render.js' ]; const readme = '../README.md'; const tmpFile = './API.md'; const options = { template: './template.md.ejs', output: tmpFile }; markdox.process(sources, options, function() { let docsStr = fs.readFileSync(tmpFile, 'utf8'); let readmeStr = fs.readFileSync(readme, 'utf8'); docsStr = docsStr .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&#39;/g, "'") .replace(/&quot;/g, "'") .replace(/&amp;/g, '&'); readmeStr = readmeStr .replace(/(<!-- DOCS -->)(?:\r|\n|.)+(<!-- ENDDOCS -->)/gm, '$1' + docsStr + '$2'); fs.writeFileSync(readme, readmeStr); fs.unlinkSync(tmpFile); process.stdout.write('Documentation generated.\n'); });
var fs = require('fs') , markdox = require('markdox'); var sources = [ '../src/index.js', '../src/apis/users.js', '../src/apis/organizations.js', '../src/apis/memberships.js', '../src/apis/sourceimages.js', '../src/apis/operations.js', '../src/apis/stacks.js', '../src/apis/render.js' ] , readme = '../README.md' , tmpFile = './API.md'; var options = { template: './template.md.ejs', output: tmpFile }; markdox.process(sources, options, function() { var docsStr = fs.readFileSync(tmpFile, 'utf8') , readmeStr = fs.readFileSync(readme, 'utf8'); docsStr = docsStr .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&#39;/g, "'") .replace(/&quot;/g, "'") .replace(/&amp;/g, '&'); readmeStr = readmeStr .replace(/(<!-- DOCS -->)(?:\r|\n|.)+(<!-- ENDDOCS -->)/gm, '$1' + docsStr + '$2'); fs.writeFileSync(readme, readmeStr); fs.unlinkSync(tmpFile); process.stdout.write('Documentation generated.\n'); });
Make request executor not follow redirects
import { Map } from 'immutable'; const httpClient = {request: require('request')}; class Response { body:?string; headers:Map; status:number; statusText:string; responseTimeMs:number; constructor(body, headers, status, statusText, responseTimeMs) { this.body = body; this.headers = new Map(headers); this.status = status; this.statusText = statusText; this.responseTimeMs = responseTimeMs; } } export class Request { method:string; url:string; headers:Object; body:?string; constructor(method, url, headers, body) { this.method = method; this.url = url; this.headers = headers; this.body = body; } } export function execute(request:Request, callback) { const requestStart = performance.now(); const sentRequest = httpClient.request({ method: request.method, url: request.url, headers: request.headers, body: request.body, followRedirect: false }, (error, response) => { if (error) return callback(error, null); const requestEnd = performance.now(); const responseTimeMs = Math.round(requestEnd - requestStart); callback(null, new Response(response.body, response.headers, response.statusCode, response.statusMessage, responseTimeMs)); }); return function cancel() { sentRequest.abort(); }; }
import { Map } from 'immutable'; const httpClient = {request: require('request')}; class Response { body:?string; headers:Map; status:number; statusText:string; responseTimeMs:number; constructor(body, headers, status, statusText, responseTimeMs) { this.body = body; this.headers = new Map(headers); this.status = status; this.statusText = statusText; this.responseTimeMs = responseTimeMs; } } export class Request { method:string; url:string; headers:Object; body:?string; constructor(method, url, headers, body) { this.method = method; this.url = url; this.headers = headers; this.body = body; } } export function execute(request:Request, callback) { const requestStart = performance.now(); const sentRequest = httpClient.request({ method: request.method, url: request.url, headers: request.headers, body: request.body }, (error, response) => { if (error) return callback(error, null); const requestEnd = performance.now(); const responseTimeMs = Math.round(requestEnd - requestStart); callback(null, new Response(response.body, response.headers, response.statusCode, response.statusMessage, responseTimeMs)); }); return function cancel() { sentRequest.abort(); }; }
Refactor code based on PR comments.
import React, { Component } from 'react' import ResponseFields from './ResponseFields.js' export default class ResponseList extends Component { render () { return ( <div className="response-list"> { this.props.responses.map(response => (<ResponseFields response={response} key={this.props.responses.indexOf(response)} responseIndex={this.props.responses.indexOf(response)} onChangeResponse={this.props.onChangeResponse} onChangeQuestion={this.props.onChangeQuestion} onRemoveOption={this.props.onRemoveOption} onAddOption={this.props.onAddOption} /> ))} </div> ) } }
import React, { Component } from 'react' import ResponseFields from './ResponseFields.js' export default class ResponseList extends Component { render () { return ( <div className="response-list"> { this.props.responses.map(response => { return (<ResponseFields response={response} key={this.props.responses.indexOf(response)} responseIndex={this.props.responses.indexOf(response)} onChangeResponse={this.props.onChangeResponse} onChangeQuestion={this.props.onChangeQuestion} onRemoveOption={this.props.onRemoveOption} onAddOption={this.props.onAddOption} />) })} </div> ) } }
Replace version with a placeholder for develop
package main import ( "github.com/albrow/scribble/util" "gopkg.in/alecthomas/kingpin.v1" "os" ) var ( app = kingpin.New("scribble", "A tiny static blog generator written in go.") serveCmd = app.Command("serve", "Compile and serve the site.") servePort = serveCmd.Flag("port", "The port on which to serve the site.").Short('p').Default("4000").Int() compileCmd = app.Command("compile", "Compile the site.") compileWatch = compileCmd.Flag("watch", "Whether or not to watch for changes and automatically recompile.").Short('w').Default("").Bool() ) const ( version = "X.X.X (develop)" ) func main() { // catch panics and print them out as errors defer util.Recovery() // print out the version when prompted kingpin.Version(version) // Parse the command line arguments and flags and delegate // to the appropriate functions. cmd, err := app.Parse(os.Args[1:]) if err != nil { app.Usage(os.Stdout) os.Exit(0) } switch cmd { case compileCmd.FullCommand(): compile(*compileWatch) case serveCmd.FullCommand(): compile(true) serve(*servePort) default: app.Usage(os.Stdout) os.Exit(0) } }
package main import ( "github.com/albrow/scribble/util" "gopkg.in/alecthomas/kingpin.v1" "os" ) var ( app = kingpin.New("scribble", "A tiny static blog generator written in go.") serveCmd = app.Command("serve", "Compile and serve the site.") servePort = serveCmd.Flag("port", "The port on which to serve the site.").Short('p').Default("4000").Int() compileCmd = app.Command("compile", "Compile the site.") compileWatch = compileCmd.Flag("watch", "Whether or not to watch for changes and automatically recompile.").Short('w').Default("").Bool() ) const ( version = "0.0.1" ) func main() { // catch panics and print them out as errors defer util.Recovery() // print out the version when prompted kingpin.Version(version) // Parse the command line arguments and flags and delegate // to the appropriate functions. cmd, err := app.Parse(os.Args[1:]) if err != nil { app.Usage(os.Stdout) os.Exit(0) } switch cmd { case compileCmd.FullCommand(): compile(*compileWatch) case serveCmd.FullCommand(): compile(true) serve(*servePort) default: app.Usage(os.Stdout) os.Exit(0) } }
Add extra inner wrapper which has a 'flex: 1'
import React, { PureComponent } from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import { Box } from '../box'; import theme from './theme.css'; class ScrollContainer extends PureComponent { render() { const { className, header, body, footer, ...others } = this.props; const classNames = cx(theme['scroll-container'], className); return ( <Box className={classNames} display="flex" flexDirection="column" {...others}> {header && <header className={theme['scroll-container-header']}>{header}</header>} {body && ( <div className={theme['scroll-container-body']}> <Box flex="1">{body}</Box> </div> )} {footer && <footer className={theme['scroll-container-footer']}>{footer}</footer>} </Box> ); } } ScrollContainer.propTypes = { /** Node to render as the header */ header: PropTypes.node, /** Node to render as the body */ body: PropTypes.node, /** Node to render as the footer */ footer: PropTypes.node, }; export default ScrollContainer;
import React, { PureComponent } from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import { Box } from '../box'; import theme from './theme.css'; class ScrollContainer extends PureComponent { render() { const { className, header, body, footer, ...others } = this.props; const classNames = cx(theme['scroll-container'], className); return ( <Box className={classNames} display="flex" flexDirection="column" {...others}> {header && <header className={theme['scroll-container-header']}>{header}</header>} {body && <div className={theme['scroll-container-body']}>{body}</div>} {footer && <footer className={theme['scroll-container-footer']}>{footer}</footer>} </Box> ); } } ScrollContainer.propTypes = { /** Node to render as the header */ header: PropTypes.node, /** Node to render as the body */ body: PropTypes.node, /** Node to render as the footer */ footer: PropTypes.node, }; export default ScrollContainer;
Change don't device orientation lock at the time of run
(function() { 'use strict'; angular.module('sensors.components') .controller('MenuController', MenuController); function MenuController($scope, $window, menuItems, openLinkTobrowser) { $scope.items = []; $scope.isLock = false; $scope.screen = $window.screen; $scope.openLink = openLinkTobrowser.open; angular.forEach(menuItems, function(item) { $scope.items.push({ title: item, state: 'app.' + item }) }); // 初期起動時は画面の回転をロックする // [MEMO] インストール後の初回起動時と通常の再起動時で挙動が異なるので様子見 //$scope.screen.mozLockOrientation($scope.screen.mozOrientation); //////////// $scope.toggleLockOrientation = function() { $scope.isLock ? $scope.screen.mozUnlockOrientation() : $scope.screen.mozLockOrientation($scope.screen.mozOrientation); $scope.isLock = !$scope.isLock; } } })();
(function() { 'use strict'; angular.module('sensors.components') .controller('MenuController', MenuController); function MenuController($scope, $window, menuItems, openLinkTobrowser) { $scope.items = []; $scope.isLock = true; $scope.screen = $window.screen; $scope.openLink = openLinkTobrowser.open; angular.forEach(menuItems, function(item) { $scope.items.push({ title: item, state: 'app.' + item }) }); // 初期起動時は画面の回転をロックする $scope.screen.mozLockOrientation($scope.screen.mozOrientation); //////////// $scope.toggleLockOrientation = function() { $scope.isLock ? $scope.screen.mozUnlockOrientation() : $scope.screen.mozLockOrientation($scope.screen.mozOrientation); $scope.isLock = !$scope.isLock; } } })();
Build constraints for cairo packages should be based on cairo-naming, not use pango-naming.
// +build !cairo_1_10,!cairo_1_12,!cairo_1_14 package cairo // #include <stdlib.h> // #include <cairo.h> // #include <cairo-gobject.h> import "C" import ( "unsafe" ) // GetVariations is a wrapper around cairo_font_options_get_variations(). func (o *FontOptions) GetVariations() string { return C.GoString(C.cairo_font_options_get_variations(o.native)) } // SetVariations is a wrapper around cairo_font_options_set_variations(). func (o *FontOptions) SetVariations(variations string) { var cvariations *C.char if variations != "" { cvariations = C.CString(variations) // Cairo will call strdup on its own. defer C.free(unsafe.Pointer(cvariations)) } C.cairo_font_options_set_variations(o.native, cvariations) }
// +build !pango_1_10,!pango_1_12,!pango_1_14 package cairo // #include <stdlib.h> // #include <cairo.h> // #include <cairo-gobject.h> import "C" import ( "unsafe" ) // GetVariations is a wrapper around cairo_font_options_get_variations(). func (o *FontOptions) GetVariations() string { return C.GoString(C.cairo_font_options_get_variations(o.native)) } // SetVariations is a wrapper around cairo_font_options_set_variations(). func (o *FontOptions) SetVariations(variations string) { var cvariations *C.char if variations != "" { cvariations = C.CString(variations) // Cairo will call strdup on its own. defer C.free(unsafe.Pointer(cvariations)) } C.cairo_font_options_set_variations(o.native, cvariations) }
Add alert for posted comment
<?php use Laracasts\Commander\CommanderTrait; use Nook\Statuses\LeaveCommentOnStatusCommand; use Nook\Forms\LeaveCommentForm; /** * Class CommentsController */ class CommentsController extends BaseController { use CommanderTrait; /** * @var LeaveCommentForm */ protected $leaveCommentFormForm; /** * Constructor. * * @param LeaveCommentForm $leaveCommentFormForm */ public function __construct(LeaveCommentForm $leaveCommentFormForm) { $this->leaveCommentFormForm = $leaveCommentFormForm; } /** * Leave a new comment. * * @return Response */ public function store() { // Fetch the input $input = array_add(Input::all(), 'user_id', Auth::id()); // Validate the input $this->leaveCommentFormForm->validate($input); // Execute a command to leave a comment $this->execute(LeaveCommentOnStatusCommand::class, $input); Flash::message('Your comment has been posted!'); // Return response $response = [ 'success' => true, 'message' => 'The comment has been successfully posted.' ]; return Response::json($response); } }
<?php use Laracasts\Commander\CommanderTrait; use Nook\Statuses\LeaveCommentOnStatusCommand; use Nook\Forms\LeaveCommentForm; /** * Class CommentsController */ class CommentsController extends BaseController { use CommanderTrait; /** * @var LeaveCommentForm */ protected $leaveCommentFormForm; /** * Constructor. * * @param LeaveCommentForm $leaveCommentFormForm */ public function __construct(LeaveCommentForm $leaveCommentFormForm) { $this->leaveCommentFormForm = $leaveCommentFormForm; } /** * Leave a new comment. * * @return Response */ public function store() { // Fetch the input $input = array_add(Input::all(), 'user_id', Auth::id()); // Validate the input $this->leaveCommentFormForm->validate($input); // Execute a command to leave a comment $this->execute(LeaveCommentOnStatusCommand::class, $input); // Return response $response = [ 'success' => true, 'message' => 'The comment has been successfully posted.' ]; return Response::json($response); } }
Add FIXME note in recursive reduction rule node.
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.premises.Premise; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.profiles.BranchProfile; import com.oracle.truffle.api.source.SourceSection; // FIXME this is not the point where this should be implemented. it should be the responsibilty of the RuleUnionNode public class RecursiveReductionRule extends ReductionRule { public RecursiveReductionRule(SourceSection source, FrameDescriptor fd, RuleKind kind, String arrowName, Class<?> dispatchClass, RuleInputsNode inputsNode, Premise[] premises, RuleTarget output) { super(source, fd, kind, arrowName, dispatchClass, inputsNode, premises, output); } private final BranchProfile recurTaken = BranchProfile.create(); @Override public RuleResult execute(VirtualFrame frame) { RuleResult result = null; boolean repeat = true; while (repeat) { try { result = super.execute(frame); repeat = false; } catch (RecurException recex) { recurTaken.enter(); repeat = true; } } assert result != null; return result; } }
package org.metaborg.meta.lang.dynsem.interpreter.nodes.rules; import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.premises.Premise; import com.oracle.truffle.api.frame.FrameDescriptor; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.profiles.BranchProfile; import com.oracle.truffle.api.source.SourceSection; public class RecursiveReductionRule extends ReductionRule { public RecursiveReductionRule(SourceSection source, FrameDescriptor fd, RuleKind kind, String arrowName, Class<?> dispatchClass, RuleInputsNode inputsNode, Premise[] premises, RuleTarget output) { super(source, fd, kind, arrowName, dispatchClass, inputsNode, premises, output); } private final BranchProfile recurTaken = BranchProfile.create(); @Override public RuleResult execute(VirtualFrame frame) { RuleResult result = null; boolean repeat = true; while (repeat) { try { result = super.execute(frame); repeat = false; } catch (RecurException recex) { recurTaken.enter(); repeat = true; } } assert result != null; return result; } }