text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix to fix to fix a fix.
package com.letscode.lcg; import java.util.Random; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; public class Main { public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); String hostname = args.length > 0 ? args[0] : "localhost"; int port = args.length > 1 ? Integer.parseInt(args[1]) : 80; String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124)); cfg.title = "Lambda Cipher Genesis - " + nickname; cfg.useGL20 = false; { cfg.width = 1024; cfg.height = 600; } new LwjglApplication(new LcgApp(hostname, port, nickname), cfg); } }
package com.letscode.lcg; import java.util.Random; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; public class Main { public static void main(String[] args) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); String hostname = args.length > 0 ? args[0] : "localhost"; int port = args.length > 1 ? Integer.parseInt(args[1]) : g; String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124)); cfg.title = "Lambda Cipher Genesis - " + nickname; cfg.useGL20 = false; { cfg.width = 1024; cfg.height = 600; } new LwjglApplication(new LcgApp(hostname, port, nickname), cfg); } }
Increase attempts for loading ticker
import req from '../req.js'; import Event from '../Event'; export default function Ticker() { this.event = new Event(); this.ready = false; this.data = {}; this.load(); setInterval(() => {this.load()}, 60*1000) // Refresh every 60 seconds } const MAX_ATTEMPTS = 120; Ticker.prototype.load = function(attempt) { if (attempt >= MAX_ATTEMPTS) { return; } req.getJson('https://api.stellarterm.com/v1/ticker.json') .then(tickerData => { this.ready = true; this.data = tickerData; console.log('Loaded ticker. Data generated ' + Math.round((new Date() - this.data._meta.start * 1000)/1000) + ' seconds ago.') this.event.trigger(); }) .catch(e => { console.log('Unable to load ticker', e); if (!attempt) { attempt = 0; } setTimeout(() => { this.load(attempt + 1); }, 1000) }) }
import req from '../req.js'; import Event from '../Event'; export default function Ticker() { this.event = new Event(); this.ready = false; this.data = {}; this.load(); setInterval(() => {this.load()}, 60*1000) // Refresh every 60 seconds } const MAX_ATTEMPTS = 5; Ticker.prototype.load = function(attempt) { if (attempt >= MAX_ATTEMPTS) { return; } req.getJson('https://api.stellarterm.com/v1/ticker.json') .then(tickerData => { this.ready = true; this.data = tickerData; console.log('Loaded ticker. Data generated ' + Math.round((new Date() - this.data._meta.start * 1000)/1000) + ' seconds ago.') this.event.trigger(); }) .catch(e => { console.log('Unable to load ticker', e); if (!attempt) { attempt = 0; } setTimeout(() => { this.load(attempt + 1); }, 100) }) }
Add state routing to example
import React from "react" import ReactDOM from "react-dom" import ReactTestUtils from "react-addons-test-utils" import * as Testdown from "../index.js" import exampleSuite from "./example-suite.md" let state const actions = { increment: () => setState({ counter: state.counter + 1 }), } class App extends React.Component { render() { return ( <div data-role="app"> <span data-role="counter"> {this.props.counter} </span> <button data-role="button" onClick={actions.increment} > Click me </button> </div> ) } } document.body.innerHTML += '<div id="app"/>' function setState(newState) { location.hash = JSON.stringify({ ...state, ...newState }) } window.onhashchange = function(hash) { console.info("hashchange") state = JSON.parse(location.hash.substr(1)) ReactDOM.render(<App {...state}/>, app) } if (location.hash) { onhashchange() } else { setState({ counter: 0 }) } window.test = function test() { const suite = Testdown.parseSuite(exampleSuite) Testdown.runSuiteSequentially(suite, { root: app, locate: Testdown.locate, ...Testdown.reactConfiguration({ ReactTestUtils }), }).then(x => console.info(x)) } setTimeout(test, 0)
import React from "react" import ReactDOM from "react-dom" import ReactTestUtils from "react-addons-test-utils" import * as Testdown from "../index.js" import exampleSuite from "./example-suite.md" let state class App extends React.Component { render() { return ( <div data-role="app"> <button data-role="button">Click me</button> </div> ) } } document.body.innerHTML += '<div id="app"/>' function setState(newState) { state = newState ReactDOM.render(<App state={state}/>, app) } setState({}) window.test = function test() { const suite = Testdown.parseSuite(exampleSuite) Testdown.runSuiteSequentially(suite, { root: app, locate: Testdown.locate, ...Testdown.reactConfiguration({ ReactTestUtils }), }).then(x => console.info(x)) } test()
Fix format of messages for teamcity: 1. Replace " by ' - because Teamcity can't process messages with " 2. Change messages structrure
"use strict"; var util = require("util"); /** * @param {Errors[]} errorsCollection */ module.exports = function(errorsCollection) { var errorCount = 0; console.log(util.format("##teamcity[testSuiteStarted name='JSCS']")); /** * Formatting every error set. */ errorsCollection.forEach(function(errors) { var file = errors.getFilename(); if (!errors.isEmpty()) { errors.getErrorList().forEach(function(error) { errorCount++; console.log(util.format("##teamcity[testStarted name='%s']", file)); console.log(util.format("##teamcity[testFailed name='%s' message='line %d, col %d, %s']", file, error.line, error.column, error.message)); }); } }); if (errorCount === 0) { console.log(util.format("##teamcity[testStarted name='JSCS']")); console.log(util.format("##teamcity[testFinished name='JSCS']")); } console.log(util.format("##teamcity[testSuiteFinished name='JSCS']")); };
'use strict'; var util = require('util'); /** * @param {Errors[]} errorsCollection */ module.exports = function(errorsCollection) { var errorCount = 0; /** * Formatting every error set. */ errorsCollection.forEach(function(errors) { var file = errors.getFilename(); console.log(util.format('##teamcity[testSuiteStarted name="JSCS: %s"]', file)); if (!errors.isEmpty()) { errors.getErrorList().forEach(function(error) { errorCount++; console.log(util.format('##teamcity[testStarted name="%s"]', file)); console.log(util.format('##teamcity[testFailed name="%s" message="line %d, col %d, %s"]', file, error.line, error.column, error.message)); }); console.log(util.format('##teamcity[testSuiteFinished name="JSCS: %s"]', file)); } }); if (!errorCount) { console.log('##teamcity[testStarted name="JSCS"]'); console.log('##teamcity[testFinished name="JSCS"]'); } };
Remove "software" card from Cultura conf
# -*- coding: utf-8 -*- """Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
# -*- coding: utf-8 -*- """Ideaxbox Cultura, France""" from .idb import * # noqa from django.utils.translation import ugettext_lazy as _ IDEASCUBE_NAME = u"Cultura" IDEASCUBE_PLACE_NAME = _("city") COUNTRIES_FIRST = ['FR'] TIME_ZONE = None LANGUAGE_CODE = 'fr' LOAN_DURATION = 14 MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender'] USER_FORM_FIELDS = ( (_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa ) HOME_CARDS = HOME_CARDS + [ { 'id': 'cpassorcier', }, { 'id': 'wikisource', }, { 'id': 'software', }, { 'id': 'ted', }, { 'id': 'ubuntudoc', }, ]
Check for error and print when waiting for a particular table status.
exports.runWhenTableIs = function (tableName, desiredStatus, db, callback) { var describeParams = {}; describeParams.TableName = tableName; db.describeTable(describeParams, function (err, data) { if (err) { console.log(err); } else if (data.Table.TableStatus === desiredStatus) { callback(); } else{ var waitTimeMs = 1000; setTimeout(function () { console.log('table status is ' + data.Table.TableStatus); console.log('waiting ' + waitTimeMs + 'ms for table status to be ' + desiredStatus); exports.runWhenTableIs(tableName, desiredStatus, db, callback); }, waitTimeMs); } }); }
exports.runWhenTableIs = function (tableName, desiredStatus, db, callback) { var describeParams = {}; describeParams.TableName = tableName; db.describeTable(describeParams, function (err, data) { if (data.Table.TableStatus === desiredStatus) { callback(); } else{ var waitTimeMs = 1000; setTimeout(function () { console.log('table status is ' + data.Table.TableStatus); console.log('waiting ' + waitTimeMs + 'ms for table status to be ' + desiredStatus); exports.runWhenTableIs(tableName, desiredStatus, db, callback); }, waitTimeMs); } }); }
Decrease log level for memcache setup
"""The application's Globals object""" import logging import memcache log = logging.getLogger(__name__) class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self, config): """One instance of Globals is created during application initialization and is available during requests via the 'app_globals' variable """ if 'memcached.server' in config: self.cache = memcache.Client([config['memcached.server']]) log.debug("Memcache set up") log.debug("Flushing cache") self.cache.flush_all() else: log.warn("Skipped memcache, no results caching will take place.") self.cache = None if 'adhocracy.instance' in config: self.single_instance = config.get('adhocracy.instance') else: self.single_instance = None
"""The application's Globals object""" import logging import memcache log = logging.getLogger(__name__) class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self, config): """One instance of Globals is created during application initialization and is available during requests via the 'app_globals' variable """ if 'memcached.server' in config: self.cache = memcache.Client([config['memcached.server']]) log.info("Memcache set up") log.debug("Flushing cache") self.cache.flush_all() else: log.warn("Skipped memcache, no results caching will take place.") self.cache = None if 'adhocracy.instance' in config: self.single_instance = config.get('adhocracy.instance') else: self.single_instance = None
Add info about version to log
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Turtle Control Software v' + version_info) logger.info('[PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
from killer import kill from log import logname import os import argparse import sys from version import version_info logger = logname() def start_server(): logger.info('Starting Turtle Control System... [PID:%s PPID:%s]', os.getpid(), os.getppid()) kill() logger.info('Starting new server instance...') # logger.info('Battery: %s', frame.readBatteryVoltage()) try: from sockets import web, app import frame web.run_app(app, host='0.0.0.0', port=5000) except OSError as e: logger.error(e) if __name__ == '__main__': parser = argparse.ArgumentParser( description='This is the Turtle WebSocket Server.') parser.add_argument('-v', action='version', version=version_info,help='Show the version number and exit') parser.add_argument('start', nargs='?', help='Start the server') args = parser.parse_args() if args.start is None: start_server()
Make it easy to see what mount is giving us.
// Copyright 2015 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. // mount_gcsfuse is a small helper for using gcsfuse with mount(8). // // mount_gcsfuse can be invoked using a command-line of the form expected for // mount helpers. It simply calls the gcsfuse binary, which must be in $PATH, // and waits for it to complete. // // mount_gcsfuse does not daemonize, and therefore must be used with a wrapper // that performs daemonization if it is to be used directly with mount(8). package main import ( "log" "os" ) func main() { // Print out each argument. for i, arg := range os.Args { log.Printf("Arg %d: %q", i, arg) } os.Exit(1) }
// Copyright 2015 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. // mount_gcsfuse is a small helper for using gcsfuse with mount(8). // // mount_gcsfuse can be invoked using a command-line of the form expected for // mount helpers. It simply calls the gcsfuse binary, which must be in $PATH, // and waits for it to complete. // // mount_gcsfuse does not daemonize, and therefore must be used with a wrapper // that performs daemonization if it is to be used directly with mount(8). package main
Update issue accessor functions for Sequelize
const db = require('./postgresql'); const { VOTING_FINISHED } = require('../../common/actionTypes/issues'); const Question = db.sequelize.models.issue; async function addIssue(issue) { return Question.create(issue); } function getConcludedIssues(genfors) { const id = genfors.id || genfors; return Question.findAll({ where: { genforsId: id, deleted: false, active: false }, }); } const getIssueById = id => ( Question.findOne({ where: { id } }) ); function getActiveQuestion(genfors) { return Question.findOne({ where: { genforsId: genfors, active: true, deleted: false }, }); } async function updateIssue(issueOrId, data) { const id = issueOrId.id || issueOrId; const issue = await getIssueById(id); return Object.assign(issue, data).save(); } async function deleteIssue(issue) { const id = issue.id || issue; return updateIssue(id, { active: false, deleted: true, status: VOTING_FINISHED }, { new: true }); } function endIssue(issue) { const id = issue.id || issue; return updateIssue(id, { active: false, status: VOTING_FINISHED }, { new: true }); } module.exports = { addIssue, getActiveQuestion, getClosedQuestions: getConcludedIssues, getIssueById, getConcludedIssues, endIssue, deleteIssue, updateIssue, };
const db = require('./postgresql'); const { VOTING_FINISHED } = require('../../common/actionTypes/issues'); const Question = db.sequelize.models.issue; async function addIssue(issue) { return Question.create(issue); } function getConcludedIssues(genfors) { const id = genfors.id || genfors; return Question.findOne({ where: { id, deleted: false, active: false }, }); } const getIssueById = id => ( Question.findOne({ _id: id }) ); function getActiveQuestion(genfors) { return Question.findOne({ genfors, active: true, deleted: false }); } function endIssue(issue) { return Question.findByIdAndUpdate(issue, { active: false, status: VOTING_FINISHED }, { new: true }); } function deleteIssue(issue) { return Question.findByIdAndUpdate(issue, { active: false, deleted: true, status: VOTING_FINISHED }, { new: true }); } function updateIssue(issue, data, options) { return Question.findOneAndUpdate(issue, data, options); } module.exports = { addIssue, getActiveQuestion, getClosedQuestions: getConcludedIssues, getIssueById, getConcludedIssues, endIssue, deleteIssue, updateIssue, };
Remove unused user model import handling
from rest_framework import exceptions from rest_framework_jwt.settings import api_settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication from .models import User jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ try: user = User.objects.get( pk=payload['user_id'], email=payload['email'], token_version=payload['token_version'], is_active=True ) except User.DoesNotExist: msg = 'Invalid signature' raise exceptions.AuthenticationFailed(msg) return user
from rest_framework import exceptions from rest_framework_jwt.settings import api_settings from rest_framework_jwt.authentication import JSONWebTokenAuthentication try: from django.contrib.auth import get_user_model except ImportError: # Django < 1.5 from django.contrib.auth.models import User else: User = get_user_model() jwt_decode_handler = api_settings.JWT_DECODE_HANDLER class JWTAuthentication(JSONWebTokenAuthentication): def authenticate_credentials(self, payload): """ Returns an active user that matches the payload's user id and email. """ try: user = User.objects.get( pk=payload['user_id'], email=payload['email'], token_version=payload['token_version'], is_active=True ) except User.DoesNotExist: msg = 'Invalid signature' raise exceptions.AuthenticationFailed(msg) return user
Add scipy as a dependency of jaxlib. Jaxlib depends on LAPACK kernels provided by Scipy.
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup from glob import glob import os binary_libs = [os.path.basename(f) for f in glob('jaxlib/*.so*')] setup( name='jaxlib', version='0.1.4', description='XLA library for JAX', author='JAX team', author_email='jax-dev@google.com', packages=['jaxlib'], install_requires=['scipy', 'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py'], url='https://github.com/google/jax', license='Apache-2.0', package_data={'jaxlib': binary_libs}, )
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup from glob import glob import os binary_libs = [os.path.basename(f) for f in glob('jaxlib/*.so*')] setup( name='jaxlib', version='0.1.4', description='XLA library for JAX', author='JAX team', author_email='jax-dev@google.com', packages=['jaxlib'], install_requires=['numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py'], url='https://github.com/google/jax', license='Apache-2.0', package_data={'jaxlib': binary_libs}, )
Update to use partial instead of lambda function
from functools import partial import six from graphql.core.type import GraphQLUnionType from .base import FieldsClassType, FieldsClassTypeMeta, FieldsOptions class UnionTypeOptions(FieldsOptions): def __init__(self, *args, **kwargs): super(UnionTypeOptions, self).__init__(*args, **kwargs) self.types = [] class UnionTypeMeta(FieldsClassTypeMeta): options_class = UnionTypeOptions def get_options(cls, meta): return cls.options_class(meta, types=[]) class UnionType(six.with_metaclass(UnionTypeMeta, FieldsClassType)): class Meta: abstract = True @classmethod def _resolve_type(cls, schema, instance, *args): return schema.T(instance.__class__) @classmethod def internal_type(cls, schema): if cls._meta.abstract: raise Exception("Abstract ObjectTypes don't have a specific type.") return GraphQLUnionType( cls._meta.type_name, types=list(map(schema.T, cls._meta.types)), resolve_type=partial(cls._resolve_type, schema), description=cls._meta.description, )
import six from graphql.core.type import GraphQLUnionType from .base import FieldsClassType, FieldsClassTypeMeta, FieldsOptions class UnionTypeOptions(FieldsOptions): def __init__(self, *args, **kwargs): super(UnionTypeOptions, self).__init__(*args, **kwargs) self.types = [] class UnionTypeMeta(FieldsClassTypeMeta): options_class = UnionTypeOptions def get_options(cls, meta): return cls.options_class(meta, types=[]) class UnionType(six.with_metaclass(UnionTypeMeta, FieldsClassType)): class Meta: abstract = True @classmethod def _resolve_type(cls, schema, instance, *args): return schema.T(instance.__class__) @classmethod def internal_type(cls, schema): if cls._meta.abstract: raise Exception("Abstract ObjectTypes don't have a specific type.") return GraphQLUnionType( cls._meta.type_name, types=list(map(schema.T, cls._meta.types)), resolve_type=lambda instance, info: cls._resolve_type(schema, instance, info), description=cls._meta.description, )
Make parameter resolution backwards compatible
package com.codicesoftware.plugins.hudson.util; import hudson.Util; import hudson.model.ParameterValue; import java.util.HashMap; import java.util.List; import java.util.Map; public class SelectorParametersResolver { public static String resolve(String text, List<ParameterValue> parameters) { if (parameters == null) { return text; } Map<String, String> parametersMap = new HashMap<>(); for (ParameterValue parameter : parameters) { if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) { parametersMap.put(parameter.getName(), parameter.getValue().toString()); } } return Util.replaceMacro( resolveLegacyFormat(text, parametersMap), parametersMap); } static String resolveLegacyFormat(String text, Map<String, String> parametersMap) { String result = text; for (Map.Entry<String, String> entry : parametersMap.entrySet()) { result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue()); } return result; } }
package com.codicesoftware.plugins.hudson.util; import hudson.Util; import hudson.model.ParameterValue; import java.util.HashMap; import java.util.List; import java.util.Map; public class SelectorParametersResolver { public static String resolve(String text, List<ParameterValue> parameters) { if (parameters == null) { return text; } Map<String, String> parametersMap = new HashMap<>(); for (ParameterValue parameter : parameters) { if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) { parametersMap.put(parameter.getName(), parameter.getValue().toString()); } } return Util.replaceMacro(text, parametersMap); } }
Add pages to admin UI menu
'use strict'; var express = require('express'); var co = require('collections-online'); // This allows loading of environment variables from a .env file require('dotenv').config({silent: true}); // Loading the configuration var config = require('./config'); // Creating an express app var app = express(); // Set up Keystone var keystone = require('keystone'); keystone.init({ 'name': 'KBH-billeder', 'static': ['generated'], 'views': 'app/views', 'view engine': 'jade', 'auto update': true, 'mongo': 'mongodb://localhost/kbh-billeder', 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '1234' }); keystone.import('./models'); keystone.set('routes', require('./routes')); keystone.set('nav', { users: 'users', pages: 'pages', }); keystone.mount('/content', app, function() { }); // Asking collections online to set-up itself co.initialize(app, config);
'use strict'; var express = require('express'); var co = require('collections-online'); // This allows loading of environment variables from a .env file require('dotenv').config({silent: true}); // Loading the configuration var config = require('./config'); // Creating an express app var app = express(); // Set up Keystone var keystone = require('keystone'); keystone.init({ 'name': 'KBH-billeder', 'static': ['generated'], 'views': 'app/views', 'view engine': 'jade', 'auto update': true, 'mongo': 'mongodb://localhost/kbh-billeder', 'session': true, 'auth': true, 'user model': 'User', 'cookie secret': '1234' }); keystone.import('./models'); keystone.set('routes', require('./routes')); keystone.set('nav', { users: 'users', }); keystone.mount('/content', app, function() { }); // Asking collections online to set-up itself co.initialize(app, config);
Fix HTTP redirects to be absolute
<?php include_once 'models/dependencies.php'; include_once 'header.php'; if ( isset( $_GET[ 'resource' ] ) ) { $resource = $_GET[ 'resource' ]; } else { $resource = ''; } $resource = basename( $resource ); $filename = 'controllers/' . $resource . '.php'; if ( !file_exists( $filename ) ) { $resource = 'dashboard'; $filename = 'controllers/' . $resource . '.php'; } include_once $filename; $controllername = ucfirst( $resource ) . 'Controller'; $controller = new $controllername(); try { $controller->dispatch( $_GET, $_POST, $_FILES, $_SERVER[ 'REQUEST_METHOD' ] ); } catch ( NotImplemented $e ) { die( 'An attempt was made to call a not implemented function: ' . $e->getFunctionName() ); } catch ( RedirectException $e ) { global $config; $url = $e->getURL(); header( 'Location: ' . $config[ 'base' ] . $url ); } catch ( HTTPErrorException $e ) { header( $e->header ); } ?>
<?php include_once 'models/dependencies.php'; include_once 'header.php'; if ( isset( $_GET[ 'resource' ] ) ) { $resource = $_GET[ 'resource' ]; } else { $resource = ''; } $resource = basename( $resource ); $filename = 'controllers/' . $resource . '.php'; if ( !file_exists( $filename ) ) { $resource = 'dashboard'; $filename = 'controllers/' . $resource . '.php'; } include_once $filename; $controllername = ucfirst( $resource ) . 'Controller'; $controller = new $controllername(); try { $controller->dispatch( $_GET, $_POST, $_FILES, $_SERVER[ 'REQUEST_METHOD' ] ); } catch ( NotImplemented $e ) { die( 'An attempt was made to call a not implemented function: ' . $e->getFunctionName() ); } catch ( RedirectException $e ) { $url = $e->getURL(); header( 'Location: ' . $url ); } catch ( HTTPErrorException $e ) { header( $e->header ); } ?>
Fix for not setting Gofig global/user dirs This patch fixes the issue where the Gofig's global (/etc) and user ($HOME) directories were not set, resulting in the default config files not being loaded.
package core import ( "fmt" "github.com/akutz/gofig" "github.com/emccode/rexray/util" ) func init() { initDrivers() gofig.SetGlobalConfigPath(util.EtcDirPath()) gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", util.HomeDir())) gofig.Register(globalRegistration()) gofig.Register(driverRegistration()) } func globalRegistration() *gofig.Registration { r := gofig.NewRegistration("Global") r.Yaml(` rexray: host: tcp://:7979 logLevel: warn `) r.Key(gofig.String, "h", "tcp://:7979", "The REX-Ray host", "rexray.host") r.Key(gofig.String, "l", "warn", "The log level (error, warn, info, debug)", "rexray.logLevel") return r } func driverRegistration() *gofig.Registration { r := gofig.NewRegistration("Driver") r.Yaml(` rexray: osDrivers: - linux storageDrivers: - libstorage volumeDrivers: - docker `) r.Key(gofig.String, "", "linux", "The OS drivers to consider", "rexray.osDrivers") r.Key(gofig.String, "", "", "The storage drivers to consider", "rexray.storageDrivers") r.Key(gofig.String, "", "docker", "The volume drivers to consider", "rexray.volumeDrivers") return r }
package core import ( "github.com/akutz/gofig" ) func init() { initDrivers() gofig.Register(globalRegistration()) gofig.Register(driverRegistration()) } func globalRegistration() *gofig.Registration { r := gofig.NewRegistration("Global") r.Yaml(` rexray: host: tcp://:7979 logLevel: warn `) r.Key(gofig.String, "h", "tcp://:7979", "The REX-Ray host", "rexray.host") r.Key(gofig.String, "l", "warn", "The log level (error, warn, info, debug)", "rexray.logLevel") return r } func driverRegistration() *gofig.Registration { r := gofig.NewRegistration("Driver") r.Yaml(` rexray: osDrivers: - linux storageDrivers: - libstorage volumeDrivers: - docker `) r.Key(gofig.String, "", "linux", "The OS drivers to consider", "rexray.osDrivers") r.Key(gofig.String, "", "", "The storage drivers to consider", "rexray.storageDrivers") r.Key(gofig.String, "", "docker", "The volume drivers to consider", "rexray.volumeDrivers") return r }
[Streams] Reset non-blocking to be safe
<?php namespace React\Socket; use Evenement\EventEmitter; use React\EventLoop\LoopInterface; use React\Stream\WritableStreamInterface; use React\Stream\Buffer; use React\Stream\Stream; use React\Stream\Util; class Connection extends Stream implements ConnectionInterface { public function handleData($stream) { $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' === $data || false === $data || feof($stream)) { $this->end(); } else { $this->emit('data', array($data, $this)); } } public function handleClose() { if (is_resource($this->stream)) { // http://chat.stackoverflow.com/transcript/message/7727858#7727858 stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR); stream_set_blocking($this->stream, false); fclose($this->stream); } } public function getRemoteAddress() { return $this->parseAddress(stream_socket_get_name($this->stream, true)); } private function parseAddress($address) { return trim(substr($address, 0, strrpos($address, ':')), '[]'); } }
<?php namespace React\Socket; use Evenement\EventEmitter; use React\EventLoop\LoopInterface; use React\Stream\WritableStreamInterface; use React\Stream\Buffer; use React\Stream\Stream; use React\Stream\Util; class Connection extends Stream implements ConnectionInterface { public function handleData($stream) { $data = stream_socket_recvfrom($stream, $this->bufferSize); if ('' === $data || false === $data || feof($stream)) { $this->end(); } else { $this->emit('data', array($data, $this)); } } public function handleClose() { if (is_resource($this->stream)) { stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR); fclose($this->stream); } } public function getRemoteAddress() { return $this->parseAddress(stream_socket_get_name($this->stream, true)); } private function parseAddress($address) { return trim(substr($address, 0, strrpos($address, ':')), '[]'); } }
Replace sendAction with a function call.
import Ember from 'ember'; import layout from '../templates/components/resize-detector'; const { inject: { service }, run: { scheduleOnce, bind } } = Ember; export default Ember.Component.extend({ layout, tagName: '', resizeDetector: service(), didInsertElement() { this._super(...arguments); scheduleOnce('afterRender', this, this.setup); }, setup() { this.callback = bind(this, this.onResize); this.get('resizeDetector').setup(this.get('selector'), this.callback); }, teardown() { this.get('resizeDetector').teardown(this.get('selector'), this.callback); }, onResize(element) { if (this.get('isDestroyed') || this.get('isDestroying')) { return; } let $el = Ember.$(element); this.get('on-resize')({ width: $el.width(), height: $el.height() }, element); }, willDestroyElement() { this.teardown(); this._super(...arguments); } }).reopenClass({ positionalParams: ['selector'] });
import Ember from 'ember'; import layout from '../templates/components/resize-detector'; const { inject: { service }, run: { scheduleOnce, bind } } = Ember; export default Ember.Component.extend({ layout, tagName: '', resizeDetector: service(), didInsertElement() { this._super(...arguments); scheduleOnce('afterRender', this, this.setup); }, setup() { this.callback = bind(this, this.onResize); this.get('resizeDetector').setup(this.get('selector'), this.callback); }, teardown() { this.get('resizeDetector').teardown(this.get('selector'), this.callback); }, onResize(element) { if (this.get('isDestroyed') || this.get('isDestroying')) { return; } let $el = Ember.$(element); this.sendAction('on-resize', { width: $el.width(), height: $el.height() }, element); }, willDestroyElement() { this.teardown(); this._super(...arguments); } }).reopenClass({ positionalParams: ['selector'] });
:art: Make spyOnTree() an arrow function
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const processTree = require("../lib/process-tree"); let treeSpy = function(logTree, runningProcess) { let spy = { }; spy.tree = logTree; spy.process = runningProcess; spy.messages = [ ]; spy.log = function(message) { spy.messages.push(message) }; return spy; }; let spy; let spyOnTree = async (done, setup) => { spy = await processTree(treeSpy, setup) done(); }; describe("a processTree with no children", () => { beforeEach(done => { spyOnTree(done, function(o) { }); }); it("returns a spy", () => { expect(spy.tree).toBeDefined(); }); });
// Copyright (c) 2017 The Regents of the University of Michigan. // All Rights Reserved. Licensed according to the terms of the Revised // BSD License. See LICENSE.txt for details. const processTree = require("../lib/process-tree"); let treeSpy = function(logTree, runningProcess) { let spy = { }; spy.tree = logTree; spy.process = runningProcess; spy.messages = [ ]; spy.log = function(message) { spy.messages.push(message) }; return spy; }; let spy; let spyOnTree = async function(done, setup) { spy = await processTree(treeSpy, setup) done(); }; describe("a processTree with no children", () => { beforeEach(done => { spyOnTree(done, function(o) { }); }); it("returns a spy", () => { expect(spy.tree).toBeDefined(); }); });
Increase Pypi version. New package uploaded to Pypi already. PiperOrigin-RevId: 435120795 Change-Id: Idaed3713248afaeefad2eac345d6cd4d6b37bef9
# Copyright 2022 Google LLC. # # 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. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '4' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
# Copyright 2022 Google LLC. # # 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. # coding=utf-8 # python3 """Package metadata for RLDS. This is kept in a separate module so that it can be imported from setup.py, at a time when RLDS's dependencies may not have been installed yet. """ # We follow Semantic Versioning (https://semver.org/) _MAJOR_VERSION = '0' _MINOR_VERSION = '1' _PATCH_VERSION = '3' # Example: '0.4.2' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION])
Create observable out of promise explicitly for better understanding
Rx.Observable .fromEvent(document.getElementById("search"), "keyup") .map(event => { return event.target.value; }) .switchMap(searchQuery => { return Rx.Observable.fromPromise( axios.get("http://localhost:3334/movies/" + searchQuery) ); }) .map(results => { /*var movies = results[0].data; var tv = results[1].data; return movies.concat(tv);*/ return results.data; }) .subscribe(results => { renderResults(results); }); function renderResults(results) { var searchResultsElement = document.getElementById("searchResults"); searchResultsElement.innerHTML = ""; for (var i = 0; i < results.length; i++) { var el = document.createElement("li"); el.innerHTML = results[i]; searchResultsElement.appendChild(el); } }
Rx.Observable .fromEvent(document.getElementById("search"), "keyup") .map(event => { return event.target.value; }) .switchMap(searchQuery => { /*return axios.all([ axios.get("http://localhost:3334/movies/" + searchQuery), axios.get("http://localhost:3334/tv/" + searchQuery) ]);*/ return axios.get("http://localhost:3334/movies/" + searchQuery); }) .map(results => { /*var movies = results[0].data; var tv = results[1].data; return movies.concat(tv);*/ return results.data; }) .subscribe(results => { renderResults(results); }); function renderResults(results) { var searchResultsElement = document.getElementById("searchResults"); searchResultsElement.innerHTML = ""; for (var i = 0; i < results.length; i++) { var el = document.createElement("li"); el.innerHTML = results[i]; searchResultsElement.appendChild(el); } }
Put in a temporary fix for the layout system.
import _ from 'underscore'; import React from 'react'; import equip from './equip'; import PostsGrid from '../StaticResponsiveGrid'; import Post from './Post'; const Posts = ({ style, posts, added }) => { let i = -1; const postCards = _.mapObject(posts, (post) => { const props = { post, style, added, }; i++; return ( <div key={i}> <Post {...props} /> </div> ); }); return ( <PostsGrid itemWidth={style.width} itemHeight={style.height} maxWidth={1600} items={_.values(postCards)} /> ); }; export default equip(Posts);
import _ from 'underscore'; import React from 'react'; import equip from './equip'; import PostsGrid from '../StaticResponsiveGrid'; import Post from './Post'; const Posts = ({ style, posts, added }) => { const postCards = _.mapObject(posts, (post, id) => { const props = { post, style, added, }; return ( <div key={id}> <Post {...props} /> </div> ); }); return ( <PostsGrid itemWidth={style.width} itemHeight={style.height} maxWidth={1600} items={_.values(postCards)} /> ); }; export default equip(Posts);
Remove changelog from release description
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "ali@indydevs.org" __copyright__ = "Copyright 2014, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) setup( name="Flask-Limiter", author=__author__, author_email=__email__, license="MIT", url="https://flask-limiter.readthedocs.org", zip_safe=False, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), install_requires=list(REQUIREMENTS), classifiers=[k for k in open("CLASSIFIERS").read().split("\n") if k], description="Rate limiting for flask applications", long_description=open("README.rst").read(), packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", )
""" setup.py for Flask-Limiter """ __author__ = "Ali-Akber Saifee" __email__ = "ali@indydevs.org" __copyright__ = "Copyright 2014, Ali-Akber Saifee" from setuptools import setup, find_packages import os import versioneer this_dir = os.path.abspath(os.path.dirname(__file__)) REQUIREMENTS = filter( None, open(os.path.join(this_dir, "requirements", "main.txt")).read().splitlines() ) setup( name="Flask-Limiter", author=__author__, author_email=__email__, license="MIT", url="https://flask-limiter.readthedocs.org", zip_safe=False, version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), install_requires=list(REQUIREMENTS), classifiers=[k for k in open("CLASSIFIERS").read().split("\n") if k], description="Rate limiting for flask applications", long_description=open("README.rst").read() + open("HISTORY.rst").read(), packages=find_packages(exclude=["tests*"]), python_requires=">=3.7", )
Fix error with operator precedence
'use babel'; import editorconfig from 'editorconfig'; import generateConfig from './commands/generate'; function init(editor) { generateConfig(); if (!editor) { return; } const file = editor.getURI(); if (!file) { return; } editorconfig.parse(file).then(config => { if (Object.keys(config).length === 0) { return; } const indentStyle = config.indent_style || (editor.getSoftTabs() ? 'space' : 'tab'); if (indentStyle === 'tab') { editor.setSoftTabs(false); if (config.tab_width) { editor.setTabLength(config.tab_width); } } else if (indentStyle === 'space') { editor.setSoftTabs(true); if (config.indent_size) { editor.setTabLength(config.indent_size); } } if (config.charset) { // EditorConfig charset names matches iconv charset names. // Which is used by Atom. So no charset name convertion is needed. editor.setEncoding(config.charset); } }); } export const activate = () => { atom.workspace.observeTextEditors(init); };
'use babel'; import editorconfig from 'editorconfig'; import generateConfig from './commands/generate'; function init(editor) { generateConfig(); if (!editor) { return; } const file = editor.getURI(); if (!file) { return; } editorconfig.parse(file).then(config => { if (Object.keys(config).length === 0) { return; } const indentStyle = config.indent_style || editor.getSoftTabs() ? 'space' : 'tab'; if (indentStyle === 'tab') { editor.setSoftTabs(false); if (config.tab_width) { editor.setTabLength(config.tab_width); } } else if (indentStyle === 'space') { editor.setSoftTabs(true); if (config.indent_size) { editor.setTabLength(config.indent_size); } } if (config.charset) { // EditorConfig charset names matches iconv charset names. // Which is used by Atom. So no charset name convertion is needed. editor.setEncoding(config.charset); } }); } export const activate = () => { atom.workspace.observeTextEditors(init); };
Change obj to self in selfparams This is so sphinx detects the first parameter in decorated functions as `self`, and therefore does not display it in the method signature.
import numba def selfparams(f): def wrapped_func(self, x1, x2): return f(x1.astype('f8', copy=False), x2.astype('f8', copy=False), *self.params) wrapped_func.__name__ = f.__name__ wrapped_func.__doc__ = f.__doc__ return wrapped_func def lazyjit(*args, **kwargs): compiler = numba.jit(*args, **kwargs) def compile(f): f.compiled = None def thunk(*fargs, **fkwargs): if not f.compiled: f.compiled = compiler(f) return f.compiled(*fargs, **fkwargs) thunk.__name__ = f.__name__ thunk.__doc__ = f.__doc__ return thunk return compile
import numba def selfparams(f): def wrapped_func(obj, x1, x2): return f(x1.astype('f8', copy=False), x2.astype('f8', copy=False), *obj.params) wrapped_func.__name__ = f.__name__ wrapped_func.__doc__ = f.__doc__ return wrapped_func def lazyjit(*args, **kwargs): compiler = numba.jit(*args, **kwargs) def compile(f): f.compiled = None def thunk(*fargs, **fkwargs): if not f.compiled: f.compiled = compiler(f) return f.compiled(*fargs, **fkwargs) thunk.__name__ = f.__name__ thunk.__doc__ = f.__doc__ return thunk return compile
Add string cast for 3.24 in tests
<?hh class :test:contexts extends :x:element { protected function render(): XHPRoot { return <div> <p>{(string) $this->getContext('heading')}</p> {$this->getChildren()} </div>; } } class XHPContextsTest extends PHPUnit_Framework_TestCase { public function testContextSimple(): void { $x = <test:contexts />; $x->setContext('heading', 'herp'); $this->assertSame('<div><p>herp</p></div>', $x->toString()); } public function testContextInsideHTMLElement(): void { $x = <div><test:contexts /></div>; $x->setContext('heading', 'herp'); $this->assertSame('<div><div><p>herp</p></div></div>', $x->toString()); } public function testNestedContexts(): void { $x = <test:contexts><test:contexts /></test:contexts>; $x->setContext('heading', 'herp'); $this->assertSame( '<div><p>herp</p><div><p>herp</p></div></div>', $x->toString(), ); } }
<?hh class :test:contexts extends :x:element { protected function render(): XHPRoot { return <div> <p>{$this->getContext('heading')}</p> {$this->getChildren()} </div>; } } class XHPContextsTest extends PHPUnit_Framework_TestCase { public function testContextSimple(): void { $x = <test:contexts />; $x->setContext('heading', 'herp'); $this->assertSame('<div><p>herp</p></div>', $x->toString()); } public function testContextInsideHTMLElement(): void { $x = <div><test:contexts /></div>; $x->setContext('heading', 'herp'); $this->assertSame('<div><div><p>herp</p></div></div>', $x->toString()); } public function testNestedContexts(): void { $x = <test:contexts><test:contexts /></test:contexts>; $x->setContext('heading', 'herp'); $this->assertSame( '<div><p>herp</p><div><p>herp</p></div></div>', $x->toString(), ); } }
Fix rain ceremony not working correctly
package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level instanceof ServerLevel slevel && slevel.isRaining() != doRain) { slevel.setWeatherParameters( doRain ? 0 : 6000, //Clear weather time doRain ? 6000 : 0, //Rain time doRain, //raining false); //thundering } } }
package pokefenn.totemic.ceremony; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import pokefenn.totemic.api.ceremony.CeremonyEffectContext; import pokefenn.totemic.api.ceremony.CeremonyInstance; public class CeremonyRain extends CeremonyInstance { private final boolean doRain; public CeremonyRain(boolean doRain) { this.doRain = doRain; } @Override public void effect(Level level, BlockPos pos, CeremonyEffectContext context) { if(level.isRaining() != doRain) { level.getLevelData().setRaining(doRain); level.setRainLevel(doRain ? 1.0F : 0.0F); } } }
Change log line handling http request to DEBUG
// Copyright 2014-2018 Amazon.com, Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 handlers import ( "net/http" "github.com/cihub/seelog" ) // LoggingHandler is used to log all requests for an endpoint. type LoggingHandler struct{ h http.Handler } // NewLoggingHandler creates a new LoggingHandler object. func NewLoggingHandler(handler http.Handler) LoggingHandler { return LoggingHandler{h: handler} } // ServeHTTP logs the method and remote address of the request. func (lh LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { seelog.Debug("Handling http request", "method", r.Method, "from", r.RemoteAddr) lh.h.ServeHTTP(w, r) }
// Copyright 2014-2018 Amazon.com, Inc. or its affiliates. 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. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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 handlers import ( "net/http" "github.com/cihub/seelog" ) // LoggingHandler is used to log all requests for an endpoint. type LoggingHandler struct{ h http.Handler } // NewLoggingHandler creates a new LoggingHandler object. func NewLoggingHandler(handler http.Handler) LoggingHandler { return LoggingHandler{h: handler} } // ServeHTTP logs the method and remote address of the request. func (lh LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { seelog.Info("Handling http request", "method", r.Method, "from", r.RemoteAddr) lh.h.ServeHTTP(w, r) }
Revert "Remove temporary patch for broken TestNG 6.9.13" This reverts commit 3aaab7db09e801d66e66029a7c0719fe24084d39. CI still has the dynamic versions lookup result in cache. Will resubmit later.
/* * Copyright 2016 the original author or 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 org.gradle.buildinit.plugins.internal; import com.google.common.base.Throwables; import org.gradle.api.JavaVersion; import java.io.IOException; import java.util.Properties; public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider { private final Properties libraryVersions = new Properties(); public DefaultTemplateLibraryVersionProvider() { try { this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties")); } catch (IOException e) { throw Throwables.propagate(e); } } public String getVersion(String module) { if (module.equals("testng") && !JavaVersion.current().isJava8Compatible()) { // Use the highest version that runs on Java 7 return "6.9.12"; } return libraryVersions.getProperty(module); } }
/* * Copyright 2016 the original author or 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 org.gradle.buildinit.plugins.internal; import com.google.common.base.Throwables; import java.io.IOException; import java.util.Properties; public class DefaultTemplateLibraryVersionProvider implements TemplateLibraryVersionProvider { private final Properties libraryVersions = new Properties(); public DefaultTemplateLibraryVersionProvider() { try { this.libraryVersions.load(getClass().getResourceAsStream("/org/gradle/buildinit/tasks/templates/library-versions.properties")); } catch (IOException e) { throw Throwables.propagate(e); } } public String getVersion(String module) { return libraryVersions.getProperty(module); } }
Change kebab case into snake case
<?php namespace $NAME$\Dashboard; use Illuminate\Support\ServiceProvider; class DashboardServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { // $this->loadViewsFrom(__DIR__ . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'views', '$NAME$\Dashboard'); $this->loadTranslationsFrom(resource_path('lang/vendor/module_dashboard'), 'module_dashboard'); } }
<?php namespace $NAME$\Dashboard; use Illuminate\Support\ServiceProvider; class DashboardServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @return void */ public function boot() { // $this->loadViewsFrom(__DIR__ . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'views', '$NAME$\Dashboard'); $this->loadTranslationsFrom(resource_path('lang/vendor/module-dashboard'), 'module-dashboard'); } }
Fix for periodic task scheduler (5)
__author__ = 'onur' from kombu import Queue CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 BROKER_URL = 'amqp://%s' % "direnaj-staging.cmpe.boun.edu.tr" CELERY_DEFAULT_QUEUE = 'control' CELERY_DEFAULT_EXCHANGE = 'campaigns' CELERY_DEFAULT_EXCHANGE_TYPE = 'topic' CELERY_QUEUES = ( #Queue('timelines', routing_key='*.timeline.*'), #Queue('streamings', routing_key='*.streaming.*'), Queue('control', routing_key='control'), ) from datetime import timedelta CELERYBEAT_SCHEDULE = { 'dispatch_timeline_harvester_tasks_every_three_minutes': { 'task': 'check_watchlist_and_dispatch_tasks', 'schedule': timedelta(seconds=60*3), }, }
__author__ = 'onur' from kombu import Queue CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 BROKER_URL = 'amqp://%s' % "direnaj-staging.cmpe.boun.edu.tr" CELERY_DEFAULT_QUEUE = 'control' CELERY_DEFAULT_EXCHANGE = 'campaigns' CELERY_DEFAULT_EXCHANGE_TYPE = 'topic' CELERY_QUEUES = ( Queue('timelines', routing_key='*.timeline.*'), Queue('streamings', routing_key='*.streaming.*'), Queue('control', routing_key='control'), ) from datetime import timedelta CELERYBEAT_SCHEDULE = { 'dispatch_timeline_harvester_tasks_every_three_minutes': { 'task': 'check_watchlist_and_dispatch_tasks', 'schedule': timedelta(seconds=60*3), }, }
Make EnsuredState rollback unconditionally on error It is very confusing if resources that got acquired (daemon, connector, intercepts) as the result of issuing a command are retained although the command failed. This command changes that behavior so that all resources acquired by the command are released if the command fails.
package client import "fmt" // An EnsuredState represents some state that is needed in order for a function to execute. type EnsuredState interface { // EnsureState will check if the state is active and activate it if that is not the case. // The boolean return value indicates if the state was activated or not. EnsureState() (bool, error) // Deactivate the state (i.e. quit, remove, disconnect) DeactivateState() error } // WithEnsuredState ensures the given state, calls the function, and then, if the state // was activated, it is deactivated unless the retain flag is true. func WithEnsuredState(r EnsuredState, retain bool, f func() error) (err error) { var wasAcquired bool defer func() { // Always deactivate an acquired state unless there's no error // and a desire to retain it. if wasAcquired && !(err == nil && retain) { if cerr := r.DeactivateState(); cerr != nil { if err == nil { err = cerr } else { err = fmt.Errorf("%s\n%s", err.Error(), cerr.Error()) } } } }() if wasAcquired, err = r.EnsureState(); err != nil { return err } return f() }
package client import "fmt" // An EnsuredState represents some state that is needed in order for a function to execute. type EnsuredState interface { // EnsureState will check if the state is active and activate it if that is not the case. // The boolean return value indicates if the state was activated or not. EnsureState() (bool, error) // Deactivate the state (i.e. quit, remove, disconnect) DeactivateState() error } // WithEnsuredState ensures the given state, calls the function, and then, if the state // was activated, it is deactivated unless the retain flag is true. func WithEnsuredState(r EnsuredState, retain bool, f func() error) (err error) { var wasAcquired bool wasAcquired, err = r.EnsureState() if wasAcquired && !retain { defer func() { if cerr := r.DeactivateState(); cerr != nil { if err == nil { err = cerr } else { err = fmt.Errorf("%s\n%s", err.Error(), cerr.Error()) } } }() } if err != nil { return err } err = f() return }
Check for reference handlers only when resetting to default state.
var $$ = React.createElement; var stateHandlers = { handleSelectionChange: function(writerCtrl, sel) { var surface = writerCtrl.getSurface(); if (surface.name !== "content") return; if (sel.isNull() || !sel.isPropertySelection()) return; var range = sel.getTextRange(); var annotations = writerCtrl.doc.annotationIndex.get(sel.getPath(), range[0], range[1], "reference"); // Switch to a neutral state if no annotation matches have been found if (annotations.length === 0 && writerCtrl.state.contextId !== "editSubjectReference") { var prevContextId = writerCtrl.state.contextId; var nextContextId = "entities"; if (prevContextId === "editSubjectReference" || prevContextId === "subjects") { nextContextId = "subjects"; } writerCtrl.replaceState({ contextId: nextContextId }); return true; } } }; module.exports = stateHandlers;
var $$ = React.createElement; var stateHandlers = { handleSelectionChange: function(writerCtrl, sel) { var surface = writerCtrl.getSurface(); if (surface.name !== "content") return; if (sel.isNull() || !sel.isPropertySelection()) return; var range = sel.getTextRange(); var annotations = writerCtrl.doc.annotationIndex.get(sel.getPath(), range[0], range[1]); // Switch to a neutral state if no annotation matches have been found if (annotations.length === 0 && writerCtrl.state.contextId !== "editSubjectReference") { var prevContextId = writerCtrl.state.contextId; var nextContextId = "entities"; if (prevContextId === "editSubjectReference" || prevContextId === "subjects") { nextContextId = "subjects"; } writerCtrl.replaceState({ contextId: nextContextId }); return true; } } }; module.exports = stateHandlers;
Patch to send mails with UTF8 encoding Just a temp fix
""" This module contains the SESBackend class, which is what you'll want to set in your settings.py:: EMAIL_BACKEND = 'seacucumber.backend.SESBackend' """ from django.core.mail.backends.base import BaseEmailBackend from seacucumber.tasks import SendEmailTask class SESBackend(BaseEmailBackend): """ A Django Email backend that uses Amazon's Simple Email Service. """ def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. :param EmailMessage email_messages: A list of Django's EmailMessage object instances. :rtype: int :returns: The number of EmailMessage objects that were successfully queued up. Note that these are not in a state where we can guarantee delivery just yet. """ num_sent = 0 for message in email_messages: # Hand this off to a celery task. SendEmailTask.delay( message.from_email, message.recipients(), message.message().as_string().decode('utf8'), ) num_sent += 1 return num_sent
""" This module contains the SESBackend class, which is what you'll want to set in your settings.py:: EMAIL_BACKEND = 'seacucumber.backend.SESBackend' """ from django.core.mail.backends.base import BaseEmailBackend from seacucumber.tasks import SendEmailTask class SESBackend(BaseEmailBackend): """ A Django Email backend that uses Amazon's Simple Email Service. """ def send_messages(self, email_messages): """ Sends one or more EmailMessage objects and returns the number of email messages sent. :param EmailMessage email_messages: A list of Django's EmailMessage object instances. :rtype: int :returns: The number of EmailMessage objects that were successfully queued up. Note that these are not in a state where we can guarantee delivery just yet. """ num_sent = 0 for message in email_messages: # Hand this off to a celery task. SendEmailTask.delay( message.from_email, message.recipients(), message.message().as_string(), ) num_sent += 1 return num_sent
[client] Use only msecs of dacapo output. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
import re BENCHMARKS = set(( 'avrora' , 'batik' , 'eclipse' , 'fop' , 'h2' , 'jython' , 'luindex' , 'lusearch' , 'pmd' , 'sunflow' , 'tomcat' , 'tradebeans' , 'tradesoap' , 'xalan')) WALLCLOCK_RE = re.compile(r'(?:(?P<time>\d+) msec)') def dacapo_wallclock(output): """ :param output: benchmark output :returns: list of relevant parts for wallclock time :rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec) """ return WALLCLOCK_RE.findall(output)
import re BENCHMARKS = set(( 'avrora' , 'batik' , 'eclipse' , 'fop' , 'h2' , 'jython' , 'luindex' , 'lusearch' , 'pmd' , 'sunflow' , 'tomcat' , 'tradebeans' , 'tradesoap' , 'xalan')) WALLCLOCK_RE = re.compile(r'((?P<succed>FAILED|PASSED) in (?P<time>\d+) msec)') def dacapo_wallclock(output): """ :param output: benchmark output :returns: list of relevant parts for wallclock time :rtype: list of tuples as (whole relevant part, PASSED/FAILED, time in msec) """ return WALLCLOCK_RE.findall(output)
Make setRadius and updateStyle({radius: 123 }) work.
/* * L.CircleMarker is a circle overlay with a permanent pixel radius. */ L.CircleMarker = L.Circle.extend({ options: { radius: 10, weight: 2 }, initialize: function (latlng, options) { L.Circle.prototype.initialize.call(this, latlng, null, options); this._radius = this.options.radius; }, projectLatlngs: function () { this._point = this._map.latLngToLayerPoint(this._latlng); }, _updateStyle : function () { L.Circle.prototype._updateStyle.call(this); this.setRadius(this.options.radius); }, setRadius: function (radius) { this.options.radius = this._radius = radius; return this.redraw(); } }); L.circleMarker = function (latlng, options) { return new L.CircleMarker(latlng, options); };
/* * L.CircleMarker is a circle overlay with a permanent pixel radius. */ L.CircleMarker = L.Circle.extend({ options: { radius: 10, weight: 2 }, initialize: function (latlng, options) { L.Circle.prototype.initialize.call(this, latlng, null, options); this._radius = this.options.radius; }, projectLatlngs: function () { this._point = this._map.latLngToLayerPoint(this._latlng); }, _updateStyle : function () { L.Circle.prototype._updateStyle.call(this); this.setRadius(this.options.radius); }, setRadius: function (radius) { this._radius = radius; return this.redraw(); } }); L.circleMarker = function (latlng, options) { return new L.CircleMarker(latlng, options); };
Fix test to reflect actual behaviour it would be more consistent if the first starts with `1`, but since it is the default implementation, it would be hard to change
package de.retest.recheck.ui.descriptors.idproviders; import static de.retest.recheck.ui.Path.fromString; import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; class ElementCountingRetestIdProviderTest { @Test void test() { final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider(); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-2" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a" ); } }
package de.retest.recheck.ui.descriptors.idproviders; import static de.retest.recheck.ui.Path.fromString; import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; class ElementCountingRetestIdProviderTest { @Test void test() { final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider(); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-2" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-3" ); assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a-1" ); } }
Disable frequently failing test until the rootcause is fixed.
/* * 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.facebook.presto.raptor.integration; import com.facebook.presto.testing.QueryRunner; import com.facebook.presto.tests.AbstractTestDistributedQueries; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import static com.facebook.presto.raptor.RaptorQueryRunner.createRaptorQueryRunner; public class TestRaptorDistributedQueries extends AbstractTestDistributedQueries { @Override protected QueryRunner createQueryRunner() throws Exception { return createRaptorQueryRunner(ImmutableMap.of(), true, false, false, ImmutableMap.of("storage.orc.optimized-writer-stage", "ENABLED_AND_VALIDATED")); } @Override protected boolean supportsNotNullColumns() { return false; } @Test(enabled = false) @Override public void testLargeQuerySuccess() { // TODO: disabled until we fix stackoverflow error in ExpressionTreeRewriter } }
/* * 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.facebook.presto.raptor.integration; import com.facebook.presto.testing.QueryRunner; import com.facebook.presto.tests.AbstractTestDistributedQueries; import com.google.common.collect.ImmutableMap; import static com.facebook.presto.raptor.RaptorQueryRunner.createRaptorQueryRunner; public class TestRaptorDistributedQueries extends AbstractTestDistributedQueries { @Override protected QueryRunner createQueryRunner() throws Exception { return createRaptorQueryRunner(ImmutableMap.of(), true, false, false, ImmutableMap.of("storage.orc.optimized-writer-stage", "ENABLED_AND_VALIDATED")); } @Override protected boolean supportsNotNullColumns() { return false; } }
api: Update to use gensim format
from flask import Flask, request from flask.ext.restful import reqparse, Api, Resource from gensim.models.word2vec import Word2Vec import json print 'loading model' MODEL = Word2Vec.load('GoogleNews-vectors-negative300.gensim') print 'model loaded' app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def post(self): # reqparse didn't work, when a single item was passed in the negative # field It was splitting the string by character args = request.get_json() try: result = MODEL.most_similar( positive=args['positive'], negative=args['negative'], topn=args['topn'], ) except KeyError: return {'result': [("Sorry, I haven't learned that word yet", -1)]}, 201 return {'result': result}, 201 api.add_resource(HelloWorld, '/most_similar') if __name__ == '__main__': app.run(debug=False)
from flask import Flask, request from flask.ext.restful import reqparse, Api, Resource from gensim.models.word2vec import Word2Vec import json print 'loading model' MODEL = Word2Vec.load_word2vec_format( 'GoogleNews-vectors-negative300.bin.gz', binary=True) print 'model loaded' app = Flask(__name__) api = Api(app) class HelloWorld(Resource): def post(self): # reqparse didn't work, when a single item was passed in the negative # field It was splitting the string by character args = request.get_json() result = MODEL.most_similar( positive=args['positive'], negative=args['negative'], topn=args['topn'], ) return {'result': result}, 201 api.add_resource(HelloWorld, '/most_similar') if __name__ == '__main__': app.run(debug=True)
Rename variable button1 to normalButton.
package net.stack3.buttonsample; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); Button normalButton = (Button)findViewById(R.id.normal_button); normalButton.setOnClickListener(normalButtonOnClickListener); } private OnClickListener normalButtonOnClickListener = new OnClickListener() { @Override public void onClick(View v) { Button normalButton = (Button)v; normalButton.setText(R.string.clicked); } }; }
package net.stack3.buttonsample; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); Button button1 = (Button)findViewById(R.id.normal_button); button1.setOnClickListener(normalButtonOnClickListener); } private OnClickListener normalButtonOnClickListener = new OnClickListener() { @Override public void onClick(View v) { Button button1 = (Button)v; button1.setText(R.string.clicked); } }; }
Read credentials based on account.
"""Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-name> Account to work with. """ import json from docopt import docopt from pkg_resources import require def read_credentials(account): credentials = {} with open('plaid-credentials.json') as json_data: credentials = json.load(json_data) with open('cfg/%s.json'%account) as json_data: credentials["account"] = {}; credentials["account"]["name"] = account credentials["account"]["credentials"] = json.load(json_data) return credentials def main(): version = require("transaction-downloader")[0].version args = docopt(__doc__, version=version) print(args) credentials = read_credentials(args['--account']) if __name__ == '__main__': main()
"""Transaction Downloader. Usage: transaction-downloader auth --account=<account-name> transaction-downloader -h | --help transaction-downloader --version Options: -h --help Show this screen. --version Show version. --account=<account-name> Account to work with. """ import json from docopt import docopt from pkg_resources import require def read_credentials(account): credentials = {} with open('plaid-credentials.json') as json_data: credentials = json.load(json_data) with open('cfg/%s.json'%account) as json_data: credentials["account"] = {}; credentials["account"]["name"] = account credentials["account"]["credentials"] = json.load(json_data) return credentials def main(): version = require("transaction-downloader")[0].version args = docopt(__doc__, version=version) print(args) if __name__ == '__main__': main()
Update insertion sort with list validation
def insertion_sort(un_list): if type(un_list) is not list: return "You must pass a valid list as argument. Do it." for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
Add test for incorrect password auth view
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services')
Make sure config is empty if a bad path is given
# -*- coding: utf-8 -*- import unittest from .utils import all_available_methods, get_config_path from noterator import Noterator from noterator.config import ConfigurationError class TestConfigValidation(unittest.TestCase): def test_valid_config(self): noterator = Noterator( method=all_available_methods(), config_file=get_config_path('config-full.ini') ) noterator._validate_config() def test_invalid_config(self): noterator = Noterator( method=all_available_methods(), config_file=get_config_path('config-bad.ini') ) with self.assertRaises(ConfigurationError): noterator._validate_config() def test_bad_path(self): noterator = Noterator( config_file='nowhere-useful', ) self.assertEqual(len(noterator.cfg.sections()), 0)
# -*- coding: utf-8 -*- import unittest from .utils import all_available_methods, get_config_path from noterator import Noterator from noterator.config import ConfigurationError class TestConfigValidation(unittest.TestCase): def test_valid_config(self): noterator = Noterator( method=all_available_methods(), config_file=get_config_path('config-full.ini') ) noterator._validate_config() def test_invalid_config(self): noterator = Noterator( method=all_available_methods(), config_file=get_config_path('config-bad.ini') ) with self.assertRaises(ConfigurationError): noterator._validate_config()
Set locale based on new language user table field
<?php namespace eHOSP\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Auth; use App; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { $this->middleware(function ($request, $next) { if (Auth::user()) { $language = Auth::user()->language; App::setLocale($language); } return $next($request); }); } }
<?php namespace eHOSP\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Auth; use App; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; public function __construct() { $this->middleware(function ($request, $next) { if (Auth::user()) { $country = Auth::user()->birth_country; App::setLocale($country); } return $next($request); }); } }
Use comment builder for dirhtml too
from django.utils.importlib import import_module from django.conf import settings # Managers mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs')) sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx')) loading = { # Possible HTML Builders 'sphinx': sphinx.HtmlBuilderComments, 'sphinx_htmldir': sphinx.HtmlDirBuilderComments, 'sphinx_singlehtml': sphinx.SingleHtmlBuilder, # Other Sphinx Builders 'sphinx_pdf': sphinx.PdfBuilder, 'sphinx_epub': sphinx.EpubBuilder, 'sphinx_search': sphinx.SearchBuilder, 'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder, # Other markup 'mkdocs': mkdocs.MkdocsHTML, 'mkdocs_json': mkdocs.MkdocsJSON, }
from django.utils.importlib import import_module from django.conf import settings # Managers mkdocs = import_module(getattr(settings, 'MKDOCS_BACKEND', 'doc_builder.backends.mkdocs')) sphinx = import_module(getattr(settings, 'SPHINX_BACKEND', 'doc_builder.backends.sphinx')) loading = { # Possible HTML Builders 'sphinx': sphinx.HtmlBuilderComments, 'sphinx_htmldir': sphinx.HtmlDirBuilder, 'sphinx_singlehtml': sphinx.SingleHtmlBuilder, # Other Sphinx Builders 'sphinx_pdf': sphinx.PdfBuilder, 'sphinx_epub': sphinx.EpubBuilder, 'sphinx_search': sphinx.SearchBuilder, 'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder, # Other markup 'mkdocs': mkdocs.MkdocsHTML, 'mkdocs_json': mkdocs.MkdocsJSON, }
Remove debugging line. Be consistent about quotes.
var express = require('express'); var multer = require('multer'); var app = express(); var storage = multer.diskStorage({ destination: './uploads', filename: function (req, file, cb) { cb(null, file.originalname); } }) var upload = multer({ storage: storage}); app.use(express.static('uploads')) app.get('/',function(req,res){ res.sendFile(__dirname + '/index.html'); }); app.get('/robots.txt', function(req, res) { res.end('User-agent: *\nDisallow: /'); }); app.post('/api/upload', upload.array('userFile', 25), function(req,res){ var numFiles = req.files.length; for (var index = 0; index < numFiles; ++index) { var file = req.files[index]; console.log('Uploaded ' + file.originalname + ' to ' + file.path); } res.end('Files uploaded.'); }); app.listen(3000,function(){ console.log('Listening on port 3000'); });
var express = require("express"); var multer = require('multer'); var app = express(); var storage = multer.diskStorage({ destination: './uploads', filename: function (req, file, cb) { cb(null, file.originalname); } }) var upload = multer({ storage: storage}); app.use(express.static('uploads')) app.get('/',function(req,res){ res.sendFile(__dirname + "/index.html"); }); app.get('/robots.txt', function(req, res) { res.end('User-agent: *\nDisallow: /'); }); app.post('/api/upload', upload.array('userFile', 25), function(req,res){ var numFiles = req.files.length; for (var index = 0; index < numFiles; ++index) { var file = req.files[index]; console.log('Uploaded ' + file.originalname + ' to ' + file.path); } console.log("sending"); res.end("Files uploaded."); }); app.listen(3000,function(){ console.log("Listening on port 3000"); });
Include all source files into coverage
var log = require('./helpers/log.js') var bin = require('./helpers/bin.js') var root = require('./helpers/root.js') var exec = require('./helpers/exec.js') module.exports = function () { var nyc = bin('nyc') + ' --all --only="' + root + 'src/" --require babel-core/register --require babel-polyfill --sourceMap=false --instrument=false --reporter=lcov --reporter=text-summary --report-dir=' + root + 'coverage/' var mocha = bin('mocha') + ' ' + root + 'tests/*' var command = 'NODE_ENV=test ' + nyc + ' ' + mocha log.info('Running tests in `tests/`') exec(command, function (err) { log.info('Tests finished. Check your coverage via coverage/lcov-report/index.html') if (err) process.exit(1) }) }
var log = require('./helpers/log.js') var bin = require('./helpers/bin.js') var root = require('./helpers/root.js') var exec = require('./helpers/exec.js') module.exports = function () { var nyc = bin('nyc') + ' --include="' + root + 'src/" --sourceMap=false --instrument=false --all=true --reporter=lcov --reporter=text-summary --report-dir=' + root + 'coverage/' var mocha = bin('mocha') + ' --compilers js:babel-core/register --require babel-polyfill ' + root + 'tests/*' var command = 'NODE_ENV=test ' + nyc + ' ' + mocha log.info('Running tests in `tests/`') exec(command, function (err) { log.info('Tests finished. Check your coverage via coverage/lcov-report/index.html') if (err) process.exit(1) }) }
Remove the comma on the end of method
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\View; /** * * Factory to create View objects. * * @package Aura.View * */ class ViewFactory { /** * * Returns a new View instance. * * @param object $helpers An arbitrary helper manager for the View; if not * specified, uses the HelperRegistry from this package. * * @return View * */ public function newInstance( $helpers = null, $view_map = [], $view_paths = [], $layout_map = [], $layout_paths = [] ) { if (! $helpers) { $helpers = new HelperRegistry; } return new View( new TemplateRegistry($view_map, $view_paths), new TemplateRegistry($layout_map, $layout_paths), $helpers ); } }
<?php /** * * This file is part of Aura for PHP. * * @license http://opensource.org/licenses/bsd-license.php BSD * */ namespace Aura\View; /** * * Factory to create View objects. * * @package Aura.View * */ class ViewFactory { /** * * Returns a new View instance. * * @param object $helpers An arbitrary helper manager for the View; if not * specified, uses the HelperRegistry from this package. * * @return View * */ public function newInstance( $helpers = null, $view_map = [], $view_paths = [], $layout_map = [], $layout_paths = [], ) { if (! $helpers) { $helpers = new HelperRegistry; } return new View( new TemplateRegistry($view_map, $view_paths), new TemplateRegistry($layout_map, $layout_paths), $helpers ); } }
Disable SELinux before OS disk encryption
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # 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. # # Requires Python 2.7+ # from OSEncryptionState import * class SelinuxState(OSEncryptionState): def __init__(self, context): super(SelinuxState, self).__init__('SelinuxState', context) def enter(self): if not super(SelinuxState, self).should_enter(): return self.context.logger.log("Entering selinux state") se_linux_status = self.context.encryption_environment.get_se_linux() if(se_linux_status.lower() == 'enforcing'): self.context.logger.log("SELinux is in enforcing mode, disabling") self.context.encryption_environment.disable_se_linux() def should_exit(self): self.context.logger.log("Verifying if machine should exit selinux state") return super(SelinuxState, self).should_exit()
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microsoft Corporation # # 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. # # Requires Python 2.7+ # from OSEncryptionState import * class SelinuxState(OSEncryptionState): def __init__(self, context): super(SelinuxState, self).__init__('SelinuxState', context) def enter(self): if not super(SelinuxState, self).should_enter(): return self.context.logger.log("Entering selinux state") def should_exit(self): self.context.logger.log("Verifying if machine should exit selinux state") return super(SelinuxState, self).should_exit()
Add possibility to warn adapter
package de.retest.recheck; import java.util.Set; import de.retest.recheck.report.ActionReplayResult; import de.retest.recheck.ui.DefaultValueFinder; import de.retest.recheck.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the Golden Master to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); /** * Notifies about differences in the given {@code ActionReplayResult}. * * @param actionReplayResult * The {@code ActionReplayResult} containing differences to be notified about. */ default void notifyAboutDifferences( final ActionReplayResult actionReplayResult ) {} }
package de.retest.recheck; import java.util.Set; import de.retest.recheck.ui.DefaultValueFinder; import de.retest.recheck.ui.descriptors.RootElement; /** * Interface to help recheck transform an arbitrary object into its internal format to allow persistence, state diffing * and ignoring of attributes and elements. */ public interface RecheckAdapter { /** * Returns {@code true} if the given object can be converted by the adapter. * * @param toVerify * the object to verify * @return true if the given object can be converted by the adapter */ boolean canCheck( Object toVerify ); /** * Convert the given object into a {@code RootElement} (respectively into a set of {@code RootElement}s if this is * sensible for this type of object). * * @param toVerify * the object to verify * @return The RootElement(s) for the given object */ Set<RootElement> convert( Object toVerify ); /** * Returns a {@code DefaultValueFinder} for the converted element attributes. Default values of attributes are * omitted in the Golden Master to not bloat it. * * @return The DefaultValueFinder for the converted element attributes */ DefaultValueFinder getDefaultValueFinder(); }
Update bundle so that it can export a value
/* * leaflet-geocoder-mapzen * Leaflet plugin to search (geocode) using Mapzen Search or your * own hosted version of the Pelias Geocoder API. * * License: MIT * (c) Mapzen */ ;(function (root, factory) { // eslint-disable-line no-extra-semi var L; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['leaflet'], factory); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. L = require('leaflet'); module.exports = factory(L); } else { // Browser globals (root is window) if (typeof root.L === 'undefined') { throw new Error('Leaflet must be loaded first'); } root.Geocoder = factory(root.L); } }(this, function (L) { 'use strict'; var Geocoder = require('./core'); // Automatically attach to Leaflet's `L` namespace. L.Control.Geocoder = Geocoder; L.control.geocoder = function (apiKey, options) { return new L.Control.Geocoder(apiKey, options); }; // Return value defines this module's export value. return Geocoder; }));
/* * leaflet-geocoder-mapzen * Leaflet plugin to search (geocode) using Mapzen Search or your * own hosted version of the Pelias Geocoder API. * * License: MIT * (c) Mapzen */ ;(function (factory) { // eslint-disable-line no-extra-semi var L; if (typeof define === 'function' && define.amd) { // AMD define(['leaflet'], factory); } else if (typeof module !== 'undefined') { // Node/CommonJS L = require('leaflet'); module.exports = factory(L); } else { // Browser globals if (typeof window.L === 'undefined') { throw new Error('Leaflet must be loaded first'); } factory(window.L); } }(function (L) { 'use strict'; var Geocoder = require('./core'); // Automatically attach to Leaflet's `L` namespace. L.Control.Geocoder = Geocoder; L.control.geocoder = function (apiKey, options) { return new L.Control.Geocoder(apiKey, options); }; // Also, can be exported as a variable. module.exports = Geocoder; }));
Fix test case for WebSocketSubscriber Switched to unittest-style testing (pytest is a bit too magical especially with the pytest-tornado extension). I may change all tests later to use unittest.
"""Tests for the WebSocketSubscriber handlers.""" import json from tornado.ioloop import IOLoop from tornado.web import Application from tornado.websocket import websocket_connect from tornado.testing import AsyncHTTPTestCase, gen_test from tornadose.handlers import WebSocketSubscriber import utilities class WebSocketSubscriberTestCase(AsyncHTTPTestCase): def setUp(self): self.store = utilities.TestStore() super(WebSocketSubscriberTestCase, self).setUp() def get_app(self): return Application([ (r'/', WebSocketSubscriber, dict(store=self.store)) ]) @gen_test def test_get_message(self): url = self.get_url('/').replace("http://", "ws://") conn = yield websocket_connect(url) self.store.submit('test') IOLoop.current().call_later(0.01, self.store.publish) msg = yield conn.read_message() msg = json.loads(msg) self.assertEqual(msg['data'], 'test') conn.close()
"""Tests for the WebSocketSubscriber handlers.""" import json import pytest from tornado.web import Application from tornado.websocket import websocket_connect from tornadose.handlers import WebSocketSubscriber import utilities @pytest.fixture def store(): return utilities.TestStore() @pytest.fixture def app(): return Application([ (r'/', WebSocketSubscriber, dict(store=store)) ]) @pytest.mark.gen_test def test_get_message(http_server, io_loop, base_url, store): conn = yield websocket_connect('ws' + base_url.split('http')[1]) store.submit('test') io_loop.call_later(0.01, store.publish) msg = yield conn.read_message() msg = json.loads(msg) assert msg['data'] == 'test' conn.close()
Move search header to the top part of the screen
// @flow import * as React from 'react'; import { Animated, StyleSheet, View, Platform, StatusBar, } from 'react-native'; import SearchForm from './SearchForm'; type Props = { onSend: ({ from: string, to: string, date: Date, }) => void, }; export default class SearchHeader extends React.PureComponent<Props, {}> { state = { height: new Animated.Value(50), expanded: false, }; render = () => ( <View style={styles.container} behavior="padding"> {/* TODO: this.state.expanded */} <SearchForm onSend={(from, to, date) => this.props.onSend({ from, to, date, })} /> </View> ); } const styles = StyleSheet.create({ container: { position: 'absolute', zIndex: 1, top: Platform.OS === 'ios' ? 40 : StatusBar.currentHeight, right: 10, left: 10, margin: 10, backgroundColor: 'white', shadowColor: 'black', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, padding: 10, }, });
// @flow import * as React from 'react'; import { Animated, StyleSheet, KeyboardAvoidingView } from 'react-native'; import SearchForm from './SearchForm'; type Props = { onSend: ({ from: string, to: string, date: Date, }) => void, }; export default class SearchHeader extends React.PureComponent<Props, {}> { state = { height: new Animated.Value(50), expanded: false, }; render = () => ( <KeyboardAvoidingView style={styles.container} behavior="padding"> {/* TODO: this.state.expanded */} <SearchForm onSend={(from, to, date) => this.props.onSend({ from, to, date, })} /> </KeyboardAvoidingView> ); } const styles = StyleSheet.create({ container: { position: 'absolute', zIndex: 1, bottom: 20, right: 20, margin: 10, backgroundColor: 'white', shadowColor: 'black', shadowOffset: { width: 0, height: 4 }, shadowOpacity: 0.3, padding: 10, }, });
Move tests to v4 version Serial API
'use strict'; var util = require('util'); var events = require('events'); var EventEmitter = events.EventEmitter || events; /** * Mock for SerialPort */ var SerialPortMock = function(path, options, callback) { EventEmitter.call(this); this._openFlag = false; if (callback) { callback(null); } }; util.inherits(SerialPortMock, EventEmitter); SerialPortMock.prototype.open = function (callback) { this._openFlag = true; if (callback) { callback(null); } this.emit('open'); }; SerialPortMock.prototype.isOpen = function() { return this._openFlag; }; SerialPortMock.prototype.write = function(buffer, callback) { this._data = buffer; if (callback) { callback(null); } }; SerialPortMock.prototype.close = function (callback) { this._openFlag = false; if (callback) { callback(null); } this.emit('close'); }; SerialPortMock.prototype.receive = function (buffer) { this.emit('data', buffer); }; module.exports = SerialPortMock;
'use strict'; var util = require('util'); var events = require('events'); var EventEmitter = events.EventEmitter || events; /** * Mock for SerialPort */ var SerialPortMock = function(path, options, openImmediately, callback) { EventEmitter.call(this); this._openFlag = openImmediately; if (callback) { callback(null); } }; util.inherits(SerialPortMock, EventEmitter); SerialPortMock.prototype.open = function (callback) { this._openFlag = true; if (callback) { callback(null); } this.emit('open'); }; SerialPortMock.prototype.isOpen = function() { return this._openFlag; }; SerialPortMock.prototype.write = function(buffer, callback) { this._data = buffer; if (callback) { callback(null); } }; SerialPortMock.prototype.close = function (callback) { this._openFlag = false; if (callback) { callback(null); } this.emit('close'); }; SerialPortMock.prototype.receive = function (buffer) { this.emit('data', buffer); }; module.exports.SerialPort = SerialPortMock;
Change access token requirement on Ordercloud facade
<?php namespace Ordercloud; use Illuminate\Container\Container; use Ordercloud\Entities\Auth\AccessToken; use Ordercloud\Entities\Organisations\OrganisationAccessToken; use Ordercloud\Support\CommandBus\Command; use Ordercloud\Support\CommandBus\CommandBus; use Ordercloud\Support\Http\Client; use Ordercloud\Support\Http\Response; class Ordercloud { const VERSION = '0.1'; /** @var CommandBus */ private $commandBus; /** @var Container */ private $container; public function __construct(CommandBus $commandBus, Container $container) { $this->commandBus = $commandBus; $this->container = $container; } /** * @param Command $command * * @return Response */ public function exec(Command $command) { return $this->commandBus->execute($command); } /** * @param string $token */ public function setAccessToken($token) { $this->getHttpClient()->setAccessToken($token); } /** * @param string $token */ public function setOrganisationToken($token) { $this->getHttpClient()->setOrganisationToken($token); } /** * @return Client */ protected function getHttpClient() { return $this->container->make('Ordercloud\Support\Http\Client'); } }
<?php namespace Ordercloud; use Illuminate\Container\Container; use Ordercloud\Entities\Auth\AccessToken; use Ordercloud\Entities\Organisations\OrganisationAccessToken; use Ordercloud\Support\CommandBus\Command; use Ordercloud\Support\CommandBus\CommandBus; use Ordercloud\Support\Http\Client; use Ordercloud\Support\Http\Response; class Ordercloud { const VERSION = '0.1'; /** @var CommandBus */ private $commandBus; /** @var Container */ private $container; public function __construct(CommandBus $commandBus, Container $container) { $this->commandBus = $commandBus; $this->container = $container; } /** * @param Command $command * * @return Response */ public function exec(Command $command) { return $this->commandBus->execute($command); } /** * @param AccessToken $token */ public function setAccessToken(AccessToken $token) { $this->getHttpClient()->setAccessToken($token->getAccessToken()); } /** * @param OrganisationAccessToken $token */ public function setOrganisationToken(OrganisationAccessToken $token) { $this->getHttpClient()->setOrganisationToken($token->getToken()); } /** * @return Client */ protected function getHttpClient() { return $this->container->make('Ordercloud\Support\Http\Client'); } }
Exclude presenter from unit testing
module.exports = function(config) { var karma = { frameworks: ['jasmine'], files: [ 'test/*.spec.js', 'src/js/model.js', 'src/js/view.js', 'src/js/presenter.js' ], port: 9876, colors: true, logLevel: config.LOG_INFO, client: { captureConsole: false }, autoWatch: false, browsers: ['Chrome'], customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'] } }, reporters: ['progress', 'coverage'], coverageReporter: { reporters: [ {type: 'html', subdir: './html'}, {type: 'lcovonly', subdir: './lcov'} ] }, preprocessors: { 'src/js/model.js': ['coverage'], 'src/js/view.js': ['coverage'] }, singleRun: true, concurrency: Infinity }; if (process.env.TRAVIS) { karma.browsers = ['ChromeTravis']; } config.set(karma); };
module.exports = function(config) { var karma = { frameworks: ['jasmine'], files: [ 'test/*.spec.js', 'src/js/model.js', 'src/js/view.js', 'src/js/presenter.js' ], port: 9876, colors: true, logLevel: config.LOG_INFO, client: { captureConsole: false }, autoWatch: false, browsers: ['Chrome'], customLaunchers: { ChromeTravis: { base: 'Chrome', flags: ['--no-sandbox'] } }, reporters: ['progress', 'coverage'], coverageReporter: { reporters: [ {type: 'html', subdir: './html'}, {type: 'lcovonly', subdir: './lcov'} ] }, preprocessors: {'src/js/*.js': ['coverage']}, singleRun: true, concurrency: Infinity }; if (process.env.TRAVIS) { karma.browsers = ['ChromeTravis']; } config.set(karma); };
Delete the if-none-match header in the no-caching plugin
var robohydra = require('robohydra'), RoboHydraHead = robohydra.heads.RoboHydraHead; function getBodyParts(config) { "use strict"; var noCachingPath = config.nocachingpath || '/.*'; return {heads: [new RoboHydraHead({ path: noCachingPath, handler: function(req, res, next) { // Tweak client cache-related headers so ensure no // caching, then let the request be dispatched normally delete req.headers['if-modified-since']; delete req.headers['if-none-match']; req.headers['cache-control'] = 'no-cache'; next(req, res); } })]}; } exports.getBodyParts = getBodyParts;
var robohydra = require('robohydra'), RoboHydraHead = robohydra.heads.RoboHydraHead; function getBodyParts(config) { "use strict"; var noCachingPath = config.nocachingpath || '/.*'; return {heads: [new RoboHydraHead({ path: noCachingPath, handler: function(req, res, next) { // Tweak client cache-related headers so ensure no // caching, then let the request be dispatched normally delete req.headers['if-modified-since']; req.headers['cache-control'] = 'no-cache'; next(req, res); } })]}; } exports.getBodyParts = getBodyParts;
Fix PEP8 white spacing (space after comma)
from slackclient._user import User from slackclient._server import Server, SlackLoginError from slackclient._channel import Channel import json import pytest @pytest.fixture def login_data(): login_data = open('_pytest/data/rtm.start.json', 'r').read() login_data = json.loads(login_data) return login_data def test_Server(server): assert type(server) == Server def test_Server_parse_channel_data(server, login_data): server.parse_channel_data(login_data["channels"]) assert type(server.channels.find('general')) == Channel def test_Server_parse_user_data(server, login_data): server.parse_user_data(login_data["users"]) assert type(server.users.find('fakeuser')) == User def test_Server_cantconnect(server): with pytest.raises(SlackLoginError): reply = server.ping() @pytest.mark.xfail def test_Server_ping(server, monkeypatch): #monkeypatch.setattr("", lambda: True) monkeypatch.setattr("websocket.create_connection", lambda: True) reply = server.ping()
from slackclient._user import User from slackclient._server import Server, SlackLoginError from slackclient._channel import Channel import json import pytest @pytest.fixture def login_data(): login_data = open('_pytest/data/rtm.start.json','r').read() login_data = json.loads(login_data) return login_data def test_Server(server): assert type(server) == Server def test_Server_parse_channel_data(server, login_data): server.parse_channel_data(login_data["channels"]) assert type(server.channels.find('general')) == Channel def test_Server_parse_user_data(server, login_data): server.parse_user_data(login_data["users"]) assert type(server.users.find('fakeuser')) == User def test_Server_cantconnect(server): with pytest.raises(SlackLoginError): reply = server.ping() @pytest.mark.xfail def test_Server_ping(server, monkeypatch): #monkeypatch.setattr("", lambda: True) monkeypatch.setattr("websocket.create_connection", lambda: True) reply = server.ping()
Add single-line-stringified error to error.message case
'use strict'; var inherits = require('inherits'); inherits(APIError, Error); module.exports = APIError; function APIError (error, request) { if (!(this instanceof APIError)) { return new APIError(error); } this.name = error.sys.id; this.message = [request.method, request.uri, formatMessage(error)].join(' '); this.request = request; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } var customFormatters = { ValidationFailed: function (error) { if (!(error.details && error.details.errors)) { return JSON.stringify(error); } return error.details.errors.reduce(function (messages, validationError) { var message = '(' + validationError.name + ' path=' + validationError.path.join('.') + ' value=' + JSON.stringify(validationError.value) + ')'; return messages.concat(message); }, []).join(', '); } }; function formatMessage (error) { if ('message' in error) { return error.message + ' ' + JSON.stringify(error); } if (customFormatters[error.sys.id]) { return customFormatters[error.sys.id](error); } // stringify on one line return JSON.stringify(error); }
'use strict'; var inherits = require('inherits'); inherits(APIError, Error); module.exports = APIError; function APIError (error, request) { if (!(this instanceof APIError)) { return new APIError(error); } this.name = error.sys.id; this.message = [request.method, request.uri, formatMessage(error)].join(' '); this.request = request; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } var customFormatters = { ValidationFailed: function (error) { if (!(error.details && error.details.errors)) { return JSON.stringify(error); } return error.details.errors.reduce(function (messages, validationError) { var message = '(' + validationError.name + ' path=' + validationError.path.join('.') + ' value=' + JSON.stringify(validationError.value) + ')'; return messages.concat(message); }, []).join(', '); } }; function formatMessage (error) { if ('message' in error) { return error.message; } if (customFormatters[error.sys.id]) { return customFormatters[error.sys.id](error); } // stringify on one line return JSON.stringify(error); }
Support setting custom error page for lazy view loader
import { Component } from 'react'; // TODO use custom loading view & load failed view. class ViewLoader extends Component { constructor() { super(); this.state = {}; } loadComponent(loader) { loader().then(C => { C = C['default'] || C; this.setState({ C, error: null }); }, res => { console.log('err', res); this.setState({ C: null, error: res }); }); } componentWillMount() { this.loadComponent(this.props.loader); } componentWillReceiveProps(nextProps) { if (this.props.loader !== nextProps.loader) { this.setState({ C: null }); this.loadComponent(nextProps.loader); } } render() { let { C, error } = this.state; let { loader, LoadingView, ErrorView, ...props } = this.props; if (!C) { return error ? (ErrorView || <div>Unable to load this page.</div>) : (LoadingView || <div>Loading...</div>); } else { return <C {...props} /> } } } export default ViewLoader;
import { Component } from 'react'; // TODO use custom loading view & load failed view. class ViewLoader extends Component { constructor() { super(); this.state = {}; } loadComponent(loader) { loader().then(C => { C = C['default'] || C; this.setState({ C }); }, res => { console.log('err', res); }); } componentWillMount() { this.loadComponent(this.props.loader); } componentWillReceiveProps(nextProps) { if (this.props.loader !== nextProps.loader) { this.setState({ C: null }); this.loadComponent(nextProps.loader); } } render() { let { C } = this.state; if (!C) { return this.props.LoadingView || <div>Loading...</div>; } else { let { loader, ...props } = this.props; return <C {...props}/> } } } export default ViewLoader;
Set status button in serial no
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); if(frm.doc.status == "Sales Returned" && frm.doc.warehouse) cur_frm.add_custom_button(__('Set Status as Available'), cur_frm.cscript.set_status_as_available); }); cur_frm.cscript.set_status_as_available = function() { cur_frm.set_value("status", "Available"); cur_frm.save() }
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt cur_frm.add_fetch("customer", "customer_name", "customer_name") cur_frm.add_fetch("supplier", "supplier_name", "supplier_name") cur_frm.add_fetch("item_code", "item_name", "item_name") cur_frm.add_fetch("item_code", "description", "description") cur_frm.add_fetch("item_code", "item_group", "item_group") cur_frm.add_fetch("item_code", "brand", "brand") cur_frm.cscript.onload = function() { cur_frm.set_query("item_code", function() { return erpnext.queries.item({"is_stock_item": "Yes", "has_serial_no": "Yes"}) }); }; frappe.ui.form.on("Serial No", "refresh", function(frm) { frm.toggle_enable("item_code", frm.doc.__islocal); });
Isolate pops and pushes through function objects so that they can be manipulated It gets really weird, but it will become clearer
package monads; import static org.junit.Assert.assertEquals; import static monads.Stack.*; import static monads.Pair.*; import org.junit.Test; public class StackTest { private static final Object A = new Object(); private static final Object B = new Object(); private Pair pair = pair(empty()); @Test public void starts_empty() { assertEquals(empty(), pair.stack); } @Test(expected = Exception.class) public void forbids_pop_when_empty() { pop(pair.stack); } private static interface StackFunction { Pair eval(Stack stack); } @Test public void pushes_and_pops_an_objects() { pair = new StackFunction() { public Pair eval(Stack stack) { return stack.push(stack, A); } }.eval(pair.stack); pair = pop(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } @Test public void pops_objects_in_reverse_push_order() { pair = push(pair.stack, A); pair = push(pair.stack, B); pair = pop(pair.stack); assertEquals(B, pair.value); pair = pop(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } }
package monads; import static org.junit.Assert.assertEquals; import static monads.Stack.*; import static monads.Pair.*; import org.junit.Test; public class StackTest { private static final Object A = new Object(); private static final Object B = new Object(); private Pair pair = pair(empty()); @Test public void starts_empty() { assertEquals(empty(), pair.stack); } @Test(expected = Exception.class) public void forbids_pop_when_empty() { pop(pair.stack); } @Test public void pushes_and_pops_an_objects() { pair = push(pair.stack, A); pair = pop(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } @Test public void pops_objects_in_reverse_push_order() { pair = push(pair.stack, A); pair = push(pair.stack, B); pair = pop(pair.stack); assertEquals(B, pair.value); pair = pop(pair.stack); assertEquals(A, pair.value); assertEquals(empty(), pair.stack); } }
Put each unexpected dynamic symbols on its own line
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. import sys import re import subprocess symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$") allowed_symbols = frozenset([b'unshare', b'malloc_usable_size']) actual_symbols = set() objdump_output = subprocess.check_output([ 'arm-linux-androideabi-objdump', '-T', 'target/arm-linux-androideabi/debug/libservo.so'] ).split(b'\n') for line in objdump_output: m = symbol_regex.search(line) if m is not None: actual_symbols.add(m.group(2)) difference = actual_symbols - allowed_symbols if len(difference) > 0: human_readable_difference = "\n".join(str(s) for s in difference) print("Unexpected dynamic symbols in binary:\n{0}".format(human_readable_difference)) sys.exit(-1)
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. import sys import re import subprocess symbol_regex = re.compile(b"D \*UND\*\t(.*) (.*)$") allowed_symbols = frozenset([b'unshare', b'malloc_usable_size']) actual_symbols = set() objdump_output = subprocess.check_output([ 'arm-linux-androideabi-objdump', '-T', 'target/arm-linux-androideabi/debug/libservo.so'] ).split(b'\n') for line in objdump_output: m = symbol_regex.search(line) if m is not None: actual_symbols.add(m.group(2)) difference = actual_symbols - allowed_symbols if len(difference) > 0: human_readable_difference = ", ".join(str(s) for s in difference) print("Unexpected dynamic symbols in binary: {0}".format(human_readable_difference)) sys.exit(-1)
Update log output so that it works more nicely with ELK
import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=7) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
import logging import logging.handlers # ######### Set up logging ########## # log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG) logger = logging.getLogger('bb_log') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages tfh = logging.handlers.TimedRotatingFileHandler('./logs/app.log', when='midnight', delay=False, encoding=None, backupCount=5) tfh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatterch = logging.Formatter('%(asctime)s %(levelname)s: %(message)s') formattertfh = logging.Formatter('%(asctime)s %(levelname)s: %(message)s - %(name)s') ch.setFormatter(formatterch) tfh.setFormatter(formattertfh) # add the handlers to logger logger.addHandler(ch) logger.addHandler(tfh)
Fix serialization of typeahead fields
// Helper functions for fields defined by the field.html template "use strict"; var $ = require('jquery'), _ = require('underscore'); exports.getField = function getField($fields, name) { return $fields.filter('[data-field="' + name + '"]'); }; exports.formToDictionary = function ($form, $editFields) { var isTypeaheadHiddenField = function(name) { $form.find('[name="' + name + '"]').is('[data-typeahead-hidden]'); }; var result = {}; _.each($form.serializeArray(), function(item) { var type = exports.getField($editFields, item.name).data('type'); if (type === 'bool'){ return; } else if (item.value === '' && (type === 'int' || type === 'float')) { // convert empty numeric fields to null result[item.name] = null; } else if (item.value === '' && isTypeaheadHiddenField(name)) { // convert empty foreign key id strings to null result[item.name] = null; } else { result[item.name] = item.value; } }); $form.find('input[name][type="checkbox"]').each(function() { result[this.name] = this.checked; }); return result; };
// Helper functions for fields defined by the field.html template "use strict"; var $ = require('jquery'), _ = require('underscore'); exports.getField = function getField($fields, name) { return $fields.filter('[data-field="' + name + '"]'); }; exports.formToDictionary = function ($form, $editFields) { var result = {}; _.each($form.serializeArray(), function(item) { var type = exports.getField($editFields, item.name).data('type'); if (type === 'bool'){ return; } else if (item.value === '' && (type === 'int' || type === 'float')) { // convert empty numeric fields to null result[item.name] = null; } else if (item.value === '' && item.name === 'tree.species') { // convert empty species id strings to null result[item.name] = null; } else { result[item.name] = item.value; } }); $form.find('input[name][type="checkbox"]').each(function() { result[this.name] = this.checked; }); return result; };
Fix typos and concatenate directly
'use strict'; // MODULES // var merge = require( '@stdlib/utils/merge' ); var unique = require( './unique.js' ); // MAIN // /** * Combines two lunr indices into a single one. * * @private * @param {Object} a - first lunr index * @param {Object} b - second lunr index * @returns {Object} combined lunr object */ function combine( a, b ) { var documentStore; var corpusTokens; var tokenStore; corpusTokens = unique( a.corpusTokens.concat( b.corpusTokens ) ); documentStore = { 'store': merge( a.documentStore.store, b.documentStore.store ), 'length': a.documentStore.length = b.documentStore.length }; tokenStore = { 'root': merge( a.tokenStore.root, b.tokenStore.root ), 'length': a.tokenStore.length + b.tokenStore.length }; return { 'version': a.version, 'fields': a.fields.slice(), 'corpusTokens': corpusTokens, 'documentStore': documentStore, 'tokenStore': tokenStore, 'pipeline': a.pipeline.slice() }; } // end FUNCTION combine() // EXPORTS // module.exports = combine;
'use strict'; // MODULES // var merge = require( '@stdlib/utils/merge' ); var unique = require( './unique.js' ); // MAIN // /** * Combines two lunr indices into a sigle one. * * @private * @param {Object} a - fird lunr index * @param {Object} b - second lunr index * @returns {Object} combined lunr object */ function combine( a, b ) { var documentStore; var corpusTokens; var tokenStore; corpusTokens = unique( [].concat( a.corpusTokens ).concat( b.corpusTokens ) ); documentStore = { 'store': merge( a.documentStore.store, b.documentStore.store ), 'length': a.documentStore.length = b.documentStore.length }; tokenStore = { 'root': merge( a.tokenStore.root, b.tokenStore.root ), 'length': a.tokenStore.length + b.tokenStore.length }; return { 'version': a.version, 'fields': a.fields.slice(), 'corpusTokens': corpusTokens, 'documentStore': documentStore, 'tokenStore': tokenStore, 'pipeline': a.pipeline.slice() }; } // end FUNCTION combine() // EXPORTS // module.exports = combine;
Add new line at EOF
module.exports = { env: { 'jest/globals': true, }, root: true, extends: ['@react-native-community'], plugins: ['jest'], rules: { "array-bracket-spacing": 0, "no-console": 0, 'comma-dangle': 0, 'object-curly-spacing': 0, 'no-unused-vars': 2, "semi": 0, "quotes": [2, "single", "avoid-escape"], "eqeqeq": 0, "keyword-spacing": 0, "no-extra-semi": 0, "one-line": 0, "curly": 0, "no-shadow": 0, "prettier/prettier": 0, "no-trailing-spaces": 0, "dot-notation": 0 } }
module.exports = { env: { 'jest/globals': true, }, root: true, extends: ['@react-native-community'], plugins: ['jest'], rules: { "array-bracket-spacing": 0, "no-console": 0, 'comma-dangle': 0, 'object-curly-spacing': 0, 'no-unused-vars': 2, "semi": 0, "quotes": [2, "single", "avoid-escape"], "eqeqeq": 0, "keyword-spacing": 0, "no-extra-semi": 0, "one-line": 0, "curly": 0, "no-shadow": 0, "prettier/prettier": 0, "no-trailing-spaces": 0, "dot-notation": 0 } }
Sort the melee catalog by bash and cutting.
@section('title') Melee - Cataclysm: Dark Days Ahead @endsection @section('content') <h1>Melee</h1> <p> Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2 </p> <table class="table table-bordered table-hover tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>Material</th> <th><span title="Volume">V</span></th> <th><span title="Weight">W</span></th> <th><span title="Bashing">B</span></th> <th><span title="Cutting">C</span></th> <th><span title="To-Hit">H</span></th> </tr> </thead> @foreach($items as $item) <tr> <td>{{ $item->symbol }}</td> <td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td> <td>{{ $item->materials }}</td> <td>{{ $item->volume }}</td> <td>{{ $item->weight }}</td> <td>{{ $item->bashing }}</td> <td>{{ $item->cutting }}</td> <td>{{ $item->to_hit }}</td> </tr> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[5,1], [6,1]] }); }); </script> @endsection
@section('title') Melee - Cataclysm: Dark Days Ahead @endsection @section('content') <h1>Melee</h1> <p> Items with bashing+cutting damage higher than 10 and to-hit bonus higher than -2 </p> <table class="table table-bordered table-hover tablesorter"> <thead> <tr> <th></th> <th>Name</th> <th>Material</th> <th><span title="Volume">V</span></th> <th><span title="Weight">W</span></th> <th><span title="Bashing">B</span></th> <th><span title="Cutting">C</span></th> <th><span title="To-Hit">H</span></th> </tr> </thead> @foreach($items as $item) <tr> <td>{{ $item->symbol }}</td> <td><a href="{{route('item.view', $item->id)}}">{{ $item->name }}</a></td> <td>{{ $item->materials }}</td> <td>{{ $item->volume }}</td> <td>{{ $item->weight }}</td> <td>{{ $item->bashing }}</td> <td>{{ $item->cutting }}</td> <td>{{ $item->to_hit }}</td> </tr> </tr> @endforeach </table> <script> $(function() { $(".tablesorter").tablesorter({ sortList: [[3,1], [4,1]] }); }); </script> @endsection
Bump version since there are commits since last tag.
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "cmsplugin-filer", version = "0.9.4pbs4", url = 'http://github.com/stefanfoulis/cmsplugin-filer', license = 'BSD', description = "django-cms plugins for django-filer", long_description = read('README.rst'), author = 'Stefan Foulis', author_email = 'stefan.foulis@gmail.com', packages = find_packages(), #package_dir = {'':'src'}, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ], install_requires=[ "Django >= 1.3", "django-cms >= 2.2", "django-sekizai >= 0.4.2", "easy_thumbnails >= 1.0", "django-filer >= 0.9" ], include_package_data=True, zip_safe = False, setup_requires=['s3sourceuploader',], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "cmsplugin-filer", version = "0.9.4pbs3", url = 'http://github.com/stefanfoulis/cmsplugin-filer', license = 'BSD', description = "django-cms plugins for django-filer", long_description = read('README.rst'), author = 'Stefan Foulis', author_email = 'stefan.foulis@gmail.com', packages = find_packages(), #package_dir = {'':'src'}, classifiers = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP', ], install_requires=[ "Django >= 1.3", "django-cms >= 2.2", "django-sekizai >= 0.4.2", "easy_thumbnails >= 1.0", "django-filer >= 0.9" ], include_package_data=True, zip_safe = False, setup_requires=['s3sourceuploader',], )
Fix ancien appel de fonction
var mongoose = require('mongoose'); var _ = require('lodash'); var AcceptanceTestExecution = mongoose.model('AcceptanceTestExecution'); exports.list = function(req, res, next) { AcceptanceTestExecution .find() .where('acceptanceTest').equals(req.acceptanceTest._id) .select('-acceptanceTest') .exec(function(err, acceptanceTestExecutions) { if (err) return next(err); res.send(acceptanceTestExecutions); }); }; exports.create = function(req, res, next) { req.acceptanceTest.execute(function(err, execution) { if (err) return next(err); res.send(_.omit(execution.toObject(), 'acceptanceTest')); }); };
var mongoose = require('mongoose'); var _ = require('lodash'); var AcceptanceTestExecution = mongoose.model('AcceptanceTestExecution'); exports.list = function(req, res, next) { AcceptanceTestExecution .find() .where('acceptanceTest').equals(req.acceptanceTest._id) .select('-acceptanceTest') .exec(function(err, acceptanceTestExecutions) { if (err) return next(err); res.send(acceptanceTestExecutions); }); }; exports.create = function(req, res, next) { req.acceptanceTest.execute(req.user, function(err, execution) { if (err) return next(err); res.send(_.omit(execution.toObject(), 'acceptanceTest')); }); };
Fix: Resolve build issue caused by using window object server side.
import React from 'react' import Layout from '@theme/Layout' import {useLocation} from '@docusaurus/router'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext' import styles from './styles.module.css' import errorCodes from '../../../errors.json' import 'url-search-params-polyfill'; function Errors() { const location = useLocation(); const context = useDocusaurusContext() const { siteConfig = {} } = context const errorCode = new URLSearchParams(location.search).get("code"); const error = errorCodes[errorCode]; return ( <Layout title={`${siteConfig.title} - A predictable state container for JavaScript apps.`} description="A predictable state container for JavaScript apps." > <main className={styles.mainFull}> <h1>Production Error Codes</h1> <p> When Redux is built and running in production, error text is replaced by indexed error codes to save on bundle size. These errors will provide a link to this page with more information about the error below. </p> {error && <React.Fragment> <p><strong>The full text of the error you just encountered is:</strong></p> <code className={styles.errorDetails}> {error} </code> </React.Fragment> } </main> </Layout> ) } export default Errors
import React from 'react' import Layout from '@theme/Layout' import useDocusaurusContext from '@docusaurus/useDocusaurusContext' import 'url-search-params-polyfill'; import styles from './styles.module.css' import errorCodes from '../../../errors.json' function Errors() { const context = useDocusaurusContext() const { siteConfig = {} } = context const errorCode = new URLSearchParams(window.location.search).get("code"); const error = errorCodes[errorCode]; return ( <Layout title={`${siteConfig.title} - A predictable state container for JavaScript apps.`} description="A predictable state container for JavaScript apps." > <main className={styles.mainFull}> <h1>Production Error Codes</h1> <p> When Redux is built and running in production, error text is replaced by indexed error codes to save on bundle size. These errors will provide a link to this page with more information about the error below. </p> {error && <React.Fragment> <p><strong>The full text of the error you just encountered is:</strong></p> <code className={styles.errorDetails}> {error} </code> </React.Fragment> } </main> </Layout> ) } export default Errors
Revert "Enforce valid captcha only if required, so tests can relax captcha requirement" This reverts commit c3c450b1a7070a1dd1b808e55371e838dd297857. It wasn't such a great idea.
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { 'captcha_invalid': _(u'Invalid captcha') } def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if not check_captcha.is_valid: raise forms.util.ValidationError( self.error_messages['captcha_invalid']) return values[0]
from django.conf import settings from django import forms from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from recaptcha.client import captcha from captcha.widgets import ReCaptcha class ReCaptchaField(forms.CharField): default_error_messages = { 'captcha_invalid': _(u'Invalid captcha') } def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def __init__(self, *args, **kwargs): self.widget = ReCaptcha self.required = True super(ReCaptchaField, self).__init__(*args, **kwargs) def clean(self, values): super(ReCaptchaField, self).clean(values[1]) recaptcha_challenge_value = smart_unicode(values[0]) recaptcha_response_value = smart_unicode(values[1]) check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {}) if self.required and not check_captcha.is_valid: raise forms.util.ValidationError( self.error_messages['captcha_invalid']) return values[0]
Add Tests for the lists adventure
from py101 import Story from py101 import variables from py101 import lists import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(Story().name, 'py101', "name should be py101") class TestAdventureVariables(unittest.TestCase): good_solution = """ myinteger = 4 mystring = 'Python String Here' print(myinteger) print(mystring) """ def test_solution(self): test = variables.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() class TestAdventureLists(unittest.TestCase): good_solution = """ languages = ["ADA", "Pascal", "Fortran", "Smalltalk"] print(languages) """ def test_solution(self): test = lists.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown()
from py101 import Story from py101 import variables from py101 import lists import unittest class TestStory(unittest.TestCase): def test_name(self): self.assertEqual(Story().name, 'py101', "name should be py101") class TestAdventureVariables(unittest.TestCase): good_solution = """ myinteger = 4 mystring = 'Python String Here' print(myinteger) print(mystring) """ def test_solution(self): test = variables.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown() class TestAdventureLists(unittest.TestCase): good_solution = """ languages = ["ADA", "Pascal", "Fortran", "Smalltalk"] print(languages) """ def test_solution(self): test = lists.TestOutput(self.good_solution) test.setUp() try: test.runTest() finally: test.tearDown()
Remove new account id generation
package models import ( "database/sql" "github.com/pborman/uuid" "github.com/stripe/stripe-go" ) /*Roaster has information retrieved from stripe and the db about billing for roaster entities*/ type Roaster struct { //ID is the roaster ID in towncenter ID uuid.UUID `json:"id"` AccountID string `json:"stripeAccountId"` Account *stripe.Account `json:"account"` } /*RoasterRequest has information used in creating a roaster managed account in stripe*/ type RoasterRequest struct { UserID uuid.UUID `json:"userId" binding:"required"` /* TODO: more info as we need it */ } /*NewRoaster initialized and returns a roaster model*/ func NewRoaster(id uuid.UUID, accountID string) *Roaster { return &Roaster{ ID: id, AccountID: accountID, } } /*RoasterFromSQL maps an sql row to roaster properties, where order matters*/ func RoasterFromSQL(rows *sql.Rows) ([]*Roaster, error) { roasters := make([]*Roaster, 0) for rows.Next() { c := &Roaster{} rows.Scan(&c.ID, &c.AccountID) roasters = append(roasters, c) } return roasters, nil }
package models import ( "database/sql" "github.com/pborman/uuid" "github.com/stripe/stripe-go" ) /*Roaster has information retrieved from stripe and the db about billing for roaster entities*/ type Roaster struct { //ID is the roaster ID in towncenter ID uuid.UUID `json:"id"` AccountID string `json:"stripeAccountId"` Account *stripe.Account `json:"account"` } /*RoasterRequest has information used in creating a roaster managed account in stripe*/ type RoasterRequest struct { UserID uuid.UUID `json:"userId" binding:"required"` /* TODO: more info as we need it */ } /*NewRoaster initialized and returns a roaster model*/ func NewRoaster(id uuid.UUID, accountID string) *Roaster { return &Roaster{ ID: uuid.NewUUID(), AccountID: accountID, } } /*RoasterFromSQL maps an sql row to roaster properties, where order matters*/ func RoasterFromSQL(rows *sql.Rows) ([]*Roaster, error) { roasters := make([]*Roaster, 0) for rows.Next() { c := &Roaster{} rows.Scan(&c.ID, &c.AccountID) roasters = append(roasters, c) } return roasters, nil }
Use currently responding TPB domain
'use strict'; var bytes = require('bytes'); var tpb = require('thepiratebay'); tpb.setUrl('http://thepiratebay.se'); module.exports = function (program, query, done) { program.log.debug('tpb: searching for %s', query); tpb.search(query, { category: 205, orderBy: 7 }).then(function (results) { var torrents = results || []; program.log.debug('tpb: found %s torrents for %s', torrents.length, query); done(null, torrents.map(function (torrent) { return { title: torrent.name, size: Number(bytes(torrent.size.replace(/[i\s]/g, ''))), torrentLink: torrent.magnetLink, seeders: Number(torrent.seeders), leechers: Number(torrent.leechers), source: 'tpb' }; })); }, function (e) { program.log.error('tpb', e); done(null, []); }); };
'use strict'; var bytes = require('bytes'); var tpb = require('thepiratebay'); tpb.setUrl('http://thepiratebay.la'); module.exports = function (program, query, done) { program.log.debug('tpb: searching for %s', query); tpb.search(query, { category: 205, orderBy: 7 }).then(function (results) { var torrents = results || []; program.log.debug('tpb: found %s torrents for %s', torrents.length, query); done(null, torrents.map(function (torrent) { return { title: torrent.name, size: Number(bytes(torrent.size.replace(/[i\s]/g, ''))), torrentLink: torrent.magnetLink, seeders: Number(torrent.seeders), leechers: Number(torrent.leechers), source: 'tpb' }; })); }, function (e) { program.log.error('tpb', e); done(null, []); }); };
[chore]: Update default view user renders due to Melody
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import $ from 'jQuery'; import CoreLayout from 'layouts/CoreLayout'; import HomeView from 'views/HomeView'; import ResumeView from 'views/ResumeView'; import UserFormView from 'views/UserFormView'; import AboutView from 'views/AboutView'; import SecretView from 'views/SecretView'; function requireAuth(nextState, replaceState) { // NOTE: will change url address when deployed $.ajax({ url: 'http://localhost:3000/authentication', async: false, type: 'POST', contentType: 'application/json', success: (data) => { if (data.Auth === false) { replaceState({ nextPathname: nextState.location.pathname }, '/'); } }, error: (xhr, status, err) => console.error(err) }); } export default ( <Route path='/' component={CoreLayout}> <IndexRoute component={HomeView} /> <Route path='/userform' component={UserFormView} /> <Route path='/resume' component={ResumeView} /> <Route path='/about' component={AboutView} /> <Route path='/secretpage' component={SecretView} onEnter={requireAuth} /> </Route> );
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import $ from 'jQuery'; import CoreLayout from 'layouts/CoreLayout'; import HomeView from 'views/HomeView'; import ResumeView from 'views/ResumeView'; import UserFormView from 'views/UserFormView'; import AboutView from 'views/AboutView'; import SecretView from 'views/SecretView'; function requireAuth(nextState, replaceState) { // NOTE: will change url address when deployed $.ajax({ url: 'http://localhost:3000/authentication', async: false, type: 'POST', contentType: 'application/json', success: (data) => { if (data.Auth === false) { replaceState({ nextPathname: nextState.location.pathname }, '/'); } }, error: (xhr, status, err) => console.error(err) }); } export default ( <Route path='/' component={CoreLayout}> <IndexRoute component={ResumeView} /> <Route path='/userform' component={UserFormView} /> <Route path='/resume' component={ResumeView} /> <Route path='/about' component={AboutView} /> <Route path='/secretpage' component={SecretView} onEnter={requireAuth} /> </Route> );
Print all hourly temperatures from run date
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser import json # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky', 'key') tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx') run_time = tcx.completed_at def convert_time_to_unix(time): parsed_time = dateutil.parser.parse(time) time_in_unix = parsed_time.strftime('%s') return time_in_unix unix_run_time = convert_time_to_unix(run_time) darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/" + str(tcx.latitude) + "," + str(tcx.longitude) + "," + unix_run_time + "?exclude=currently,flags").read() # Decode JSON darksky_json = json.loads(darksky_request.decode('utf-8')) for i in darksky_json['hourly']['data']: print(i['temperature']) class getWeather: def __init__(self, date, time): self.date = date self.time = time def goodbye(self, date): print("my name is " + date)
import tcxparser from configparser import ConfigParser from datetime import datetime import urllib.request import dateutil.parser t = '1984-06-02T19:05:00.000Z' # Darksky weather API # Create config file manually parser = ConfigParser() parser.read('slowburn.config', encoding='utf-8') darksky_key = parser.get('darksky', 'key') tcx = tcxparser.TCXParser('gps_logs/2017-06-15_Running.tcx') run_time = tcx.completed_at def convert_time_to_unix(time): parsed_time = dateutil.parser.parse(time) time_in_unix = parsed_time.strftime('%s') return time_in_unix unix_run_time = convert_time_to_unix(run_time) darksky_request = urllib.request.urlopen("https://api.darksky.net/forecast/" + darksky_key + "/" + str(tcx.latitude) + "," + str(tcx.longitude) + "," + unix_run_time + "?exclude=currently,flags").read() print(darksky_request) class getWeather: def __init__(self, date, time): self.date = date self.time = time def goodbye(self, date): print("my name is " + date)
Change game status to -help
import datetime import os import json import aiohttp import discord from discord.ext import commands config = json.load(open('config.json')) class Bot(commands.Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.session = aiohttp.ClientSession(loop=self.loop) self.config = config self.startup_time = datetime.datetime.utcnow() async def on_ready(self): print(f'You are currently logged in as {bot.user}.') game = discord.Game('-help') await self.change_presence(activity=game) def load_extensions(self): for file in os.listdir('cogs'): if file.endswith('.py'): ext = file[:-3] try: self.load_extension(f'cogs.{ext}') except Exception as e: print(f'Failed to load extension {ext}: {e}') if __name__ == '__main__': bot = Bot(command_prefix='-', config=config) bot.load_extensions() bot.run(bot.config['discord'])
import datetime import os import json import aiohttp from discord.ext import commands config = json.load(open('config.json')) class Bot(commands.Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.session = aiohttp.ClientSession(loop=self.loop) self.config = config self.startup_time = datetime.datetime.utcnow() async def on_ready(self): print(f'You are currently logged in as {bot.user}.') def load_extensions(self): for file in os.listdir('cogs'): if file.endswith('.py'): ext = file[:-3] try: self.load_extension(f'cogs.{ext}') except Exception as e: print(f'Failed to load extension {ext}: {e}') if __name__ == '__main__': bot = Bot(command_prefix='-', config=config) bot.load_extensions() bot.run(bot.config['discord'])
Sort hierarchy tree by $orderColumn
<?php namespace Baum\Extensions\Eloquent; use Illuminate\Database\Eloquent\Collection as BaseCollection; class Collection extends BaseCollection { public function toHierarchy() { $dict = $this->getDictionary(); // sort based on orderColumn uasort($dict, function($a, $b){ return ($a->getOrder() >= $b->getOrder()) ? 1 : -1; }); return new BaseCollection($this->hierarchical($dict)); } protected function hierarchical($result) { foreach($result as $key => $node) $node->setRelation('children', new BaseCollection); $nestedKeys = array(); foreach($result as $key => $node) { $parentKey = $node->getParentId(); if ( !is_null($parentKey) && array_key_exists($parentKey, $result) ) { $result[$parentKey]->children[] = $node; $nestedKeys[] = $node->getKey(); } } foreach($nestedKeys as $key) unset($result[$key]); return $result; } }
<?php namespace Baum\Extensions\Eloquent; use Illuminate\Database\Eloquent\Collection as BaseCollection; class Collection extends BaseCollection { public function toHierarchy() { $dict = $this->getDictionary(); return new BaseCollection($this->hierarchical($dict)); } protected function hierarchical($result) { foreach($result as $key => $node) $node->setRelation('children', new BaseCollection); $nestedKeys = array(); foreach($result as $key => $node) { $parentKey = $node->getParentId(); if ( !is_null($parentKey) && array_key_exists($parentKey, $result) ) { $result[$parentKey]->children[] = $node; $nestedKeys[] = $node->getKey(); } } foreach($nestedKeys as $key) unset($result[$key]); return $result; } }
SEC-2651: Fix hellojs-jc after Thymeleaf Spring 4 changes
/* * Copyright 2002-2013 the original author or 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 org.springframework.security.samples.mvc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.view.ThymeleafViewResolver; /** * Disable tiles so that we can provide our custom view without being decorated. * * @author Rob Winch * */ @Configuration public class CustomMvcConfig { @Bean public ThymeleafViewResolver thymeleafViewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setOrder(Ordered.HIGHEST_PRECEDENCE - 10); viewResolver.setTemplateEngine(templateEngine); return viewResolver; } }
/* * Copyright 2002-2013 the original author or 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 org.springframework.security.samples.mvc.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.thymeleaf.spring3.SpringTemplateEngine; import org.thymeleaf.spring3.view.ThymeleafViewResolver; /** * Disable tiles so that we can provide our custom view without being decorated. * * @author Rob Winch * */ @Configuration public class CustomMvcConfig { @Bean public ThymeleafViewResolver thymeleafViewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setOrder(Ordered.HIGHEST_PRECEDENCE - 10); viewResolver.setTemplateEngine(templateEngine); return viewResolver; } }
Return user instead of optional object
package de.altenerding.biber.pinkie.user.bounday; import de.altenerding.biber.pinkie.user.entity.User; import javax.inject.Inject; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Optional; @Path("/users") @Produces(MediaType.APPLICATION_JSON) public class UserResource { @Inject UserService userService; @GET public Response getUsers() { List<User> users = userService.getUsers(); return Response.ok(users).build(); } @GET @Path("{id}") public Response getUser(@PathParam("id") long id) { Optional<User> user = userService.getUser(id); if (!user.isPresent()) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(user.get()).build(); } @POST @Path("/login") public Response login(@FormParam("name") String name, @FormParam("password") String password) { return Response.ok().build(); } }
package de.altenerding.biber.pinkie.user.bounday; import de.altenerding.biber.pinkie.user.entity.User; import javax.inject.Inject; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Optional; @Path("/users") @Produces(MediaType.APPLICATION_JSON) public class UserResource { @Inject UserService userService; @GET public Response getUsers() { List<User> users = userService.getUsers(); return Response.ok(users).build(); } @GET @Path("{id}") public Response getUser(@PathParam("id") long id) { Optional<User> user = userService.getUser(id); if (!user.isPresent()) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.ok(user).build(); } @POST @Path("/login") public Response login(@FormParam("name") String name, @FormParam("password") String password) { return Response.ok().build(); } }
refactor: Move package details to more function
const Assert = require('assert') const Child = require('child_process') const Fs = require('fs') const Path = require('path') let keys = [] let out = {} module.exports = (options, done) => { if (typeof options === 'function') { done = options options = {} } Assert.equal(typeof options, 'object', 'Options must be an object') Assert.equal(typeof done, 'function', 'Must pass in a callback function') options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options) keys = Object.keys(options) out = { env: process.env.NODE_ENV } packageDetails((err, data) => { if (err) return done(err) Object.assign(out, data) return execute(options, done) }) } const packageDetails = (done) => { const packagePath = Path.join(process.cwd(), 'package.json') Fs.readFile(packagePath, 'utf8', (err, data) => { if (err) return done(err) const { name, version } = JSON.parse(data) done(null, { name, version }) }) } const execute = (options, done) => { var key = keys.shift() if (!key) return done(null, out) Child.exec(options[key], function (err, stdout) { out[key] = err ? err.toString() : stdout.replace(/\n/g, '') return execute(options, done) }) }
const Assert = require('assert') const Child = require('child_process') const Fs = require('fs') const Path = require('path') const packagePath = Path.join(process.cwd(), 'package.json') let keys = [] let out = {} module.exports = (options, done) => { if (typeof options === 'function') { done = options options = {} } Assert.equal(typeof options, 'object', 'Options must be an object') Assert.equal(typeof done, 'function', 'Must pass in a callback function') options = Object.assign({ node: 'node -v', npm: 'npm -v' }, options) keys = Object.keys(options) Fs.readFile(packagePath, 'utf8', (err, packageJson) => { if (err) return done(err) packageJson = JSON.parse(packageJson) out = { name: packageJson.name, version: packageJson.version, env: process.env.NODE_ENV } return execute(options, done) }) } const execute = (options, done) => { var key = keys.shift() if (!key) return done(null, out) Child.exec(options[key], function (err, stdout) { out[key] = err ? err.toString() : stdout.replace(/\n/g, '') return execute(options, done) }) }
Upgrade to Jacoco 0.8.8 for Java 18 compatibility.
package org.ehcache.build.conventions; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.tasks.testing.Test; import org.gradle.testing.jacoco.plugins.JacocoPlugin; import org.gradle.testing.jacoco.plugins.JacocoPluginExtension; import org.gradle.testing.jacoco.plugins.JacocoTaskExtension; import org.gradle.testing.jacoco.tasks.JacocoReport; public class JacocoConvention implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(JacocoPlugin.class); project.getExtensions().configure(JacocoPluginExtension.class, jacoco -> { jacoco.setToolVersion("0.8.8"); }); project.getTasks().withType(JacocoReport.class).configureEach(jacocoReport -> { jacocoReport.getReports().configureEach(report -> { report.getRequired().set(false); }); }); project.getTasks().withType(Test.class).configureEach(test -> { test.getExtensions().configure(JacocoTaskExtension.class, jacoco -> { jacoco.getExcludes().add("org.terracotta.tripwire.*"); }); }); } }
package org.ehcache.build.conventions; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.tasks.testing.Test; import org.gradle.testing.jacoco.plugins.JacocoPlugin; import org.gradle.testing.jacoco.plugins.JacocoTaskExtension; import org.gradle.testing.jacoco.tasks.JacocoReport; public class JacocoConvention implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(JacocoPlugin.class); project.getTasks().withType(JacocoReport.class).configureEach(jacocoReport -> { jacocoReport.getReports().configureEach(report -> { report.getRequired().set(false); }); }); project.getTasks().withType(Test.class).configureEach(test -> { test.getExtensions().configure(JacocoTaskExtension.class, jacoco -> { jacoco.getExcludes().add("org.terracotta.tripwire.*"); }); }); } }
Remove ads from porncomixonline's main page
package me.devsaki.hentoid.activities.sources; import me.devsaki.hentoid.enums.Site; public class PorncomixActivity extends BaseWebActivity { // private static final String DOMAIN_FILTER = "porncomixonline.net"; private static final String[] GALLERY_FILTER = { "//www.porncomixonline.net/manga/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+$", "//www.porncomixonline.net/[A-Za-z0-9\\-]+/$", "//porncomicszone.net/[0-9]+/[A-Za-z0-9\\-]+/[0-9]+/$", "//porncomixinfo.com/manga-comics/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+/$", "//bestporncomix.com/gallery/[A-Za-z0-9\\-]+/$" }; private static final String[] DIRTY_ELEMENTS = {"iframe[name^='spot']"}; Site getStartSite() { return Site.PORNCOMIX; } @Override protected CustomWebViewClient getWebClient() { addDirtyElements(DIRTY_ELEMENTS); return new CustomWebViewClient(GALLERY_FILTER, this); } }
package me.devsaki.hentoid.activities.sources; import me.devsaki.hentoid.enums.Site; public class PorncomixActivity extends BaseWebActivity { // private static final String DOMAIN_FILTER = "porncomixonline.net"; private static final String[] GALLERY_FILTER = { "//www.porncomixonline.net/manga/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+$", "//www.porncomixonline.net/[A-Za-z0-9\\-]+/$", "//porncomicszone.net/[0-9]+/[A-Za-z0-9\\-]+/[0-9]+/$", "//porncomixinfo.com/manga-comics/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+/$", "//bestporncomix.com/gallery/[A-Za-z0-9\\-]+/$" }; Site getStartSite() { return Site.PORNCOMIX; } @Override protected CustomWebViewClient getWebClient() { return new CustomWebViewClient(GALLERY_FILTER, this); } }
FIX: Make sure requirements are cleared before sending notifications
<?php namespace Milkyway\SS\FlashMessage; use Controller as Original; class Controller extends Original { private static $allowed_actions = [ 'refresh', ]; private static $url_handlers = [ '$Area!' => 'refresh', ]; /** * Grab available notifications * * @param $request * @return array|\SS_HTTPResponse|void * @throws \SS_HTTPResponse_Exception */ public function refresh($request) { // Only available via AJAX if(!$request->isAjax()) { return $this->httpError(404); } $area = $request->param('Area'); singleton('require')->clear(); // If no area specified, do nothing if(!$area) { return []; } $response = $this->getResponse(); $response->addHeader('Content-type', 'application/json'); $response->setBody(json_encode(singleton('message')->$area()->get())); return $response; } public function Link($area = '') { return $this->join_links('notifications', $area); } }
<?php namespace Milkyway\SS\FlashMessage; use Controller as Original; class Controller extends Original { private static $allowed_actions = [ 'refresh', ]; private static $url_handlers = [ '$Area!' => 'refresh', ]; /** * Grab available notifications * * @param $request * @return array|\SS_HTTPResponse|void * @throws \SS_HTTPResponse_Exception */ public function refresh($request) { // Only available via AJAX if(!$request->isAjax()) { return $this->httpError(404); } $area = $request->param('Area'); // If no area specified, do nothing if(!$area) { return []; } $response = $this->getResponse(); $response->addHeader('Content-type', 'application/json'); $response->setBody(json_encode(singleton('message')->$area()->get())); return $response; } public function Link($area = '') { return $this->join_links('notifications', $area); } }
Update stable channel builders to the 1.2 branch Review URL: https://codereview.chromium.org/179723002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@253135 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.2', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Channel(object): def __init__(self, name, branch, position, category_postfix, priority): self.branch = branch self.builder_postfix = '-' + name self.category_postfix = category_postfix self.name = name self.position = position self.priority = priority self.all_deps_path = '/' + branch + '/deps/all.deps' self.standalone_deps_path = '/' + branch + '/deps/standalone.deps' self.dartium_deps_path = '/' + branch + '/deps/dartium.deps' # The channel names are replicated in the slave.cfg files for all # dart waterfalls. If you change anything here please also change it there. CHANNELS = [ Channel('be', 'branches/bleeding_edge', 0, '', 3), Channel('dev', 'trunk', 1, '-dev', 2), Channel('stable', 'branches/1.1', 2, '-stable', 1), ] CHANNELS_BY_NAME = {} for c in CHANNELS: CHANNELS_BY_NAME[c.name] = c
Add link to same calendar manage in navigation
<?php foreach ($context->getCalendars() as $calendar): ?> <?php if ($context->getCalendar() && ($calendar->shortname == $context->getCalendar()->shortname)): ?> <div style="background: #CCCCCC;"><a href="<?php echo $calendar->getManageURL() ?>"><?php echo $calendar->name ?></a></div> <ul> <li><small><a href="<?php echo $calendar->getFrontendURL() ?>">Live Calendar</a></small></li> <li><small><a href="<?php echo $calendar->getEditURL() ?>">Edit Calendar Info</a></small></li> <li><small><a href="<?php echo $calendar->getSubscriptionsURL() ?>">Subscriptions</a></small></li> <li><small><a href="<?php echo $calendar->getUsersURL() ?>">Users &amp; Permissions</a></small></li> </ul> <?php else: ?> <a href="<?php echo $calendar->getManageURL() ?>"><?php echo $calendar->name ?></a><br> <?php endif; ?> <?php endforeach; ?> <br> <a href="<?php echo $base_manager_url ?>calendar/new" class="wdn-button wdn-button-brand">+ New Calendar</a><br> <br> <a href="<?php echo $calendar->getFrontendURL() ?>">Account Info</a><br> <a href="<?php echo $calendar->getFrontendURL() ?>">InDesign Tags Export</a><br>
<?php foreach ($context->getCalendars() as $calendar): ?> <?php if ($context->getCalendar() && ($calendar->shortname == $context->getCalendar()->shortname)): ?> <div style="background: #CCCCCC;"><?php echo $calendar->name ?></div> <ul> <li><small><a href="<?php echo $calendar->getFrontendURL() ?>">Live Calendar</a></small></li> <li><small><a href="<?php echo $calendar->getEditURL() ?>">Edit Calendar Info</a></small></li> <li><small><a href="<?php echo $calendar->getSubscriptionsURL() ?>">Subscriptions</a></small></li> <li><small><a href="<?php echo $calendar->getUsersURL() ?>">Users &amp; Permissions</a></small></li> </ul> <?php else: ?> <a href="<?php echo $calendar->getManageURL() ?>"><?php echo $calendar->name ?></a><br> <?php endif; ?> <?php endforeach; ?> <br> <a href="<?php echo $base_manager_url ?>calendar/new" class="wdn-button wdn-button-brand">+ New Calendar</a><br> <br> <a href="<?php echo $calendar->getFrontendURL() ?>">Account Info</a><br> <a href="<?php echo $calendar->getFrontendURL() ?>">InDesign Tags Export</a><br>
Fix problem with Halt button on enketo colletion
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); // Workaround for when links loads with disabled and later is removed. if ($(this).hasClass('disabled')) { e.stopPropagation(); e.stopImmediatePropagation(); } }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if ($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } // Expand element. $('[data-expand]').click(function(e) { e.preventDefault(); var id = $(this).attr('data-expand'); $('#' + id).toggleClass('revealed'); }); });
$(document).foundation(); $('a.disabled').click(function(e) { e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); }); // Show shadow when content slides under the page header $(document).ready(function() { var $content = $('#site-body .content'); var $header = $('#page-head .inner'); if ($header.length > 0) { $content.css('margin-top', $header.outerHeight()); $(document).resize(function() { $content.css('margin-top', $header.outerHeight()); }); $(window).scroll(function() { if ($(this).scrollTop() > 0) { $header.addClass('overlay'); } else { $header.removeClass('overlay'); } }); } // Expand element. $('[data-expand]').click(function(e) { e.preventDefault(); var id = $(this).attr('data-expand'); $('#' + id).toggleClass('revealed'); }); });
Fix items in review feed were not linked
import _ from "lodash"; import Feed from "../feed"; import Narou from "../../sites/narou"; import { translate } from "../../util/chrome-util"; /** * Feed fetcher of received reviews in Narou * * @implements FeedFetcher */ export default class FetcherNarouReviews { isLoginRequired() { return true; } fetchFeed() { return this._fetchItems().then(items => { return new Feed({ title: translate("narouReviewsFeed"), url: Narou.URL.getMyReceivedReviewsURL(), siteName: translate(Narou.name), siteId: Narou.name, items, }); }); } _fetchItems() { return Narou.API.listMyReceivedReviews().then(reviews => { return _.map(reviews, review => ({ id: review.id, title: review.title, url: Narou.URL.getMyReceivedReviewsURL(), body: review.body, type: "review", authorName: review.userName, authorUrl: review.userUrl, sourceTitle: review.novelTitle, sourceUrl: review.novelUrl, sourceType: "novel", createdAt: review.createdAt, })); }); } }
import _ from "lodash"; import Feed from "../feed"; import Narou from "../../sites/narou"; import { translate } from "../../util/chrome-util"; /** * Feed fetcher of received reviews in Narou * * @implements FeedFetcher */ export default class FetcherNarouReviews { isLoginRequired() { return true; } fetchFeed() { return this._fetchItems().then(items => { return new Feed({ title: translate("narouReviewsFeed"), url: Narou.URL.getMyReceivedReviewsURL(), siteName: translate(Narou.name), siteId: Narou.name, items, }); }); } _fetchItems() { return Narou.API.listMyReceivedReviews().then(reviews => { return _.map(reviews, review => ({ id: review.id, title: review.title, url: this.pageUrl, body: review.body, type: "review", authorName: review.userName, authorUrl: review.userUrl, sourceTitle: review.novelTitle, sourceUrl: review.novelUrl, sourceType: "novel", createdAt: review.createdAt, })); }); } }
Increase weight of Tax Disc Beta AB to 100% This shows the beta option as the most prominent option to the majority of users.
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-beta', customVarIndex: 20, cohorts: { tax_disc_beta_control: { weight: 1, callback: function () { } }, //~100% tax_disc_beta: { weight: 0, callback: GOVUK.taxDiscBetaPrimary } //~0% } }); } });
//= require govuk/multivariate-test /*jslint browser: true, * indent: 2, * white: true */ /*global $, GOVUK */ $(function () { GOVUK.taxDiscBetaPrimary = function () { $('.primary-apply').html($('#beta-primary').html()); $('.secondary-apply').html($('#dvla-secondary').html()); }; if(window.location.href.indexOf("/tax-disc") > -1) { new GOVUK.MultivariateTest({ name: 'tax-disc-beta', customVarIndex: 20, cohorts: { tax_disc_beta_control: { weight: 50, callback: function () { } }, //50% tax_disc_beta: { weight: 50, callback: GOVUK.taxDiscBetaPrimary } //50% } }); } });
Validate parameters for the `allRaw` method too.
<?php namespace Rossedman\Teamwork; use Rossedman\Teamwork\Traits\RestfulTrait; class Time extends AbstractObject { use RestfulTrait; protected $wrapper = 'time-entry'; protected $endpoint = 'time_entries'; /** * GET /time.json * * @return mixed */ public function all($args = null) { $this->areArgumentsValid($args, [ 'page', 'updatedAfterDate' ]); return $this->client->get($this->endpoint, $args)->response(); } /** * GET /time.json * * @return mixed */ public function allRaw($args = null) { $this->areArgumentsValid($args, [ 'page', 'updatedAfterDate' ]); return $this->client->get($this->endpoint, $args)->rawResponse(); } }
<?php namespace Rossedman\Teamwork; use Rossedman\Teamwork\Traits\RestfulTrait; class Time extends AbstractObject { use RestfulTrait; protected $wrapper = 'time-entry'; protected $endpoint = 'time_entries'; /** * GET /time.json * * @return mixed */ public function all($args = null) { $this->areArgumentsValid($args, [ 'page', 'updatedAfterDate' ]); return $this->client->get($this->endpoint, $args)->response(); } /** * GET /time.json * * @return mixed */ public function allRaw($args = null) { return $this->client->get($this->endpoint, $args)->rawResponse(); } }
Remove url pattern from filter so that it will filter all paths
/* * SecurityConfig.java * * Copyright (C) 2017 [ 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 java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
/* * SecurityConfig.java * * Copyright (C) 2017 [ 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 java.security.SecureRandom; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.aleggeup.confagrid.filter.JwtFilter; @Configuration public class SecurityConfig { @Bean public FilterRegistrationBean jwtFilter() { final FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(new JwtFilter()); registrationBean.addUrlPatterns("/api/*"); return registrationBean; } @Bean public SecureRandom secureRandom() { return new SecureRandom(); } }
Fix python namespaces for test runs We need to make sure we don't use namespaced versions that are already installed on the system but rather use local version from current sources
#!/usr/bin/env python # This file is part of beets. # Copyright 2013, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. import os import re import sys from _common import unittest pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) os.chdir(pkgpath) # Make sure we use local version of beetsplug and not system namespaced version # for tests try: del sys.modules["beetsplug"] except KeyError: pass def suite(): s = unittest.TestSuite() # Get the suite() of every module in this directory beginning with # "test_". for fname in os.listdir(pkgpath): match = re.match(r'(test_\S+)\.py$', fname) if match: modname = match.group(1) s.addTest(__import__(modname).suite()) return s if __name__ == '__main__': unittest.main(defaultTest='suite')
#!/usr/bin/env python # This file is part of beets. # Copyright 2013, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. import os import re import sys from _common import unittest pkgpath = os.path.dirname(__file__) or '.' sys.path.append(pkgpath) os.chdir(pkgpath) def suite(): s = unittest.TestSuite() # Get the suite() of every module in this directory beginning with # "test_". for fname in os.listdir(pkgpath): match = re.match(r'(test_\S+)\.py$', fname) if match: modname = match.group(1) s.addTest(__import__(modname).suite()) return s if __name__ == '__main__': unittest.main(defaultTest='suite')
Make importlib import compatible w/ Django>=1.8 For Django 1.8, this just squelches a DeprecationWarning. For 1.9, this will stop an ImportError.
from __future__ import absolute_import from random import random import logging try: # Python >= 2.7 import importlib except ImportError: # Python < 2.7; will be removed in Django 1.9 from django.utils import importlib from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started logger = logging.getLogger(__name__) def clear_expired_sessions(sender, **kwargs): """ Triggered by the request_started signal, this function calls the clear_expired method on the session backend, with a certain probability (similar to how PHP clears sessions) """ if random() <= clear_expired_sessions.probability: try: clear_expired_sessions.engine.SessionStore.clear_expired() logger.debug('Sessions cleared') except NotImplementedError: logger.debug('Session engine "%s" does ont support clearing expired sessions.' % settings.SESSION_ENGINE) def patch_sessions(num_requests): """ Connects the clear_expired_sessions function to the request_started signal, and does a little configuration calculations and checking. """ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') clear_expired_sessions.engine = importlib.import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
from __future__ import absolute_import from random import random import logging from django.conf import settings from django.utils.importlib import import_module from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started logger = logging.getLogger(__name__) def clear_expired_sessions(sender, **kwargs): """ Triggered by the request_started signal, this function calls the clear_expired method on the session backend, with a certain probability (similar to how PHP clears sessions) """ if random() <= clear_expired_sessions.probability: try: clear_expired_sessions.engine.SessionStore.clear_expired() logger.debug('Sessions cleared') except NotImplementedError: logger.debug('Session engine "%s" does ont support clearing expired sessions.' % settings.SESSION_ENGINE) def patch_sessions(num_requests): """ Connects the clear_expired_sessions function to the request_started signal, and does a little configuration calculations and checking. """ if num_requests < 1: raise ImproperlyConfigured('The num_requests setting must be > 0') clear_expired_sessions.engine = import_module(settings.SESSION_ENGINE) clear_expired_sessions.probability = 1.0 / num_requests request_started.connect(clear_expired_sessions)
Fix journey graph tests following removal of the matrix
define([ 'common/views/visualisations/journey-graph/journey-graph', 'common/collections/journey_series' ], function (JourneyGraph, JourneyCollection) { describe('JourneyGraph', function () { var graph; beforeEach(function () { graph = new JourneyGraph({ collection: new JourneyCollection() }); graph.valueAttr = 'uniqueEvents'; }); describe('calcYScale', function () { describe('domain', function () { it('is set to [0,1] if there is no data', function () { expect(graph.calcYScale().domain()).toEqual([0, 1]); }); it('is set to the range of the data', function () { graph.collection.reset([ { uniqueEvents: 137 }, { uniqueEvents: 100 } ]); expect(graph.calcYScale().domain()).toEqual([0, 137]); }); }); }); }); });
define([ 'common/views/visualisations/journey-graph/journey-graph', 'common/collections/journey', 'extensions/collections/collection' ], function (JourneyGraph, JourneyCollection, Collection) { describe('JourneyGraph', function () { var graph; beforeEach(function () { graph = new JourneyGraph({ collection: new JourneyCollection([{}]) }); graph.valueAttr = 'uniqueEvents'; }); describe('calcYScale', function () { describe('domain', function () { it('is set to [0,1] if there is no data', function () { expect(graph.calcYScale().domain()).toEqual([0, 1]); }); it('is set to the range of the data', function () { graph.collection.at(0).set('values', new Collection([ { uniqueEvents: 137 }, { uniqueEvents: 100 } ])); expect(graph.calcYScale().domain()).toEqual([0, 137]); }); }); }); }); });
Remove the reference to README.
import os import re import sys from setuptools import setup, find_packages if sys.version_info[:2] < (2, 6): raise RuntimeError('Requires Python 2.6 or better') here = os.path.abspath(os.path.dirname(__file__)) info = open(os.path.join(here, 'inferno', 'lib', '__init__.py')).read() VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(info).group(1) install_requires = [ 'argparse', 'pyyaml', 'setproctitle', 'tornado', 'ujson', ] tests_require = install_requires + [ 'nose', 'mock'] setup( name='inferno', version=VERSION, description=('Inferno: a python map/reduce platform powered by disco.'), keywords='inferno discoproject', author='Chango Inc.', author_email='dev@chango.com', url='http://chango.com', license='MIT License', packages=find_packages(exclude=['test']), include_package_data=True, zip_safe=False, install_requires=install_requires, tests_require=tests_require, test_suite='nose.collector', entry_points=""" [console_scripts] inferno=inferno.bin.run:main """, requires=['disco'])
import os import re import sys from setuptools import setup, find_packages if sys.version_info[:2] < (2, 6): raise RuntimeError('Requires Python 2.6 or better') here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.txt')).read() info = open(os.path.join(here, 'inferno', 'lib', '__init__.py')).read() VERSION = re.compile(r".*__version__ = '(.*?)'", re.S).match(info).group(1) install_requires = [ 'argparse', 'pyyaml', 'setproctitle', 'tornado', 'ujson', ] tests_require = install_requires + [ 'nose', 'mock'] setup( name='inferno', version=VERSION, description=('Inferno: a python map/reduce platform powered by disco.'), long_description=README, keywords='inferno discoproject', author='Chango Inc.', author_email='dev@chango.com', url='http://chango.com', license='MIT License', packages=find_packages(exclude=['test']), include_package_data=True, zip_safe=False, install_requires=install_requires, tests_require=tests_require, test_suite='nose.collector', entry_points=""" [console_scripts] inferno=inferno.bin.run:main """, requires=['disco'])
Allow description to be changed in HelpPart
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta, Widget, APartName from ..util import set_tags with Anno("The URL that gives some help documentation for this Block"): AHelpUrl = str with Anno("The description of what the help documentation is about"): ADesc = str # Pull re-used annotypes into our namespace in case we are subclassed APartName = APartName class HelpPart(Part): """Part representing a link to some help documentation for the GUI""" def __init__(self, help_url, # type: AHelpUrl name="help", # type: APartName description="Help documentation for the Block" # type: ADesc ): # type: (...) -> None super(HelpPart, self).__init__(name) meta = StringMeta(description) set_tags(meta, widget=Widget.HELP) self.attr = meta.create_attribute_model(help_url) def setup(self, registrar): # type: (PartRegistrar) -> None registrar.add_attribute_model(self.name, self.attr)
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta, Widget, APartName from ..util import set_tags with Anno("The URL that gives some help documentation for this Block"): AHelpUrl = str # Pull re-used annotypes into our namespace in case we are subclassed APartName = APartName class HelpPart(Part): """Part representing a link to some help documentation for the GUI""" def __init__(self, help_url, name="help"): # type: (AHelpUrl, APartName) -> None super(HelpPart, self).__init__(name) meta = StringMeta("Help documentation for the Block") set_tags(meta, widget=Widget.HELP) self.attr = meta.create_attribute_model(help_url) def setup(self, registrar): # type: (PartRegistrar) -> None registrar.add_attribute_model(self.name, self.attr)
Use new retry option on superagent.request
'use strict'; const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js'); const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js'); const { request } = require('@clevercloud/client/cjs/request.superagent.js'); const { conf, loadOAuthConf } = require('../models/configuration.js'); async function loadTokens () { const tokens = await loadOAuthConf().toPromise(); return { OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET, API_OAUTH_TOKEN: tokens.token, API_OAUTH_TOKEN_SECRET: tokens.secret, }; } async function sendToApi (requestParams) { const tokens = await loadTokens(); return Promise.resolve(requestParams) .then(prefixUrl(conf.API_HOST)) .then(addOauthHeader(tokens)) .then((requestParams) => request(requestParams, { retry: 1 })); } async function getHostAndTokens () { const tokens = await loadTokens(); return { apiHost: conf.API_HOST, tokens, }; } module.exports = { sendToApi, getHostAndTokens };
'use strict'; const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js'); const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js'); const { request } = require('@clevercloud/client/cjs/request.superagent.js'); const { conf, loadOAuthConf } = require('../models/configuration.js'); async function loadTokens () { const tokens = await loadOAuthConf().toPromise(); return { OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET, API_OAUTH_TOKEN: tokens.token, API_OAUTH_TOKEN_SECRET: tokens.secret, }; } async function sendToApi (requestParams) { const tokens = await loadTokens(); return Promise.resolve(requestParams) .then(prefixUrl(conf.API_HOST)) .then(addOauthHeader(tokens)) .then(request); } async function getHostAndTokens () { const tokens = await loadTokens(); return { apiHost: conf.API_HOST, tokens, }; } module.exports = { sendToApi, getHostAndTokens };