text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Increment the version to 0.9 and set to beta. Getting close to stable and 1.0 release.
from setuptools import find_packages, setup setup_args = dict( name='furious', version='0.9', license='Apache', description='Furious is a lightweight library that wraps Google App Engine' 'taskqueues to make building dynamic workflows easy.', author='Robert Kluin', author_email='robert.kluin@webfilings.com', url='http://github.com/WebFilings/furious', packages=find_packages(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Apache', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) if __name__ == '__main__': setup(**setup_args)
from setuptools import find_packages, setup setup_args = dict( name='furious', version='0.1', license='Apache', description='Furious is a lightweight library that wraps Google App Engine' 'taskqueues to make building dynamic workflows easy.', author='Robert Kluin', author_email='robert.kluin@webfilings.com', url='http://github.com/WebFilings/furious', packages=find_packages(), classifiers=[ 'Development Status :: 2 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: Apache', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) if __name__ == '__main__': setup(**setup_args)
Update server: remove process.env read
import express from 'express'; import bodyParser from 'body-parser'; import favicon from 'serve-favicon'; import path from 'path'; import helmet from 'helmet'; import fs from 'fs'; import webpackCommonConfig from '../../webpack/config'; import envConfig from '../config'; const app = express(); const outputPath = webpackCommonConfig.paths.output; const outputServerPath = webpackCommonConfig.paths.outputServer; const serverRenderer = require(path.join(outputServerPath, 'prod.render.js')).default; const clientStats = require(path.join(outputPath, 'stats.json')); const bundleManifest = require(path.join(outputPath, 'bundle.json')); const mainCss = path.join(outputPath, bundleManifest['main.css']); app.use(helmet()); app.use(bodyParser.json()); app.use(favicon(webpackCommonConfig.paths.favicon)); app.set('view engine', 'ejs'); app.set('views', path.resolve(__dirname, 'views')); let isBuilt = false; const done = () => !isBuilt && app.listen(3000, () => { isBuilt = true; console.log("\x1b[35m", 'BUILD COMPLETE -- Listening @ :3000'); }); fs.readFile(mainCss, 'utf8', (err, data) => { if (err) throw err; app.use(serverRenderer({ clientStats, options: { criticalCssRaw: data, envConfig, isProd: true } })); done(); });
import express from 'express'; import bodyParser from 'body-parser'; import favicon from 'serve-favicon'; import path from 'path'; import helmet from 'helmet'; import fs from 'fs'; import webpackCommonConfig from '../../webpack/config'; import envConfig from '../config'; const app = express(); const outputPath = webpackCommonConfig.paths.output; const outputServerPath = webpackCommonConfig.paths.outputServer; app.use(helmet()); app.use(bodyParser.json()); app.use(favicon(webpackCommonConfig.paths.favicon)); app.set('view engine', 'ejs'); app.set('views', path.resolve(__dirname, 'views')); let isBuilt = false; const done = () => !isBuilt && app.listen(3000, () => { isBuilt = true; console.log("\x1b[35m", 'BUILD COMPLETE -- Listening @ :3000'); }); const serverRenderer = require(path.join(outputServerPath, 'prod.render.js')).default; const clientStats = require(path.join(outputPath, 'stats.json')); const bundleManifest = require(path.join(outputPath, 'bundle.json')); const mainCss = path.join(outputPath, bundleManifest['main.css']); fs.readFile(mainCss, 'utf8', (err, data) => { if (err) throw err; app.use(serverRenderer({ clientStats, options: { criticalCssRaw: data, envConfig, isProd: true } })); done(); });
Make text labels break into multi-lines by default.
// @flow import React from 'react'; import PropTypes from 'prop-types'; import type { ReactChildren } from 'react-flow-types'; import FlexCell from './FlexCell'; import Tag from './Tag'; import wrapIfNotElement from './utils/wrapIfNotElement'; export type Props = { basic?: ReactChildren, tag?: ReactChildren, statusIcon?: ReactChildren, children?: ReactChildren, // eslint-disable-line react/require-default-props }; function BasicRow({ basic, tag, statusIcon, children, ...otherProps }: Props) { if (!basic) { return null; } return ( <div {...otherProps}> <FlexCell shrink>{basic}</FlexCell> {tag && wrapIfNotElement(tag, { with: Tag })} {statusIcon && wrapIfNotElement(statusIcon, { with: 'span' })} {children} </div> ); } BasicRow.propTypes = { basic: PropTypes.node, tag: PropTypes.node, statusIcon: PropTypes.node, }; BasicRow.defaultProps = { basic: undefined, tag: undefined, statusIcon: undefined, }; export default BasicRow;
// @flow import React from 'react'; import PropTypes from 'prop-types'; import type { ReactChildren } from 'react-flow-types'; import FlexCell from './FlexCell'; import Tag from './Tag'; import TextEllipsis from './TextEllipsis'; import wrapIfNotElement from './utils/wrapIfNotElement'; export type Props = { basic?: ReactChildren, tag?: ReactChildren, statusIcon?: ReactChildren, children?: ReactChildren, // eslint-disable-line react/require-default-props }; function BasicRow({ basic, tag, statusIcon, children, ...otherProps }: Props) { if (!basic) { return null; } return ( <div {...otherProps}> <FlexCell shrink> <TextEllipsis>{basic}</TextEllipsis> </FlexCell> {tag && wrapIfNotElement(tag, { with: Tag })} {statusIcon && wrapIfNotElement(statusIcon, { with: 'span' })} {children} </div> ); } BasicRow.propTypes = { basic: PropTypes.node, tag: PropTypes.node, statusIcon: PropTypes.node, }; BasicRow.defaultProps = { basic: undefined, tag: undefined, statusIcon: undefined, }; export default BasicRow;
Use content.outputFilePath and use pass sourcemap
var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); var objectAssign = require('object-assign'); module.exports = function(source, map) { this.cacheable && this.cacheable(); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.parseQuery(this.query); var options; if (queryOptions) { options = objectAssign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(content.outputFilePath, content.contents || [''], map); content.writeFile().then(_ => { callback(null, source, map); }); }); };
var DtsCreator = require('typed-css-modules'); var loaderUtils = require('loader-utils'); var objectAssign = require('object-assign'); module.exports = function(source, map) { this.cacheable && this.cacheable(); var callback = this.async(); // Pass on query parameters as an options object to the DtsCreator. This lets // you change the default options of the DtsCreator and e.g. use a different // output folder. var queryOptions = loaderUtils.parseQuery(this.query); var options; if (queryOptions) { options = objectAssign({}, queryOptions); } var creator = new DtsCreator(options); // creator.create(..., source) tells the module to operate on the // source variable. Check API for more details. creator.create(this.resourcePath, source).then(content => { // Emit the created content as well this.emitFile(this.resourcePath + '.d.ts', content.contents || ['']); content.writeFile().then(_ => { callback(null, source, map); }); }); };
Make status indicators more like current site
import React, { Component } from 'react'; import { StyleSheet, View, } from 'react-native'; import { UserStatus } from '../api'; const styles = StyleSheet.create({ common: { width: 12, height: 12, borderRadius: 100, }, active: { backgroundColor: '#44c21d', }, idle: { backgroundColor: 'rgba(255, 165, 0, 0.25)', borderColor: 'rgba(255, 165, 0, 1)', borderWidth: 1, }, offline: { backgroundColor: 'transparent', borderColor: 'lightgray', borderWidth: 1, }, unknown: { }, }); export default class UserStatusIndicator extends Component { props: { status: UserStatus, } static defaultProps = { status: 'unknown', }; render() { const { status } = this.props; if (!status) return null; return ( <View style={[styles.common, styles[status]]} /> ); } }
import React, { Component } from 'react'; import { StyleSheet, View, } from 'react-native'; import { UserStatus } from '../api'; const styles = StyleSheet.create({ common: { width: 16, height: 16, borderRadius: 100, }, active: { borderColor: 'pink', backgroundColor: 'green', }, idle: { backgroundColor: 'rgba(255, 165, 0, 0.25)', borderColor: 'rgba(255, 165, 0, 1)', borderWidth: 2, }, offline: { backgroundColor: 'transparent', borderColor: 'lightgray', borderWidth: 2, }, unknown: { }, }); export default class UserStatusIndicator extends Component { props: { status: UserStatus, } static defaultProps = { status: 'unknown', }; render() { const { status } = this.props; if (!status) return null; return ( <View style={[styles.common, styles[status]]} /> ); } }
Simplify 'wait until interrupt signal' code (thanks to Uriel on #go-nuts)
package main import ( "flag" "log" "os" "os/signal" ) var ( listen = flag.String("listen", ":8053", "set the listener address") flaglog = flag.Bool("log", false, "be more verbose") flagrun = flag.Bool("run", false, "run server") ) func main() { log.SetPrefix("geodns ") log.SetFlags(log.Lmicroseconds | log.Lshortfile) flag.Usage = func() { flag.PrintDefaults() } flag.Parse() dirName := "dns" Zones := make(Zones) go configReader(dirName, Zones) go startServer(&Zones) if *flagrun { sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) <-sig log.Printf("geodns: signal received, stopping") os.Exit(0) } }
package main import ( "flag" "log" "os" "os/signal" ) var ( listen = flag.String("listen", ":8053", "set the listener address") flaglog = flag.Bool("log", false, "be more verbose") flagrun = flag.Bool("run", false, "run server") ) func main() { log.SetPrefix("geodns ") log.SetFlags(log.Lmicroseconds | log.Lshortfile) flag.Usage = func() { flag.PrintDefaults() } flag.Parse() dirName := "dns" Zones := make(Zones) go configReader(dirName, Zones) go startServer(&Zones) if *flagrun { sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) forever: for { select { case <-sig: log.Printf("geodns: signal received, stopping") break forever } } } }
Update default value for backtesting clock
import decimal from datetime import datetime import click from .controller import Controller, SimulatedClock from .broker import OandaBacktestBroker from .instruments import InstrumentParamType from .lib import oandapy from .conf import settings @click.command() @click.option('--instrument', '-i', 'instruments', multiple=True, type=InstrumentParamType()) def main(instruments): """ Algortihmic trading tool. """ # XXX: Currently only backtesting is supported api = oandapy.API( environment=settings.ENVIRONMENT, access_token=settings.ACCESS_TOKEN, ) broker = OandaBacktestBroker( api=api, initial_balance=decimal.Decimal(1000)) clock = SimulatedClock( start=datetime(2015, 05, 29, 12, 00), stop=datetime(2015, 05, 29, 15, 00), interval=settings.CLOCK_INTERVAL, ) # XXX: We have to be able to instantiate strategies with custom args strategies = [settings.STRATEGY(instrument) for instrument in set(instruments)] controller = Controller(clock, broker, strategies) controller.run_until_stopped()
import decimal from datetime import datetime import click from .controller import Controller, SimulatedClock from .broker import OandaBacktestBroker from .instruments import InstrumentParamType from .lib import oandapy from .conf import settings @click.command() @click.option('--instrument', '-i', 'instruments', multiple=True, type=InstrumentParamType()) def main(instruments): """ Algortihmic trading tool. """ # XXX: Currently only backtesting is supported api = oandapy.API( environment=settings.ENVIRONMENT, access_token=settings.ACCESS_TOKEN, ) broker = OandaBacktestBroker( api=api, initial_balance=decimal.Decimal(1000)) clock = SimulatedClock( start=datetime(2015, 01, 01, 12, 00), stop=datetime(2015, 01, 01, 13, 00), interval=settings.CLOCK_INTERVAL, ) # XXX: We have to be able to instantiate strategies with custom args strategies = [settings.STRATEGY(instrument) for instrument in set(instruments)] controller = Controller(clock, broker, strategies) controller.run_until_stopped()
Remove unused lambda function pool from websocket server
import { Server } from 'ws' import debugLog from '../debugLog.js' import serverlessLog from '../serverlessLog.js' import { createUniqueId } from '../utils/index.js' export default class WebSocketServer { constructor(options, webSocketClients, sharedServer) { this._options = options this._server = new Server({ server: sharedServer, }) this._webSocketClients = webSocketClients this._init() } _init() { this._server.on('connection', (webSocketClient /* request */) => { console.log('received connection') const connectionId = createUniqueId() debugLog(`connect:${connectionId}`) this._webSocketClients.addClient(webSocketClient, connectionId) }) } addRoute(functionName, functionObj, route) { this._webSocketClients.addRoute(functionName, functionObj, route) // serverlessLog(`route '${route}'`) } async start() { const { host, httpsProtocol, websocketPort } = this._options serverlessLog( `Offline [websocket] listening on ws${ httpsProtocol ? 's' : '' }://${host}:${websocketPort}`, ) } // no-op, we're re-using the http server stop() {} }
import { Server } from 'ws' import debugLog from '../debugLog.js' import LambdaFunctionPool from '../lambda/index.js' import serverlessLog from '../serverlessLog.js' import { createUniqueId } from '../utils/index.js' export default class WebSocketServer { constructor(options, webSocketClients, sharedServer) { this._lambdaFunctionPool = new LambdaFunctionPool() this._options = options this._server = new Server({ server: sharedServer, }) this._webSocketClients = webSocketClients this._init() } _init() { this._server.on('connection', (webSocketClient /* request */) => { console.log('received connection') const connectionId = createUniqueId() debugLog(`connect:${connectionId}`) this._webSocketClients.addClient(webSocketClient, connectionId) }) } addRoute(functionName, functionObj, route) { this._webSocketClients.addRoute(functionName, functionObj, route) // serverlessLog(`route '${route}'`) } async start() { const { host, httpsProtocol, websocketPort } = this._options serverlessLog( `Offline [websocket] listening on ws${ httpsProtocol ? 's' : '' }://${host}:${websocketPort}`, ) } // no-op, we're re-using the http server stop() {} }
Use enumerator instead of lists
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function() { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = listEnumerator.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
angular .module('ngSharepoint.Lists') .factory('JSOMConnector', function($q, $sp) { return ({ getLists: function() { return $q(function(resolve, reject) { var context = $sp.getContext(); var lists = context.get_web().get_lists(); context.load(lists); context.executeQueryAsync(function(sender, args) { var result = []; var listEnumerator = lists.getEnumerator(); while (listEnumerator.moveNext()) { var list = lists.get_current(); result.push(list); } resolve(result); }, reject); }); } }); });
Handle differences between semver and PEP440 Signed-off-by: Sylvain Hellegouarch <16795633e2c1543064a3ad70ac3ba71d3d589b3b@defuze.org>
# -*- coding: utf-8 -*- from unittest.mock import patch import semver from chaostoolkit import __version__ from chaostoolkit.check import check_newer_version class FakeResponse: def __init__(self, status=200, url=None, response=None): self.status_code = status self.url = url self.response = response def json(self): return self.response @patch("chaostoolkit.check.requests", autospec=True) def test_version_is_not_newer(requests): requests.get.return_value = FakeResponse( 200, "https://releases.chaostoolkit.org/latest", {"version": __version__, "up_to_date": True} ) latest_version = check_newer_version(command="init") assert latest_version is None @patch("chaostoolkit.check.requests", autospec=True) def test_version_is_newer(requests): version = __version__.replace("rc", "-rc") newer_version = semver.bump_minor(version) requests.get.return_value = FakeResponse( 200, "http://someplace//usage/latest/", {"version": __version__, "up_to_date": False} ) latest_version = check_newer_version(command="init") assert latest_version == __version__
# -*- coding: utf-8 -*- from unittest.mock import patch import semver from chaostoolkit import __version__ from chaostoolkit.check import check_newer_version class FakeResponse: def __init__(self, status=200, url=None, response=None): self.status_code = status self.url = url self.response = response def json(self): return self.response @patch("chaostoolkit.check.requests", autospec=True) def test_version_is_not_newer(requests): requests.get.return_value = FakeResponse( 200, "https://releases.chaostoolkit.org/latest", {"version": __version__, "up_to_date": True} ) latest_version = check_newer_version(command="init") assert latest_version is None @patch("chaostoolkit.check.requests", autospec=True) def test_version_is_newer(requests): newer_version = semver.bump_minor(__version__) requests.get.return_value = FakeResponse( 200, "http://someplace//usage/latest/", {"version": __version__, "up_to_date": False} ) latest_version = check_newer_version(command="init") assert latest_version == __version__
Disable filtering and sorting if not providing path
import { startCase } from "lodash"; export default schema => { let schemaToUse = schema; if (!schemaToUse.fields && Array.isArray(schema)) { schemaToUse = { fields: schema }; } schemaToUse = { ...schemaToUse }; schemaToUse.fields = schemaToUse.fields.map((field, i) => { let fieldToUse = field; if (typeof field === "string") { fieldToUse = { displayName: startCase(field), path: field, type: "string" }; } else if (!field.type) { fieldToUse = { ...field, type: "string" }; } if (!fieldToUse.displayName) { fieldToUse = { ...fieldToUse, displayName: startCase(fieldToUse.path) }; } // paths are needed for column resizing if (!fieldToUse.path) { fieldToUse = { ...fieldToUse, filterDisabled: true, sortDisabled: true, path: "fake-path" + i }; } return fieldToUse; }); return schemaToUse; };
import { startCase } from "lodash"; export default schema => { let schemaToUse = schema; if (!schemaToUse.fields && Array.isArray(schema)) { schemaToUse = { fields: schema }; } schemaToUse = { ...schemaToUse }; schemaToUse.fields = schemaToUse.fields.map((field, i) => { let fieldToUse = field; if (typeof field === "string") { fieldToUse = { displayName: startCase(field), path: field, type: "string" }; } else if (!field.type) { fieldToUse = { ...field, type: "string" }; } if (!fieldToUse.displayName) { fieldToUse = { ...fieldToUse, displayName: startCase(fieldToUse.path) }; } // paths are needed for column resizing if (!fieldToUse.path) { fieldToUse = { ...fieldToUse, path: "fake-path" + i }; } return fieldToUse; }); return schemaToUse; };
Revert "Remove unnecessary lock logging" This reverts commit ffce61611933786a9f01d01925fc154f6a7f1ecd.
var locks = require('locks'); //Map lock only used to create new partitionLocks entries var mapLock = locks.createMutex(); var partitionLocks = new Object(); var timeoutSeconds = 2; //key is unique for the namespace & partition. module.exports.lockedOperation = function lockedOperation (key, callback) { var keyStr = JSON.stringify(key); var keyLock = partitionLocks[keyStr]; // If lock does not exist - acquire the map lock and create new lock for this key if (keyLock == null) { mapLock.timedLock(timeoutSeconds * 1000, function (error) { if (error) { console.log('Could not get the partition map mutex lock within ' + timeoutSeconds + ' seconds, so gave up'); } else { if (keyLock == null) { keyLock = locks.createMutex(); partitionLocks[keyStr] = keyLock; console.log("Created partition lock object for " + keyStr); mapLock.unlock(); } } }); } if (keyLock != null) { keyLock.timedLock(timeoutSeconds * 1000, function (error) { console.log("Locked partition " + keyStr); callback(); keyLock.unlock(); console.log("Unlocked partition " + keyStr); }); } };
var locks = require('locks'); //Map lock only used to create new partitionLocks entries var mapLock = locks.createMutex(); var partitionLocks = new Object(); var timeoutSeconds = 2; //key is unique for the namespace & partition. module.exports.lockedOperation = function lockedOperation (key, callback) { var keyStr = JSON.stringify(key); var keyLock = partitionLocks[keyStr]; // If lock does not exist - acquire the map lock and create new lock for this key if (keyLock == null) { mapLock.timedLock(timeoutSeconds * 1000, function (error) { if (error) { console.log('Could not get the partition map mutex lock within ' + timeoutSeconds + ' seconds, so gave up'); } else { if (keyLock == null) { keyLock = locks.createMutex(); partitionLocks[keyStr] = keyLock; console.log("Created partition lock object for " + keyStr); mapLock.unlock(); } } }); } if (keyLock != null) { keyLock.timedLock(timeoutSeconds * 1000, function (error) { callback(); keyLock.unlock(); }); } };
Add cyrillic symbols support in mention regexp
// common chinese symbols: \u4e00-\u9eff - http://stackoverflow.com/a/1366113/837709 // hiragana (japanese): \u3040-\u309F - https://gist.github.com/ryanmcgrath/982242#file-japaneseregex-js // katakana (japanese): \u30A0-\u30FF - https://gist.github.com/ryanmcgrath/982242#file-japaneseregex-js // For an advanced explaination about Hangul see https://github.com/draft-js-plugins/draft-js-plugins/pull/480#issuecomment-254055437 // Hangul Syllables (korean): \uAC00-\uD7A3 - https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode // Hangul Jamo (korean): \u3130-\u318F - https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode // Cyrillic symbols: \u0410-\u044F - https://en.wikipedia.org/wiki/Cyrillic_script_in_Unicode export default '[\\w\u4e00-\u9eff\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7A3\u3130-\u318F\u0410-\u044F]*';
// common chinese symbols: \u4e00-\u9eff - http://stackoverflow.com/a/1366113/837709 // hiragana (japanese): \u3040-\u309F - https://gist.github.com/ryanmcgrath/982242#file-japaneseregex-js // katakana (japanese): \u30A0-\u30FF - https://gist.github.com/ryanmcgrath/982242#file-japaneseregex-js // For an advanced explaination about Hangul see https://github.com/draft-js-plugins/draft-js-plugins/pull/480#issuecomment-254055437 // Hangul Syllables (korean): \uAC00-\uD7A3 - https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode // Hangul Jamo (korean): \u3130-\u318F - https://en.wikipedia.org/wiki/Korean_language_and_computers#Hangul_in_Unicode export default '[\\w\u4e00-\u9eff\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7A3\u3130-\u318F]*';
Remove extension from grunt file
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ ts: { default: { src: ["*.ts", "node_modules/dimensions/**/*.ts", "spec/**/*.ts"], outDir: 'build' }, options: { lib: ['es2015'] } }, jasmine_node: { options: { forceExit: true, match: '.', matchall: false, extensions: 'js', specNameMatcher: 'spec' }, all: [] } }); // Tasks grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks("grunt-ts"); grunt.registerTask('default', ['ts', 'jasmine_node']); };
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ ts: { default: { src: ["*.ts", "node_modules/dimensions/**/*.ts", "extensions/1.3.5-patch/**/*.ts", "spec/**/*.ts"], outDir: 'build' }, options: { lib: ['es2015'] } }, jasmine_node: { options: { forceExit: true, match: '.', matchall: false, extensions: 'js', specNameMatcher: 'spec' }, all: [] } }); // Tasks grunt.loadNpmTasks('grunt-jasmine-node'); grunt.loadNpmTasks("grunt-ts"); grunt.registerTask('default', ['ts', 'jasmine_node']); };
Remove the logger from the heap
package io.quarkus.mutiny.runtime; import java.util.concurrent.ExecutorService; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import org.jboss.logging.Logger; import io.quarkus.runtime.annotations.Recorder; import io.smallrye.mutiny.infrastructure.Infrastructure; @Recorder public class MutinyInfrastructure { public void configureMutinyInfrastructure(ExecutorService exec) { Infrastructure.setDefaultExecutor(exec); } public void configureDroppedExceptionHandler() { Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable); } }); } public void configureThreadBlockingChecker() { Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() { @Override public boolean getAsBoolean() { String threadName = Thread.currentThread().getName(); return !threadName.contains("vertx-eventloop-thread-"); } }); } }
package io.quarkus.mutiny.runtime; import java.util.concurrent.ExecutorService; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import org.jboss.logging.Logger; import io.quarkus.runtime.annotations.Recorder; import io.smallrye.mutiny.infrastructure.Infrastructure; @Recorder public class MutinyInfrastructure { public void configureMutinyInfrastructure(ExecutorService exec) { Infrastructure.setDefaultExecutor(exec); } public void configureDroppedExceptionHandler() { Logger logger = Logger.getLogger(MutinyInfrastructure.class); Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { logger.error("Mutiny had to drop the following exception", throwable); } }); } public void configureThreadBlockingChecker() { Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() { @Override public boolean getAsBoolean() { String threadName = Thread.currentThread().getName(); return !threadName.contains("vertx-eventloop-thread-"); } }); } }
Add a couple todo's in the reset functions
<?php function reset_new($Userid) { //TODO: Delete any old entries //TODO: Delete any entries for this user if they exist global $ResetsTable; $code = reset_generate_code(); $created = time(); $sql = "INSERT INTO $ResetsTable (Userid, Code, Created) VALUES (".escape($Userid).", ".escape($code).", $created ) "; Query($sql); return $code; } function reset_by_code($code) { global $ResetsTable; return Fetch($ResetsTable, "Code = ".escape($code)); } function reset_generate_code() { return substr(bin2hex(openssl_random_pseudo_bytes(32)), 0, 64); } function resets_delete_by_id($id) { global $ResetsTable; return Query("DELETE FROM $ResetsTable WHERE Code = ".escape($id)); }
<?php function reset_new($Userid) { global $ResetsTable; $code = reset_generate_code(); $created = time(); $sql = "INSERT INTO $ResetsTable (Userid, Code, Created) VALUES (".escape($Userid).", ".escape($code).", $created ) "; Query($sql); return $code; } function reset_by_code($code){ global $ResetsTable; return Fetch($ResetsTable, "Code = ".escape($code)); } function reset_generate_code() { return substr(bin2hex(openssl_random_pseudo_bytes(32)), 0, 64); } function resets_delete_by_id($id) { global $ResetsTable; return Query("DELETE FROM $ResetsTable WHERE Code = ".escape($id)); }
Change test of configure() to validate if configure sets de parameters on the Leafbird config
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('verify if a leafbird global object has defined', function() { expect(leafbird).toBeDefined(); }); it('verify if leafbird global variable has a Leafbird object instance', function() { if(!(leafbird instanceof Leafbird)) { fail('leafbird global variable is not a Leafbird instance.'); } } ); it('verify if Leafbird has a configure method', function() { if(typeof leafbird.configure !== 'function') { fail('The Leafbird object has not a configure method'); } }); it('verify if configure method make configuration on the leafbird object', function() { var configObject = { "someConfig": "someValue" }; leafbird.configure(configObject); expect(leafbird.config).toEqual(configObject); } ); });
/* Copyright 2015 Leafbird 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. */ describe('configure', function() { it('verify if a leafbird global object has defined', function() { expect(leafbird).toBeDefined(); }); it('verify if leafbird global variable has a Leafbird object instance', function() { if(!(leafbird instanceof Leafbird)) { fail('leafbird global variable is not a Leafbird instance.'); } } ); it('verify if Leafbird has a configure method', function() { if(typeof leafbird.configure !== 'function') { fail('The Leafbird object has not a configure method'); } }); it('verify if configure method make configuration on the leafbird object', function() { leafbird.configure({}); expect(leafbird.config).toEqual(undefined); } ); });
Set stack when deploying for integration tests
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "os" ) var _ = Describe("CF Binary Buildpack", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) Describe("deploying a Ruby script", func() { BeforeEach(func() { app = cutlass.New(filepath.Join(bpDir, "fixtures", "webrick_app")) app.Stack = os.Getenv("CF_STACK") }) Context("when specifying a buildpack", func() { BeforeEach(func() { app.Buildpacks = []string{"binary_buildpack"} }) It("deploys successfully", func() { PushAppAndConfirm(app) Expect(app.GetBody("/")).To(ContainSubstring("Hello, world!")) }) }) Context("without specifying a buildpack", func() { BeforeEach(func() { app.Buildpacks = []string{} }) It("fails to stage", func() { Expect(app.Push()).ToNot(Succeed()) Eventually(app.Stdout.String).Should(ContainSubstring("None of the buildpacks detected a compatible application")) }) }) }) })
package integration_test import ( "path/filepath" "github.com/cloudfoundry/libbuildpack/cutlass" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("CF Binary Buildpack", func() { var app *cutlass.App AfterEach(func() { if app != nil { app.Destroy() } app = nil }) Describe("deploying a Ruby script", func() { BeforeEach(func() { app = cutlass.New(filepath.Join(bpDir, "fixtures", "webrick_app")) }) Context("when specifying a buildpack", func() { BeforeEach(func() { app.Buildpacks = []string{"binary_buildpack"} }) It("deploys successfully", func() { PushAppAndConfirm(app) Expect(app.GetBody("/")).To(ContainSubstring("Hello, world!")) }) }) Context("without specifying a buildpack", func() { BeforeEach(func() { app.Buildpacks = []string{} }) It("fails to stage", func() { Expect(app.Push()).ToNot(Succeed()) Eventually(app.Stdout.String).Should(ContainSubstring("None of the buildpacks detected a compatible application")) }) }) }) })
Use KeyboardEvent.key instead of code
import { Mixin, InitialRender } from './ce'; import { triggerEvent } from './events'; import { DisableBehavior } from './disabled'; import { FocusableBehavior } from './focus'; /** * Mixin that provides the behavior of a button. This set the role of the * element to `button`, add support for disabling it and normalize the * keyboard behavior. */ export let ButtonBehavior = Mixin(ParentClass => class extends ParentClass.with(DisableBehavior, FocusableBehavior, InitialRender) { initialRenderCallback() { super.initialRenderCallback(); // Mark this element as a button this.setAttribute('role', 'button'); /* * Listener that listens for a key press of Enter or Space and * emits a press event. */ this.addEventListener('keypress', e => { switch(e.key) { case 'Enter': case 'Space': e.preventDefault(); if(! this.disabled) { triggerEvent(this, 'click'); } } }); } });
import { Mixin, InitialRender } from './ce'; import { triggerEvent } from './events'; import { DisableBehavior } from './disabled'; import { FocusableBehavior } from './focus'; /** * Mixin that provides the behavior of a button. This set the role of the * element to `button`, add support for disabling it and normalize the * keyboard behavior. */ export let ButtonBehavior = Mixin(ParentClass => class extends ParentClass.with(DisableBehavior, FocusableBehavior, InitialRender) { initialRenderCallback() { super.initialRenderCallback(); // Mark this element as a button this.setAttribute('role', 'button'); /* * Listener that listens for a key press of Enter or Space and * emits a press event. */ this.addEventListener('keypress', e => { switch(e.code) { case 'Enter': case 'Space': e.preventDefault(); if(! this.disabled) { triggerEvent(this, 'click'); } } }); } });
Make truncate to be available at php 5.3 and 5.4
<?php namespace Coduo\PHPHumanizer\String; class Truncate { /** * @var string */ private $text; /** * @var int */ private $charactersCount; /** * @var string */ private $append; /** * @param string $text * @param int $charactersCount * @param string $append */ public function __construct($text, $charactersCount, $append = '') { $this->text = $text; $this->charactersCount = $charactersCount; $this->append = $append; } public function __toString() { if ($this->charactersCount < 0 || strlen($this->text) <= $this->charactersCount) { return $this->text; } $length = $this->charactersCount; if (false !== ($breakpoint = mb_strpos($this->text, ' ', $this->charactersCount))) { $length = $breakpoint; } return rtrim(mb_substr($this->text, 0, $length)) . $this->append; } }
<?php namespace Coduo\PHPHumanizer\String; class Truncate { /** * @var string */ private $text; /** * @var int */ private $charactersCount; /** * @var string */ private $append; /** * @param string $text * @param int $charactersCount * @param string $append */ public function __construct($text, $charactersCount, $append = '') { $this->text = $text; $this->charactersCount = $charactersCount; $this->append = $append; } public function __toString() { if ($this->charactersCount < 0 || strlen($this->text) <= $this->charactersCount) { return $this->text; } $word = \IntlBreakIterator::createWordInstance(\Locale::getDefault()); $word->setText($this->text); $word->following($this->charactersCount); return substr($this->text, 0, $word->current()) . $this->append; } }
Fix Trace ::start -> ::load
<?php use OpenCensus\Trace\Tracer; use OpenCensus\Trace\Exporter\StackdriverExporter; require __DIR__ . '/helpers.php'; if (is_gae() && (php_sapi_name() != 'cli')){ if (is_gae_flex()){ Tracer::start(new StackdriverExporter(['async' => true])); } else { // TODO: Async on Standard Environment too! Tracer::start(new StackdriverExporter()); } // TODO: Different arrays for Laravel vs Lumen? $traceProviders = [ // OpenSensus provides a basic Laravel trace adapter, // which covered Eloquent and view compilation. OpenCensus\Trace\Integrations\Laravel::class, // Also load our own extended Laravel trace set. A1comms\GaeSupportLaravel\Trace\Integration\LaravelExtended::class, // Trace our other basic functions... OpenCensus\Trace\Integrations\Mysql::class, OpenCensus\Trace\Integrations\PDO::class, OpenCensus\Trace\Integrations\Memcached::class, ]; foreach ($traceProviders as $p) { $p::load(); } }
<?php use OpenCensus\Trace\Tracer; use OpenCensus\Trace\Exporter\StackdriverExporter; require __DIR__ . '/helpers.php'; if (is_gae() && (php_sapi_name() != 'cli')){ if (is_gae_flex()){ Tracer::start(new StackdriverExporter(['async' => true])); } else { // TODO: Async on Standard Environment too! Tracer::start(new StackdriverExporter()); } // TODO: Different arrays for Laravel vs Lumen? $traceProviders = [ // OpenSensus provides a basic Laravel trace adapter, // which covered Eloquent and view compilation. OpenCensus\Trace\Integrations\Laravel::class, // Also load our own extended Laravel trace set. A1comms\GaeSupportLaravel\Trace\Integration\LaravelExtended::class, // Trace our other basic functions... OpenCensus\Trace\Integrations\Mysql::class, OpenCensus\Trace\Integrations\PDO::class, OpenCensus\Trace\Integrations\Memcached::class, ]; foreach ($traceProviders as $p) { $p::start(); } }
Move to buttons & remove hardcoding of image size
# coding: utf-8 # ui.View subclass for the top ten iTunes songs. # Pull requests gladly accepted. import feedparser, requests, ui url = 'https://itunes.apple.com/us/rss/topsongs/limit=10/xml' def get_image_urls(itunes_url): for entry in feedparser.parse(itunes_url).entries: yield entry['summary'].partition('src="')[2].partition('"')[0] class TopTenView(ui.View): def __init__(self, image_urls): self.present() for i, url in enumerate(image_urls): button = ui.Button() button.background_image = ui.Image.from_data(requests.get(url).content) w, h = button.background_image.size button.x = i % 5 * w button.y = i / 5 * h button.width, button.height = w, h button.border_width = 2 self.add_subview(button) TopTenView(list(get_image_urls(url)))
# coding: utf-8 # ui.View subclass for the top ten iTunes songs. # Pull requests gladly accepted. import feedparser, requests, ui url = 'https://itunes.apple.com/us/rss/topsongs/limit=10/xml' def get_image_urls(itunes_url): for entry in feedparser.parse(itunes_url).entries: yield entry['summary'].partition('src="')[2].partition('"')[0] class TopTenView(ui.View): def __init__(self, image_urls): self.present() for i, url in enumerate(image_urls): button = ui.Button() button.background_image = ui.Image.from_data(requests.get(url).content) button.border_width = 2 button.x = (i % 5) * 128 + 10 button.y = (i / 5) * 128 + 10 button.width = button.height = 128 self.add_subview(button) TopTenView(list(get_image_urls(url)))
Use QuerySelectorAll to find links Faster, and avoid <A> that lack hrefs.
// Entire frame is insecure? if ((document.location.protocol == "http:") || (document.location.protocol == "ftp:")) { document.body.style.backgroundColor="#E04343"; } var lnks = document.querySelectorAll("a[href]"); var arrUnsecure = []; for (var i = 0; i < lnks.length; i++) { var thisLink = lnks[i]; var sProtocol = thisLink.protocol.toLowerCase(); if ((sProtocol == "http:") || (sProtocol == "ftp:")) { arrUnsecure.push(thisLink.href); thisLink.style.backgroundColor = "#DE6A6A"; thisLink.style.borderRadius = "4px"; thisLink.style.border = "2px solid red"; thisLink.style.padding = "6px 6px 6px 6px"; thisLink.style.margin = "3px 3px 3px 3px"; thisLink.title = lnks[i].protocol + "//" + lnks[i].hostname; } } //https://developer.chrome.com/extensions/messaging chrome.runtime.sendMessage({cLinks: lnks.length, unsecure: arrUnsecure }, null //function(response) { console.log(response.farewell);} );
// Entire frame is insecure? if ((document.location.protocol == "http:") || (document.location.protocol == "ftp:")) { document.body.style.backgroundColor="#E04343"; } var lnks = document.getElementsByTagName("a"); var arrUnsecure = []; for(var i = 0; i < lnks.length; i++) { var thisLink = lnks[i]; var sProtocol = thisLink.protocol.toLowerCase(); if ((sProtocol == "http:") || (sProtocol == "ftp:")) { arrUnsecure.push(thisLink.href); thisLink.style.backgroundColor = "#DE6A6A"; thisLink.style.borderRadius = "4px"; thisLink.style.border = "2px solid red"; thisLink.style.padding = "6px 6px 6px 6px"; thisLink.style.margin = "3px 3px 3px 3px"; thisLink.title = lnks[i].protocol + "//" + lnks[i].hostname; } } //https://developer.chrome.com/extensions/messaging chrome.runtime.sendMessage({cLinks: lnks.length, unsecure: arrUnsecure }, null //function(response) { console.log(response.farewell);} );
Return translation instead of tuple Fixes Attributerror: 'tuple' object has no attribute 'format' when POSTing with no value for an Enum field.
from django.utils.translation import ugettext_lazy as _ from rest_framework.fields import ChoiceField class EnumField(ChoiceField): default_error_messages = { 'invalid': _("No matching enum type.") } def __init__(self, **kwargs): self.enum_type = kwargs.pop("enum_type") kwargs.pop("choices", None) super(EnumField, self).__init__(self.enum_type.choices(), **kwargs) def to_internal_value(self, data): for choice in self.enum_type: if choice.name == data or choice.value == data: return choice self.fail('invalid') def to_representation(self, value): if not value: return None return value.name
from rest_framework.fields import ChoiceField class EnumField(ChoiceField): default_error_messages = { 'invalid': ("No matching enum type.",) } def __init__(self, **kwargs): self.enum_type = kwargs.pop("enum_type") kwargs.pop("choices", None) super(EnumField, self).__init__(self.enum_type.choices(), **kwargs) def to_internal_value(self, data): for choice in self.enum_type: if choice.name == data or choice.value == data: return choice self.fail('invalid') def to_representation(self, value): if not value: return None return value.name
Use image schema, thumbs are deprecated
import mongoose from 'mongoose'; import { ImageSchema } from 'src/models/ImageModel'; const { Schema } = mongoose; export const PostSchema = new Schema({ title: { type: String, unique: true, required: true, }, created: { type: Date, default: Date.now, }, lastEdited: { type: Date, default: null, }, lastSaved: { type: Date, default: null, }, lastPublished: { type: Date, default: null, }, postDate: { type: Date, default: Date.now, }, markdown: { type: String, default: '', }, notificationSent: { type: Boolean, default: false, }, titleImage: ImageSchema, images: [ImageSchema], drawings: [ImageSchema], }); PostSchema.pre('validate', function preSave(next) { const title = this.markdown.match(/^# .+/gm); this.title = title ? title[0].replace('# ', '') : ''; next(); }); export default mongoose.model('Post', PostSchema);
import mongoose from 'mongoose'; import { ImageSchema } from 'src/models/ImageModel'; import { ThumbnailSchema } from 'src/models/ThumbnailModel'; const { Schema } = mongoose; export const PostSchema = new Schema({ title: { type: String, unique: true, required: true, }, created: { type: Date, default: Date.now, }, lastEdited: { type: Date, default: null, }, lastSaved: { type: Date, default: null, }, lastPublished: { type: Date, default: null, }, postDate: { type: Date, default: Date.now, }, markdown: { type: String, default: '', }, notificationSent: { type: Boolean, default: false, }, titleImage: ThumbnailSchema, images: [ImageSchema], drawings: [ImageSchema], }); PostSchema.pre('validate', function preSave(next) { const title = this.markdown.match(/^# .+/gm); this.title = title ? title[0].replace('# ', '') : ''; next(); }); export default mongoose.model('Post', PostSchema);
LogglyWriter: Fix goroutine leak when replacing LogglyWriter instance Each config update (after the first setting) of "gop"/"loggly_logging_token" was leaking a goro.
package gop import ( "fmt" "os" "github.com/cocoonlife/go-loggly" ) // A timber.LogWriter for the loggly service. // LogglyWriter is a Timber writer to send logging to the loggly // service. See: https://loggly.com. type LogglyWriter struct { c *loggly.Client } // NewLogEntriesWriter creates a new writer for sending logging to logentries. func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) { return &LogglyWriter{c: loggly.New(token, tags...)}, nil } // LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface. func (w *LogglyWriter) LogWrite(msg string) { // using type for the message string is how the Info etc methods on the // loggly client work. // TODO: Add a "level" key for info, error..., proper timestamp etc // Buffers the message for async send // TODO - Stat for the bytes written return? if _, err := w.c.Write([]byte(msg)); err != nil { // TODO: What is best todo here as if we log it will loop? fmt.Fprintf(os.Stderr, "loggly send error: %s\n", err.Error()) } } // Close the write. Satifies the timber.LogWriter interface. func (w *LogglyWriter) Close() { w.c.Flush() close(w.c.ShutdownChan) }
package gop import ( "fmt" "os" "github.com/segmentio/go-loggly" ) // A timber.LogWriter for the loggly service. // LogglyWriter is a Timber writer to send logging to the loggly // service. See: https://loggly.com. type LogglyWriter struct { c *loggly.Client } // NewLogEntriesWriter creates a new writer for sending logging to logentries. func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) { return &LogglyWriter{c: loggly.New(token, tags...)}, nil } // LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface. func (w *LogglyWriter) LogWrite(msg string) { // using type for the message string is how the Info etc methods on the // loggly client work. // TODO: Add a "level" key for info, error..., proper timestamp etc // Buffers the message for async send // TODO - Stat for the bytes written return? if _, err := w.c.Write([]byte(msg)); err != nil { // TODO: What is best todo here as if we log it will loop? fmt.Fprintf(os.Stderr, "loggly send error: %s\n", err.Error()) } } // Close the write. Satifies the timber.LogWriter interface. func (w *LogglyWriter) Close() { w.c.Flush() }
Remove security advisory rss feed link until it's ready
<div class="row page-content-header"> <div class="col-md-4"> <h1>Security Advisories</h1> </div> <div class="col-md-5 col-md-offset-3"> <form role="form" action="/security/advisory/" method="get"> <input name="id" type="text" class="form-control" placeholder="Advisory identifier"> <button type="submit" class="btn btn-default">Go</button> </form> </div> </div> <div class="row" style=" margin-top: 40px; "> <div class="col-md-4"> <h2>ownCloud Server</h2><br> <?php get_template_part('advisories/server-list-part'); ?> </div> <div class="col-md-4"> <h2>Desktop Clients</h2><br> <p>Coming soon</p> </div> <div class="col-md-4"> <h2>Mobile Clients</h2><br> <p>Coming soon</p> </div> </div>
<div class="row page-content-header"> <div class="col-md-4"> <h1>Security Advisories</h1> <a href="/security/advisories/feed" class="rss-button">RSS</a> </div> <div class="col-md-5 col-md-offset-3"> <form role="form" action="/security/advisory/" method="get"> <input name="id" type="text" class="form-control" placeholder="Advisory identifier"> <button type="submit" class="btn btn-default">Go</button> </form> </div> </div> <div class="row" style=" margin-top: 40px; "> <div class="col-md-4"> <h2>ownCloud Server</h2><br> <?php get_template_part('advisories/server-list-part'); ?> </div> <div class="col-md-4"> <h2>Desktop Clients</h2><br> <p>Coming soon</p> </div> <div class="col-md-4"> <h2>Mobile Clients</h2><br> <p>Coming soon</p> </div> </div>
Add image upload to event form
"""Forms definitions.""" from django import forms from .models import Event class EventForm(forms.ModelForm): """Form for EventCreateView.""" class Meta: # noqa model = Event fields = ( 'title', 'date', 'venue', 'description', 'fb_event_url', 'flyer_image', ) def clean_fb_event_url(self): url = self.cleaned_data['fb_event_url'] # heuristics to check validity of a facebook event url fb_event_content = ['facebook', 'events'] if url: for x in fb_event_content: if x not in url: raise forms.ValidationError('Not a Facebook Event URL') return url
"""Forms definitions.""" from django import forms from .models import Event class EventForm(forms.ModelForm): """Form for EventCreateView.""" class Meta: # noqa model = Event fields = ( 'title', 'date', 'venue', 'description', 'fb_event_url', ) def clean_fb_event_url(self): url = self.cleaned_data['fb_event_url'] # heuristics to check validity of a facebook event url fb_event_content = ['facebook', 'events'] if url: for x in fb_event_content: if x not in url: raise forms.ValidationError('Not a Facebook Event URL') return url
Allow more than one test class (at least for annotation reading).
import java.util.*; import java.lang.*; import java.lang.reflect.*; import java.lang.annotation.*; public class ReadForbidden { public static void main(String args[]) throws Exception { if(args.length != 1) { System.err.println("missing class argument"); System.exit(-1); } String grep = "egrep '(java/lang/ClassLoader|java\\.lang\\.ClassLoader|java/lang/reflect|java\\.lang\\.reflect"; ClassLoader cl = ClassLoader.getSystemClassLoader(); for (String tcln : args) { Class newClass = cl.loadClass(tcln); Forbidden forbidden = (Forbidden) newClass.getAnnotation(Forbidden.class); for (String s : forbidden.value()) { String escape = s.replaceAll("\\.", "\\\\."); grep += "|" + escape; escape = s.replaceAll("\\.", "/"); grep += "|" + escape; } } grep += ")'"; System.out.println(grep); } }
import java.util.*; import java.lang.*; import java.lang.reflect.*; import java.lang.annotation.*; public class ReadForbidden { public static void main(String args[]) throws Exception { if(args.length != 1) { System.err.println("missing class argument"); System.exit(-1); } String tcln = args[0]; ClassLoader cl = ClassLoader.getSystemClassLoader(); Class newClass = cl.loadClass(tcln); Forbidden forbidden = (Forbidden) newClass.getAnnotation(Forbidden.class); String grep = "egrep '(java/lang/ClassLoader|java\\.lang\\.ClassLoader|java/lang/reflect|java\\.lang\\.reflect"; for (String s : forbidden.value()) { String escape = s.replaceAll("\\.", "\\\\."); grep += "|" + escape; escape = s.replaceAll("\\.", "/"); grep += "|" + escape; } grep += ")'"; System.out.println(grep); } }
Fix duplicate key in webpack config Fix that `compress` key appears twice in `webpack.optimize.UglifyJsPlugin` params.
const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const commonConfig = require('./webpack.common.js'); const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; module.exports = webpackMerge(commonConfig, { devtool: 'source-map', externals: { 'react': 'React', 'react-dom': 'ReactDOM' }, performance: { hints: "warning" }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true, mangle: { screw_ie8: true, keep_fnames: true }, compress: { warnings: false, screw_ie8: true }, comments: false }) ] });
const webpack = require('webpack'); const webpackMerge = require('webpack-merge'); const commonConfig = require('./webpack.common.js'); const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; module.exports = webpackMerge(commonConfig, { devtool: 'source-map', externals: { 'react': 'React', 'react-dom': 'ReactDOM' }, performance: { hints: "warning" }, plugins: [ new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: true, mangle: { screw_ie8: true, keep_fnames: true }, compress: { warnings: false, screw_ie8: true }, comments: false }) ] });
Split out mock test, removed failing test. Verified Travis is working.
import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import System from 'systemjs'; import '../config.js'; chai.use(sinonChai); describe('myModule', () => { let _, myModule; before(() => { return System.import('lodash') .then((lodash) => { _ = lodash; // Mock lodash library sinon.spy(_, 'camelCase'); System.set(System.normalizeSync('lodash'), System.newModule({ default: _ })); }) .then(() => System.import('./lib/myModule.js')) .then((mod) => myModule = mod); }); describe('Module Loading', () => { it('should load', () => { expect(myModule['default']).to.equal('myModuleWorks'); }); }); describe('Sinon Mocks and Spies', () => { it('should mock lodash', () => { expect(_.camelCase).to.have.been.calledWith('myModule works!'); }); }); });
import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import System from 'systemjs'; import '../config.js'; chai.use(sinonChai); describe('myModule', () => { let _, myModule; before(() => { return System.import('lodash') .then((lodash) => { _ = lodash; // Mock lodash library sinon.spy(_, 'camelCase'); System.set(System.normalizeSync('lodash'), System.newModule({ default: _ })); }) .then(() => System.import('./lib/myModule.js')) .then((mod) => myModule = mod); }); describe('Module Loading', () => { it('should load', () => { expect(myModule['default']).to.equal('myModuleWorks'); expect(_.camelCase).to.have.been.calledWith('myModule works!'); }); }); describe('Test Failing', () => { it('should show a failed test', () => { expect('apples').to.equal('oranges'); }); }); });
Revert "use environment variable for port" This reverts commit 03abed36a666e1bd0e422b3eb7a0602905d57de5.
/* AIDA Source Code */ /* Contributors located at: github.com/2nd47/CSC309-A4 */ // main app // server modules var bcrypt = require('bcryptjs'); var express = require('express'); var mongoose = require('mongoose'); var session = require('express-session'); var validator = require('validator'); var qs = require('querystring'); // testing modules var testCase = require('mocha').describe; var pre = require('mocha').before; var assertions = require('mocha').it; var assert = require('chai').assert; // module init var app = express(); // router import keeps main file clean var router = require('./router'); var db = require('../db/db.js'); // app init const APP_PORT = 3000; const saltRounds = 10; function init() { return; } function main() { init(); app.use('/', router); app.listen(APP_PORT); console.log('Server listening on port ' + APP_PORT); } main();
/* AIDA Source Code */ /* Contributors located at: github.com/2nd47/CSC309-A4 */ // main app // server modules var bcrypt = require('bcryptjs'); var express = require('express'); var mongoose = require('mongoose'); var session = require('express-session'); var validator = require('validator'); var qs = require('querystring'); // testing modules var testCase = require('mocha').describe; var pre = require('mocha').before; var assertions = require('mocha').it; var assert = require('chai').assert; // module init var app = express(); // router import keeps main file clean var router = require('./router'); var db = require('../db/db.js'); // app init const APP_PORT = process.env.port || 3000; const saltRounds = 10; function init() { return; } function main() { init(); app.use('/', router); app.listen(APP_PORT); console.log('Server listening on port ' + APP_PORT); } main();
[OWL-277] Fix ambiguous message while connecting to database
package db import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/open-falcon/hbs/g" "log" ) var DB *sql.DB func Init() { err := dbInit(g.Config().Database) if err != nil { log.Fatalln(err) } DB.SetMaxIdleConns(g.Config().MaxIdle) } func dbInit(dsn string) (err error) { if DB, err = sql.Open("mysql", dsn) err != nil { return fmt.Errorf("Open DB error: %v", err) } if err = DB.Ping() err != nil { return fmt.Errorf("Ping DB error: %v", err) } return } // Convenient IoC for transaction processing func inTx(txCallback func(tx *sql.Tx) error) (err error) { var tx *sql.Tx if tx, err = DB.Begin() err != nil { return } /** * The transaction result by whether or not the callback has error */ defer func() { if err == nil { tx.Commit() } else { tx.Rollback() } }() // :~) err = txCallback(tx) return }
package db import ( "database/sql" _ "github.com/go-sql-driver/mysql" "github.com/open-falcon/hbs/g" "log" ) var DB *sql.DB func Init() { err := dbInit(g.Config().Database) if err != nil { log.Fatalf("open db fail: %v", err) } DB.SetMaxIdleConns(g.Config().MaxIdle) } func dbInit(dsn string) (err error) { if DB, err = sql.Open("mysql", dsn) err != nil { return } if err = DB.Ping() err != nil { return } return } // Convenient IoC for transaction processing func inTx(txCallback func(tx *sql.Tx) error) (err error) { var tx *sql.Tx if tx, err = DB.Begin() err != nil { return } /** * The transaction result by whether or not the callback has error */ defer func() { if err == nil { tx.Commit() } else { tx.Rollback() } }() // :~) err = txCallback(tx) return }
Add logging at the beginning of gitPull().
// First, import everything we need (I assume that you installed Flick via the above command). var connect = require( 'connect' ), shell = require( 'shelljs' ), flick = require( '..' ), handler = flick( { whitelist: { local: true } } ), app = connect(); // Then, define the action to run once we'll receive the notification from GitHub. function gitPull( root, options ) { return function( req, res, next ) { console.log( '[flick] Web hook called.' ); var cmd = 'git pull' + ( options.rebase ? ' --rebase' : '' ); shell.cd( root ); shell.exec( cmd, function( code, output ) { console.log( cmd + ' exited with code ' + code ); } ); next(); }; } // Tell Flick to run that action everytime we receive a notification for a specific repository. handler.use( 'romac/romac.github.com', gitPull( '/var/www/romac.me', { rebase: true } ) ); // Let's parse POST body. app.use( connect.bodyParser() ); // Supply it to Flick's handler app.use( handler ); // Thank GitHub for their niceness app.use( function( req, res ) { res.writeHead( 200 ); res.end( 'Thank you, dear friend.\n' ); } ); app.listen( 4001 ); console.log( 'flick is listening on port 4001' );
// First, import everything we need (I assume that you installed Flick via the above command). var connect = require( 'connect' ), shell = require( 'shelljs' ), flick = require( '..' ), handler = flick( { whitelist: { local: true } } ), app = connect(); // Then, define the action to run once we'll receive the notification from GitHub. function gitPull( root, options ) { return function( req, res, next ) { var cmd = 'git pull' + ( options.rebase ? ' --rebase' : '' ); shell.cd( root ); shell.exec( cmd, function( code, output ) { console.log( cmd + ' exited with code ' + code ); } ); next(); }; } // Tell Flick to run that action everytime we receive a notification for a specific repository. handler.use( 'romac/romac.github.com', gitPull( '/var/www/romac.me', { rebase: true } ) ); // Let's parse POST body. app.use( connect.bodyParser() ); // Supply it to Flick's handler app.use( handler ); // Thank GitHub for their niceness app.use( function( req, res ) { res.writeHead( 200 ); res.end( 'Thank you, dear friend.\n' ); } ); app.listen( 4001 ); console.log( 'flick is listening on port 4001' );
Revert accidental committal of client test-data Client should not get test-data right now; that was just for debugging.
Package.describe({ summary: "Given the set of the constraints, picks a satisfying configuration", version: "1.0.15" }); Npm.depends({ 'mori': '0.2.6' }); Package.on_use(function (api) { api.export('ConstraintSolver'); api.use(['underscore', 'ejson', 'check', 'package-version-parser', 'binary-heap', 'random'], 'server'); api.add_files(['constraint-solver.js', 'resolver.js', 'constraints-list.js', 'resolver-state.js', 'priority-queue.js'], ['server']); }); Package.on_test(function (api) { api.use('constraint-solver', ['server']); api.use(['tinytest', 'minimongo', 'package-version-parser']); // data for big benchmarky tests api.add_files('test-data.js', ['server']); api.add_files('constraint-solver-tests.js', ['server']); api.add_files('resolver-tests.js', ['server']); api.use('underscore'); });
Package.describe({ summary: "Given the set of the constraints, picks a satisfying configuration", version: "1.0.15" }); Npm.depends({ 'mori': '0.2.6' }); Package.on_use(function (api) { api.export('ConstraintSolver'); api.use(['underscore', 'ejson', 'check', 'package-version-parser', 'binary-heap', 'random'], 'server'); api.add_files(['constraint-solver.js', 'resolver.js', 'constraints-list.js', 'resolver-state.js', 'priority-queue.js'], ['server']); }); Package.on_test(function (api) { api.use('constraint-solver', ['server']); api.use(['tinytest', 'minimongo', 'package-version-parser']); // data for big benchmarky tests api.add_files('test-data.js', ['server', 'client']); api.add_files('constraint-solver-tests.js', ['server']); api.add_files('resolver-tests.js', ['server']); api.use('underscore'); });
Add netlify badge to qualify for open source plan
import React from 'react'; import { Container, Row, Col } from 'reactstrap'; export default () => { return ( <div className="footer"> <Container> <Row> <Col className="text-center"> <p className="social"> <iframe src="https://ghbtns.com/github-btn.html?user=reactstrap&repo=reactstrap&type=star&count=true" frameBorder="0" scrolling="0" width="100" height="20px" /> <iframe src="https://ghbtns.com/github-btn.html?user=reactstrap&repo=reactstrap&type=fork&count=true" frameBorder="0" scrolling="0" width="100" height="20px" /> </p> <a href="https://www.netlify.com"> <img src="https://www.netlify.com/img/global/badges/netlify-light.svg" alt="Deploys by Netlify" /> </a> </Col> </Row> </Container> </div> ); };
import React from 'react'; import { Container, Row, Col } from 'reactstrap'; export default () => { return ( <div className="footer"> <Container> <Row> <Col className="text-center"> <p className="social"> <iframe src="https://ghbtns.com/github-btn.html?user=reactstrap&repo=reactstrap&type=star&count=true" frameBorder="0" scrolling="0" width="100" height="20px" /> <iframe src="https://ghbtns.com/github-btn.html?user=reactstrap&repo=reactstrap&type=fork&count=true" frameBorder="0" scrolling="0" width="100" height="20px" /> </p> </Col> </Row> </Container> </div> ); };
[DDW-667] Hide staking from app menu
// @flow import { ROUTES } from '../routes-config'; import walletsIcon from '../assets/images/sidebar/wallet-ic.inline.svg'; import settingsIcon from '../assets/images/sidebar/settings-ic.inline.svg'; import paperWalletCertificateIcon from '../assets/images/sidebar/paper-certificate-ic.inline.svg'; import stakingIcon from '../assets/images/sidebar/delegation-ic.inline.svg'; export const CATEGORIES_BY_NAME = { WALLETS: { name: 'WALLETS', route: ROUTES.WALLETS.ROOT, icon: walletsIcon, }, PAPER_WALLET_CREATE_CERTIFICATE: { name: 'PAPER_WALLET_CREATE_CERTIFICATE', route: ROUTES.PAPER_WALLET_CREATE_CERTIFICATE, icon: paperWalletCertificateIcon, }, STAKING: { name: 'STAKING', route: ROUTES.STAKING.ROOT, icon: stakingIcon, }, SETTINGS: { name: 'SETTINGS', route: ROUTES.SETTINGS.ROOT, icon: settingsIcon, }, }; export const CATEGORIES = [ CATEGORIES_BY_NAME.WALLETS, CATEGORIES_BY_NAME.PAPER_WALLET_CREATE_CERTIFICATE, CATEGORIES_BY_NAME.SETTINGS, ]; export const sidebarConfig = { CATEGORIES_BY_NAME, CATEGORIES };
// @flow import { ROUTES } from '../routes-config'; import walletsIcon from '../assets/images/sidebar/wallet-ic.inline.svg'; import settingsIcon from '../assets/images/sidebar/settings-ic.inline.svg'; import paperWalletCertificateIcon from '../assets/images/sidebar/paper-certificate-ic.inline.svg'; import stakingIcon from '../assets/images/sidebar/delegation-ic.inline.svg'; export const CATEGORIES_BY_NAME = { WALLETS: { name: 'WALLETS', route: ROUTES.WALLETS.ROOT, icon: walletsIcon, }, PAPER_WALLET_CREATE_CERTIFICATE: { name: 'PAPER_WALLET_CREATE_CERTIFICATE', route: ROUTES.PAPER_WALLET_CREATE_CERTIFICATE, icon: paperWalletCertificateIcon, }, STAKING: { name: 'STAKING', route: ROUTES.STAKING.ROOT, icon: stakingIcon, }, SETTINGS: { name: 'SETTINGS', route: ROUTES.SETTINGS.ROOT, icon: settingsIcon, }, }; export const CATEGORIES = [ CATEGORIES_BY_NAME.WALLETS, CATEGORIES_BY_NAME.PAPER_WALLET_CREATE_CERTIFICATE, CATEGORIES_BY_NAME.STAKING, CATEGORIES_BY_NAME.SETTINGS, ]; export const sidebarConfig = { CATEGORIES_BY_NAME, CATEGORIES };
Send message where there are no members present at the office
// Description: // Check who's at the office // // Commands // @kontoret / @office - Reply with everyone at the office const _ = require('lodash'); const presence = require('../lib/presence'); const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@kontoret|@office/i, msg => { // Reply with a message containing mentions of members at the office. presence() .then(presence => { const members = presence.members; const presentMembers = members.filter(member => member.is_active); if (presentMembers.length === 0) { msg.send('Ingen på kontoret akkurat nå :white_frowning_face:'); return; } msg.send( presentMembers.map(member => createMention(member.slack)).join(', ') ); }) .catch(error => msg.send(error.message)); }); };
// Description: // Check who's at the office // // Commands // @kontoret / @office - Reply with everyone at the office const _ = require('lodash'); const presence = require('../lib/presence'); const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@kontoret|@office/i, msg => { // Reply with a message containing mentions of members at the office. presence() .then(presence => { const members = presence.members; if (members.length === 0) { msg.send('Ingen på kontoret akkurat nå :white_frowning_face:'); return; } msg.send( members .filter(member => member.is_active) .map(member => createMention(member.slack)) .join(', ') ); }) .catch(error => msg.send(error.message)); }); };
Update administration tool copyright year
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2010 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2008 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
Add callback to handle result of promises queued
export class PromiseQueue { constructor(result_callback) { this.promises = []; this.resultCallback = result_callback; this.endCallback; this.exceptionCallback; this.running; } run() { if(!this.running) { if(this.promises.isEmpty()) { if(this.endCallback) { this.endCallback(); } } else { this.running = this.promises.shift(); this.running.call() .then(result => { if(this.resultCallback) { this.resultCallback(result); } this.running = undefined; this.run(); }) .catch(exception => { if(this.exceptionCallback) { this.exceptionCallback(exception); } }); } } } add(promise) { this.promises.push(promise); this.run(); return this; } addAll(promises) { this.promises.pushAll(promises); this.run(); return this; } clear() { this.promises = []; return this; } then(callback) { this.endCallback = callback; return this; } catch(callback) { this.exceptionCallback = callback; return this; } }
'use strict'; export class PromiseQueue { constructor() { this.promises = []; this.endCallback; this.exceptionCallback; this.running; } run() { if(!this.running) { if(this.promises.isEmpty()) { if(this.endCallback) { this.endCallback(); } } else { this.running = this.promises.shift(); this.running.call() .then(() => {this.running = undefined; this.run();}) .catch(exception => {if(this.exceptionCallback) {this.exceptionCallback(exception);}}); } } } add(promise) { this.promises.push(promise); this.run(); return this; } addAll(promises) { this.promises.pushAll(promises); this.run(); return this; } clear() { this.promises = []; return this; } then(callback) { this.endCallback = callback; return this; } catch(callback) { this.exceptionCallback = callback; return this; } }
Allow user to set their initial amount of cash and drugs
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
Add example in Eval class
<?php /** * Execute arbitrary PHP code. * * ## EXAMPLES * * # Display WordPress content directory. * $ wp eval 'echo WP_CONTENT_DIR;' * /var/www/wordpress/wp-content * * # Generate a random number. * $ wp eval 'echo rand();' --skip-wordpress * 479620423 */ class Eval_Command extends WP_CLI_Command { /** * Execute arbitrary PHP code. * * ## OPTIONS * * <php-code> * : The code to execute, as a string. * * [--skip-wordpress] * : Execute code without loading WordPress. * * ## EXAMPLES * * # Display WordPress content directory. * $ wp eval 'echo WP_CONTENT_DIR;' * /var/www/wordpress/wp-content * * # Generate a random number. * $ wp eval 'echo rand();' --skip-wordpress * 479620423 * * @when before_wp_load */ public function __invoke( $args, $assoc_args ) { if ( null === \WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) { WP_CLI::get_runner()->load_wordpress(); } eval( $args[0] ); } } WP_CLI::add_command( 'eval', 'Eval_Command' );
<?php class Eval_Command extends WP_CLI_Command { /** * Execute arbitrary PHP code. * * ## OPTIONS * * <php-code> * : The code to execute, as a string. * * [--skip-wordpress] * : Execute code without loading WordPress. * * @when before_wp_load * * ## EXAMPLES * * $ wp eval 'echo WP_CONTENT_DIR;' * /var/www/wordpress/wp-content * * $ wp eval 'echo rand();' --skip-wordpress * 479620423 */ public function __invoke( $args, $assoc_args ) { if ( null === \WP_CLI\Utils\get_flag_value( $assoc_args, 'skip-wordpress' ) ) { WP_CLI::get_runner()->load_wordpress(); } eval( $args[0] ); } } WP_CLI::add_command( 'eval', 'Eval_Command' );
Sort tallied measurements for consistent display
import React from 'react'; const tally = (measurements, buffer) => { const tallied = measurements.reduce((accum, value) => { accum[value+buffer] = (accum[value+buffer] || 0) + 1; return accum; }, {}); return ( <table className="MeasurementsTally table table-bordered"> <thead> <tr> <th>Measurement + Buffer</th> <th>Count</th> </tr> </thead> <tbody> { Object.keys(tallied).sort().map((m) => ( <tr key={`t-${m}`}> <td>{m}</td> <td>{tallied[m]}</td> </tr> ))} </tbody> </table> ); }; const MeasurementsTally = ({measurements = [], buffer=0}) => measurements.length > 0 ? tally(measurements, buffer) : null; export default MeasurementsTally;
import React from 'react'; const tally = (measurements, buffer) => { const tallied = measurements.reduce((accum, value) => { accum[value+buffer] = (accum[value+buffer] || 0) + 1; return accum; }, {}); return ( <table className="MeasurementsTally table table-bordered"> <thead> <tr> <th>Measurement + Buffer</th> <th>Count</th> </tr> </thead> <tbody> { Object.keys(tallied).map((m) => ( <tr key={`t-${m}`}> <td>{m}</td> <td>{tallied[m]}</td> </tr> ))} </tbody> </table> ); }; const MeasurementsTally = ({measurements = [], buffer=0}) => measurements.length > 0 ? tally(measurements, buffer) : null; export default MeasurementsTally;
Introduce bitfield describing edge capabilities.
// gogl provides a framework for representing and working with graphs. package gogl // Constants defining graph capabilities and behaviors. const ( E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1 E_UNDIRECTED, EM_UNDIRECTED E_WEIGHTED, EM_WEIGHTED E_TYPED, EM_TYPED E_SIGNED, EM_SIGNED E_LOOPS, EM_LOOPS E_MULTIGRAPH, EM_MULTIGRAPH ) type Vertex interface{} type Graph interface { EachVertex(f func(vertex Vertex)) EachEdge(f func(source Vertex, target Vertex)) EachAdjacent(vertex Vertex, f func(adjacent Vertex)) HasVertex(vertex Vertex) bool GetSubgraph([]Vertex) Graph } type MutableGraph interface { Graph AddVertex(v interface{}) bool RemoveVertex(v interface{}) bool } type DirectedGraph interface { Graph Transpose() DirectedGraph IsAcyclic() bool GetCycles() [][]interface{} } type MutableDirectedGraph interface { MutableGraph DirectedGraph addDirectedEdge(source interface{}, target interface{}) bool removeDirectedEdge(source interface{}, target interface{}) bool } type Edge interface { Tail() Vertex Head() Vertex }
// gogl provides a framework for representing and working with graphs. package gogl type Vertex interface{} type Graph interface { EachVertex(f func(vertex Vertex)) EachEdge(f func(source Vertex, target Vertex)) EachAdjacent(vertex Vertex, f func(adjacent Vertex)) HasVertex(vertex Vertex) bool GetSubgraph([]Vertex) Graph } type MutableGraph interface { Graph AddVertex(v interface{}) bool RemoveVertex(v interface{}) bool } type DirectedGraph interface { Graph Transpose() DirectedGraph IsAcyclic() bool GetCycles() [][]interface{} } type MutableDirectedGraph interface { MutableGraph DirectedGraph addDirectedEdge(source interface{}, target interface{}) bool removeDirectedEdge(source interface{}, target interface{}) bool } type Edge interface { Tail() Vertex Head() Vertex }
Include query string in URL as cache ID.
var Data = require('./data'); var data = new Data(); function feedPocketPage(req, res) { res.render('feedpocket.html', { layout: 'layout', locals: { categories: data.categoryList } }); } function feedData(req, res) { data.getFeed(req.params.feedId, function (err, articles) { if (err) { res.error(err); } else { res.json(articles); } }); } function articleData(req, res) { var url = req.url.match(/http.+$/); data.getArticle(url, function (err, article) { res.json(article); }); } exports.data = data; exports.feedPocketPage = feedPocketPage; exports.feedData = feedData; exports.articleData = articleData;
var Data = require('./data'); var data = new Data(); function feedPocketPage(req, res) { res.render('feedpocket.html', { layout: 'layout', locals: { categories: data.categoryList } }); } function feedData(req, res) { data.getFeed(req.params.feedId, function (err, articles) { if (err) { res.error(err); } else { res.json(articles); } }); } function articleData(req, res) { data.getArticle(req.params[0], function (err, article) { res.json(article); }); } exports.data = data; exports.feedPocketPage = feedPocketPage; exports.feedData = feedData; exports.articleData = articleData;
Update name of callback functions
import "es6-symbol"; import "weakmap"; import svgLoader from "./loader.js"; import Icon from "./components/Icon.js"; import Sprite from "./components/Sprite.js"; import Theme from "./components/Theme.js"; var callback = function callback() { }; const icons = Icon; const initLoader = svgLoader; // loads an external SVG file as sprite. function load(loader, onFulfilled, onRejected) { if (!onRejected) { onRejected = callback; } if (typeof loader === "string") { loader = svgLoader(loader); } else if (!loader || !loader.request) { onRejected(new TypeError("Invalid Request")); } loader.onSuccess = function onSuccess(svg) { make(svg, onFulfilled, onRejected); }; loader.onFailure = function onFailure(e) { onRejected(new TypeError(e)); }; loader.send(); } function make(svg, onFulfilled, onRejected) { var theme; var autorun = false; if (!onFulfilled) { onFulfilled = callback; autorun = true; } if (!onRejected) { onRejected = callback; } try { var sprite = new Sprite(svg); theme = new Theme(sprite); onFulfilled(theme); if (autorun) { theme.render(); } } catch (e) { onRejected(e); } } export { icons, initLoader, load, make };
import "es6-symbol"; import "weakmap"; import svgLoader from "./loader.js"; import Icon from "./components/Icon.js"; import Sprite from "./components/Sprite.js"; import Theme from "./components/Theme.js"; var callback = function callback() { }; const icons = Icon; const initLoader = svgLoader; // loads an external SVG file as sprite. function load(loader, onFulfilled, onRejected) { if (!onRejected) { onRejected = callback; } if (typeof loader === "string") { loader = svgLoader(loader); } else if (!loader || !loader.request) { onRejected(new TypeError("Invalid Request")); } loader.onSuccess = function(svg) { make(svg, onFulfilled, onRejected); }; loader.onFailure = function(e) { onRejected(new TypeError(e)); }; loader.send(); } function make(svg, onFulfilled, onRejected) { var theme; var autorun = false; if (!onFulfilled) { onFulfilled = callback; autorun = true; } if (!onRejected) { onRejected = callback; } try { var sprite = new Sprite(svg); theme = new Theme(sprite); onFulfilled(theme); if (autorun) { theme.render(); } } catch (e) { onRejected(e); } } export { icons, initLoader, load, make };
Fix resolution of submit function
'use strict'; var assign = require('es5-ext/object/assign') , promisify = require('deferred').promisify , bcrypt = require('bcrypt') , dbjsCreate = require('mano/lib/utils/dbjs-form-create') , submit = require('mano/utils/save') , changePassword = require('mano-auth/controller/server/change-password').submit , dbObjects = require('mano').db.objects , genSalt = promisify(bcrypt.genSalt), hash = promisify(bcrypt.hash); // Common assign(exports, require('../user/server')); // Add User exports['user-add'] = { submit: function (data) { return hash(data['User#/password'], genSalt())(function (password) { data['User#/password'] = password; this.target = dbjsCreate(data); }.bind(this)); } }; // Edit User exports['user/[0-9][a-z0-9]+'] = { submit: function (normalizedData, data) { if (this.propertyKey) return changePassword.apply(this, arguments); return submit.apply(this, arguments); } }; // Delete User exports['user/[0-9][a-z0-9]+/delete'] = { submit: function () { dbObjects.delete(this.target); } };
'use strict'; var assign = require('es5-ext/object/assign') , promisify = require('deferred').promisify , bcrypt = require('bcrypt') , dbjsCreate = require('mano/lib/utils/dbjs-form-create') , router = require('mano/server/post-router') , changePassword = require('mano-auth/controller/server/change-password').submit , dbObjects = require('mano').db.objects , genSalt = promisify(bcrypt.genSalt), hash = promisify(bcrypt.hash) , submit = router.submit; // Common assign(exports, require('../user/server')); // Add User exports['user-add'] = { submit: function (data) { return hash(data['User#/password'], genSalt())(function (password) { data['User#/password'] = password; this.target = dbjsCreate(data); }.bind(this)); } }; // Edit User exports['user/[0-9][a-z0-9]+'] = { submit: function (normalizedData, data) { if (this.propertyKey) return changePassword.apply(this, arguments); return submit.apply(this, arguments); } }; // Delete User exports['user/[0-9][a-z0-9]+/delete'] = { submit: function () { dbObjects.delete(this.target); } };
Add integrity test for touch events
window.addEventListener('load', function(){ module('touchstart'); test('should use touchstart when touchstart is supported', function() { assert({ listener:'touchstart', receives:'touchstart' }); }); test('should use mousedown when touchstart is unsupported', function() { assert({ listener:'touchstart', receives:'mousedown' }); }); module('touchend'); test('should use touchend when touchend is supported', function() { assert({ listener:'touchend', receives:'touchend' }); }); test('should use mouseup when touchend is unsupported', function() { assert({ listener:'touchend', receives:'mouseup' }); }); module('touchmove'); test('should use touchmove when touchmove is supported', function() { assert({ listener:'touchmove', receives:'touchmove' }); }); test('should use mousemove when touchmove is unsupported', function() { assert({ listener:'touchmove', receives:'mousemove' }); }); module('tap'); test('should use tap when touch events are supported', function() { ok(false, 'not implemented'); // assert({ listener:'tap', receives:'tap' }); }); test('should use click when tap is unsupported', function() { assert({ listener:'tap', receives:'click' }); }); });
window.addEventListener('load', function(){ module('touchstart'); test('should use touchstart when touchstart is supported', function() { ok(false, 'not implemented'); // assert({ listener:'touchstart', receives:'touchstart' }); }); test('should use mousedown when touchstart is unsupported', function() { assert({ listener:'touchstart', receives:'mousedown' }); }); module('touchend'); test('should use touchend when touchend is supported', function() { ok(false, 'not implemented'); // assert({ listener:'touchend', receives:'touchend' }); }); test('should use mouseup when touchend is unsupported', function() { assert({ listener:'touchend', receives:'mouseup' }); }); module('touchmove'); test('should use touchmove when touchmove is supported', function() { ok(false, 'not implemented'); // assert({ listener:'touchmove', receives:'touchmove' }); }); test('should use mousemove when touchmove is unsupported', function() { assert({ listener:'touchmove', receives:'mousemove' }); }); module('tap'); test('should use tap when touch events are supported', function() { ok(false, 'not implemented'); // assert({ listener:'tap', receives:'tap' }); }); test('should use click when tap is unsupported', function() { assert({ listener:'tap', receives:'click' }); }); });
Reduce the verbosity of password checking on every security check.
package ca.corefacility.bioinformatics.irida.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; /** * Expired credentials should be ignored when a user is trying to change their * password. * * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca> * */ public class IgnoreExpiredCredentialsForPasswordChangeChecker implements UserDetailsChecker { private static final Logger logger = LoggerFactory .getLogger(IgnoreExpiredCredentialsForPasswordChangeChecker.class); @Override public void check(UserDetails toCheck) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (StackTraceElement frame : stack) { if (frame.getClassName().contains("UserService") && frame.getMethodName().equals("changePassword")) { logger.debug("Ignoring expired credentials because the user is trying to change their password."); return; } } logger.trace("Proceeding with checking expired credentials; user is not trying to change their password."); if (!toCheck.isCredentialsNonExpired()) { throw new CredentialsExpiredException("User credentials have exprired."); } } }
package ca.corefacility.bioinformatics.irida.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.CredentialsExpiredException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsChecker; /** * Expired credentials should be ignored when a user is trying to change their * password. * * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca> * */ public class IgnoreExpiredCredentialsForPasswordChangeChecker implements UserDetailsChecker { private static final Logger logger = LoggerFactory .getLogger(IgnoreExpiredCredentialsForPasswordChangeChecker.class); @Override public void check(UserDetails toCheck) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (StackTraceElement frame : stack) { if (frame.getClassName().contains("UserService") && frame.getMethodName().equals("changePassword")) { logger.debug("Ignoring expired credentials because the user is trying to change their password."); return; } } logger.debug("Proceeding with checking expired credentials; user is not trying to change their password."); if (!toCheck.isCredentialsNonExpired()) { throw new CredentialsExpiredException("User credentials have exprired."); } } }
Return error for invalid base
package allyourbase import ( "errors" "fmt" "math" ) func ConvertToBase(inputBase int, inputDigits []int, outputBase int) (outputDigits []int, e error) { if inputBase < 2 { return []int{}, errors.New("input base must be >= 2") } base10 := getBase10Input(inputBase, inputDigits) if base10 == 0 { return []int{0}, nil } for base10 > 0 { digit := base10 % outputBase outputDigits = append([]int{digit}, outputDigits...) base10 = base10 / outputBase } return outputDigits, nil } func getBase10Input(inputBase int, inputDigits []int) (base10Input int) { for i, digit := range reverse(inputDigits) { base10Input += powInt(inputBase, i) * digit } fmt.Printf("getBase10Input(%d, %v)=%d\n", inputBase, inputDigits, base10Input) return base10Input } func reverse(input []int) (reversed []int) { for i := len(input) - 1; i >= 0; i-- { reversed = append(reversed, input[i]) } return reversed } func powInt(x, y int) int { return int(math.Pow(float64(x), float64(y))) }
package allyourbase import ( "fmt" "math" ) func ConvertToBase(inputBase int, inputDigits []int, outputBase int) (outputDigits []int, e error) { base10 := getBase10Input(inputBase, inputDigits) if base10 == 0 { return []int{0}, nil } for base10 > 0 { digit := base10 % outputBase outputDigits = append([]int{digit}, outputDigits...) base10 = base10 / outputBase } return outputDigits, nil } func getBase10Input(inputBase int, inputDigits []int) (base10Input int) { for i, digit := range reverse(inputDigits) { base10Input += powInt(inputBase, i) * digit } fmt.Printf("getBase10Input(%d, %v)=%d\n", inputBase, inputDigits, base10Input) return base10Input } func reverse(input []int) (reversed []int) { for i := len(input) - 1; i >= 0; i-- { reversed = append(reversed, input[i]) } return reversed } func powInt(x, y int) int { return int(math.Pow(float64(x), float64(y))) }
Remove dotenv execution, create library object that contain library infos. watch if DEV MODE and UGLIFY if PROD MODE
const path = require('path') const UglifyJsPlugin = require('uglifyjs-webpack-plugin') const config = require('./package.json') const webpack = require('webpack') // Config object const library = { name: 'VueAutoscroll', target: 'umd' } const DEV = process.env.NODE_ENV === 'development'; let webpackConfig = { entry: path.resolve(__dirname, config.main), watch: DEV, output: { library: library.name, libraryTarget: library.target, path: path.resolve(__dirname, "dist"), filename: (DEV) ? 'autoscroll.js' : 'autoscroll.min.js' }, // devtool: 'source-map', module: { rules: [ { test: /\.js?$/, exclude: /(node_modules|bower_components)/, use: ['babel-loader'] } ], }, plugins: [] } if(!DEV) { webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({compress: { warnings: false }})) } module.exports = webpackConfig
const path = require('path'); const config = require('./package.json'); const webpack = require('webpack'); require('dotenv').config(); const PROD = process.env.NODE_ENV === 'production'; // let plugins = []; // PROD ? [ // plugins.push(new webpack.optimize.UglifyJsPlugin({ // compress: { warnings: false } // })) // ] : ''; module.exports = { entry: path.resolve(__dirname, config.main), output: { library: process.env.NAME, libraryTarget: process.env.TARGET, path: path.resolve(__dirname, "dist"), filename: (PROD) ? 'autoscroll.min.js' : 'autoscroll.js' }, // devtool: 'source-map', module: { rules: [ { test: /\.js?$/, exclude: /(node_modules|bower_components)/, use: ['babel-loader'] } ], } // plugins: plugins };
Remove unused import of EAgainException
package nanomsg; import nanomsg.exceptions.IOException; /** * Common interface that should implement all sockets. */ public interface ISocket { public void close(); public int getNativeSocket(); public void bind(final String dir) throws IOException; public void connect(final String dir) throws IOException; public void subscribe(final String data) throws IOException; public int sendString(final String data, final boolean blocking) throws IOException, IOException; public int sendString(final String data) throws IOException, IOException; public int sendBytes(final byte[] data, final boolean blocking) throws IOException, IOException; public int sendBytes(final byte[] data) throws IOException, IOException; public String recvString(final boolean blocking) throws IOException, IOException; public String recvString() throws IOException, IOException; public byte[] recvBytes(final boolean blocking) throws IOException, IOException; public byte[] recvBytes() throws IOException, IOException; public int getFd(final int flag) throws IOException; public void setSendTimeout(final int milis); public void setRecvTimeout(final int milis); }
package nanomsg; import nanomsg.exceptions.IOException; import nanomsg.exceptions.EAgainException; /** * Common interface that should implement all sockets. */ public interface ISocket { public void close(); public int getNativeSocket(); public void bind(final String dir) throws IOException; public void connect(final String dir) throws IOException; public void subscribe(final String data) throws IOException; public int sendString(final String data, final boolean blocking) throws IOException, IOException; public int sendString(final String data) throws IOException, IOException; public int sendBytes(final byte[] data, final boolean blocking) throws IOException, IOException; public int sendBytes(final byte[] data) throws IOException, IOException; public String recvString(final boolean blocking) throws IOException, IOException; public String recvString() throws IOException, IOException; public byte[] recvBytes(final boolean blocking) throws IOException, IOException; public byte[] recvBytes() throws IOException, IOException; public int getFd(final int flag) throws IOException; public void setSendTimeout(final int milis); public void setRecvTimeout(final int milis); }
Use latest from master as a base.
"use strict"; var path = require("path"); var clc = require("cli-color"); var _ = require("lodash"); module.exports = function (mPath, moduleIsOptional, opts) { var resolvedRequire; mPath = mPath.trim(); var runOpts = _.assign({ require: require, console: console }, opts); if (mPath.charAt(0) === ".") { resolvedRequire = path.resolve(process.cwd() + "/" + mPath); } else { resolvedRequire = mPath; } var RequiredModule; try { /*eslint global-require: 0*/ RequiredModule = runOpts.require(resolvedRequire); } catch (e) { if (e.code === "MODULE_NOT_FOUND" && moduleIsOptional !== true) { runOpts.console.error(clc.redBright("Error loading a module from user configuration.")); runOpts.console.error(clc.redBright("Cannot find module: " + resolvedRequire)); throw new Error(e); } else if (e.code === "MODULE_NOT_FOUND" && moduleIsOptional === true) { // Do nothing } else { throw new Error(e); } } return RequiredModule ? new RequiredModule() : null; };
"use strict"; var path = require("path"); var clc = require("cli-color"); var _ = require("lodash"); module.exports = function (mPath, moduleIsOptional, opts) { var resolvedRequire; mPath = mPath.trim(); var runOpts = _.assign({ require: require, console: console }, opts); if (mPath.charAt(0) === ".") { resolvedRequire = path.resolve(process.cwd() + "/" + mPath); } else { resolvedRequire = mPath; } var RequiredModule; try { /*eslint global-require: 0*/ RequiredModule = require(resolvedRequire); } catch (e) { if (e.code === "MODULE_NOT_FOUND" && moduleIsOptional !== true) { console.error(clc.redBright("Error loading a module from user configuration.")); console.error(clc.redBright("Cannot find module: " + resolvedRequire)); throw new Error(e); } else if (e.code === "MODULE_NOT_FOUND" && moduleIsOptional === true) { // Do nothing } else { throw new Error(e); } } return RequiredModule ? new RequiredModule() : null; };
Update the output when the app is running
const express = require('express') const app = express() const path = require('path') const nunjucks = require('nunjucks') // Set up App const appViews = [ path.join(__dirname, '/app/views/'), path.join(__dirname, '/app/templates/') ] nunjucks.configure(appViews, { autoescape: true, express: app, noCache: true, watch: true }) // Set views engine app.set('view engine', 'html') // Serve static content for the app from the "public" directory app.use('/public', express.static(path.join(__dirname, '/public'))) // Send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path = '/public/' next() }) // Render views/index app.get('/', function (req, res) { res.render('index') }) // Log when app is running app.listen(3000, function () { console.log('GOV.UK Frontend Alpha\n') console.log('Listening on port 3000 url: http://localhost:3000') })
const express = require('express') const app = express() const path = require('path') const nunjucks = require('nunjucks') // Set up App const appViews = [ path.join(__dirname, '/app/views/'), path.join(__dirname, '/app/templates/') ] nunjucks.configure(appViews, { autoescape: true, express: app, noCache: true, watch: true }) // Set views engine app.set('view engine', 'html') // Serve static content for the app from the "public" directory app.use('/public', express.static(path.join(__dirname, '/public'))) // Send assetPath to all views app.use(function (req, res, next) { res.locals.asset_path = '/public/' next() }) // Render views/index app.get('/', function (req, res) { res.render('index') }) // Log when app is running app.listen(3000, function () { console.log('App is running...') })
Add required skills to display.
window.onload = function onLoad() { getVolunteeringOpportunities(); }; async function getVolunteeringOpportunities() { const response = await fetch('/event-volunteering-data'); const opportunities = await response.json() for (const key in opportunities) { console.log(opportunities[key].name); console.log(opportunities[key].numSpotsLeft); $('#volunteering-opportunities') .append(getInputFieldForOpportunity( opportunities[key].name, opportunities[key].numSpotsLeft, opportunities[key].requiredSkills)); } } /** * Return a list field representing the * @param name name of opportunity * @param numSpotsLeft number of spots left for opportunity * @param requiredSkills required skills for opportunity * @return {string} */ function getInputFieldForOpportunity(name, numSpotsLeft, requiredSkills) { requiredSkillsString = requiredSkills.empty() ? "None" : requiredSkills.toString(); return `<li class="list-group-item"> <p class="card-text">Volunteer Name: ${name}</p> <p class="card-text">Volunteer Spots Left: ${numSpotsLeft}</p> <p class="card-text">Required Skills: ${requiredSkillsString}</p></li>`; }
window.onload = function onLoad() { getVolunteeringOpportunities(); }; async function getVolunteeringOpportunities() { const response = await fetch('/event-volunteering-data'); const opportunities = await response.json() console.log(opportunities); const opportunitiesArray = JSON.parse(opportunities); opportunitiesArray.forEach(function(opportunity) { console.log(opportunity); $('#volunteering-opportunities').append(getInputFieldForOpportunity(opportunity.name, opportunity.numSpotsLeft)) }); } /** * Return input string for skill input field. * @return {string} */ function getInputFieldForSkill(name, numSpotsLeft) { return `<p class="card-text">Volunteer Name: {name}</p> <p class="card-text">Volunteer Spots Left: {numSpotsLeft}</p>`; }
CHange script installation to /usr/bin/ instead of /bin
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['/usr/bin/danboorsync'], name = 'danboorsync' )
#! /usr/bin/env python3 from distutils.core import setup setup( description = 'File downloader for danbooru', author = 'Todd Gaunt', url = 'https://www.github.com/toddgaunt/danboorsync', download_url = 'https://www.github.com/toddgaunt/danboorsync', author_email = 'toddgaunt@protonmail.ch', version = '1.0', packages = ['danboorsync'], package_dir = {'danboorsync':'src'}, # Change these per distribution data_files = [('usr/share/man/man1', ['doc/danboorsync.1']), ('usr/share/licenses/imgfetch/LICENSE', ['doc/LICENSE'])], scripts = ['bin/danboorsync'], name = 'danboorsync' )
Stop logging safari-extension:// CSP blocking
var utils = require('../lib/utils'); module.exports = { ping: function(request, reply) { return reply('ok').code(200); }, status: function(appVersion) { return function(request, reply) { var info = { status: 'ok', pid: process.pid, app: process.title, host: process.env.SMF_ZONENAME, uptime: process.uptime(), version: appVersion, gitHead: require('../lib/git-head')() }; return reply(info).code(200); }; }, csplog: function(request, reply) { if (!(request.payload && request.payload['csp-report'] && /^safari-extension:/.test(request.payload['csp-report']['source-file']))) { request.logger.warn('csp report'); request.logger.warn(request.payload); } return reply('ok').code(200); } };
var utils = require('../lib/utils'); module.exports = { ping: function(request, reply) { return reply('ok').code(200); }, status: function(appVersion) { return function(request, reply) { var info = { status: 'ok', pid: process.pid, app: process.title, host: process.env.SMF_ZONENAME, uptime: process.uptime(), version: appVersion, gitHead: require('../lib/git-head')() }; return reply(info).code(200); }; }, csplog: function(request, reply) { request.logger.warn('csp report'); request.logger.warn(request.payload); return reply('ok').code(200); } };
Correct path for Spot2 service provider
<?php use App\Application; // Create new app $app = new Application(); // Core silex providers $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\RoutingServiceProvider()); $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\HttpFragmentServiceProvider()); $app->register(new Silex\Provider\MonologServiceProvider(), [ 'monolog.logfile' => __DIR__ . '/../../var/log/application.log' ]); // Twig $app->register(new Silex\Provider\TwigServiceProvider(), [ 'twig.path' => __DIR__ . '/../views' ]); // Controller annotations $app->register(new DDesrosiers\SilexAnnotations\AnnotationServiceProvider(), array( 'annot.cache' => new Doctrine\Common\Cache\FilesystemCache( __DIR__ . '/../../var/cache/annotations' ), 'annot.controllerDir' => __DIR__ . '/../../src/Controller', 'annot.controllerNamespace' => 'App\\Controller\\' )); // Spot2 $app->register(new Ronanchilvers\Silex\Spot2\Provider\Spot2ServiceProvider(), [ 'spot2.connections' => [ 'default' => 'sqlite://' . __DIR__ . '/../../var/data/database.sqlite' ] ]); return $app;
<?php use App\Application; // Create new app $app = new Application(); // Core silex providers $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\RoutingServiceProvider()); $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\HttpFragmentServiceProvider()); $app->register(new Silex\Provider\MonologServiceProvider(), [ 'monolog.logfile' => __DIR__ . '/../../var/log/application.log' ]); // Twig $app->register(new Silex\Provider\TwigServiceProvider(), [ 'twig.path' => __DIR__ . '/../views' ]); // Controller annotations $app->register(new DDesrosiers\SilexAnnotations\AnnotationServiceProvider(), array( 'annot.cache' => new Doctrine\Common\Cache\FilesystemCache( __DIR__ . '/../../var/cache/annotations' ), 'annot.controllerDir' => __DIR__ . '/../../src/Controller', 'annot.controllerNamespace' => 'App\\Controller\\' )); // Spot2 // $app->register(new \Ronanchilvers\Silex\Provider\Spot2ServiceProvider(), [ // 'spot2.connections' => [ // 'default' => 'sqlite://' . __DIR__ . '/../../var/data/database.sqlite' // ] // ]); return $app;
Adjust url from custom baselayer in OSM
PluginsAPI.Map.addActionButton(function(options){ if (options.tiles.length > 0){ // TODO: pick the topmost layer instead // of the first on the list, to support // maps that display multiple tasks. var tile = options.tiles[0]; var url = window.location.protocol + "//" + window.location.host + tile.url + "tiles/{zoom}/{x}/{y}.png"; return React.createElement("button", { type: "button", className: "btn btn-sm btn-secondary", onClick: function(){ var mapLocation = options.map.getZoom() + "/" + options.map.getCenter().lat + "/" + options.map.getCenter().lng; window.location.href = "https://www.openstreetmap.org/edit?editor=id#map=" + mapLocation + "&background=custom:" + url; } }, React.createElement("i", {className: "far fa-map"}, ""), " OSM Digitize"); } });
PluginsAPI.Map.addActionButton(function(options){ if (options.tiles.length > 0){ // TODO: pick the topmost layer instead // of the first on the list, to support // maps that display multiple tasks. var tile = options.tiles[0]; var url = window.location.protocol + "//" + window.location.host + tile.url.replace(/tiles\.json$/, "tiles/{zoom}/{x}/{ty}.png"); return React.createElement("button", { type: "button", className: "btn btn-sm btn-secondary", onClick: function(){ var mapLocation = options.map.getZoom() + "/" + options.map.getCenter().lat + "/" + options.map.getCenter().lng; window.location.href = "https://www.openstreetmap.org/edit?editor=id#map=" + mapLocation + "&background=custom:" + url; } }, React.createElement("i", {className: "far fa-map"}, ""), " OSM Digitize"); } });
[FIX] mrp_subcontracting: Allow to select any type of subcontracting product
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## from openerp import models, fields class MrpRoutingWorkcenter(models.Model): _inherit = 'mrp.routing.workcenter' external = fields.Boolean('External', help="Is Subcontract Operation") semifinished_id = fields.Many2one( comodel_name='product.product', string='Semifinished Subcontracting') picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type', domain=[('code', '=', 'outgoing')])
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # ############################################################################## from openerp import models, fields class MrpRoutingWorkcenter(models.Model): _inherit = 'mrp.routing.workcenter' external = fields.Boolean('External', help="Is Subcontract Operation") semifinished_id = fields.Many2one( 'product.product', 'Semifinished Subcontracting', domain=[('type', '=', 'product'), ]) picking_type_id = fields.Many2one('stock.picking.type', 'Picking Type', domain=[('code', '=', 'outgoing')])
Build app before running bozon test with no arguments
#! /usr/bin/env node var path = require('path') var program = require('commander') var bozon = require('../bozon') var json = require('../../package.json') program .version(json.version) program .command('new <name>') .description('Generate scaffold for new Electron application') .action(function (name, options) { var Generator = require('./generator') new Generator(name, options).generate() }) program .command('start') .description('Compile and run application') .action(function () { bozon.runGulp(['start']) }) program .command('test [spec]') .description('Run tests from spec/ directory') .action(function (spec) { if (!spec) { spec = bozon.specPath() } if (spec.match(/spec\/features/) || spec.match(/spec\/?$/)) { bozon.runGulp(['package:test']) } bozon.runMocha(['--recursive', spec]) }) program .command('clear') .description('Clear builds and releases directories') .action(function () { bozon.runGulp(['clear']) }) program .command('package') .description('Build and Package applications for platforms defined in package.json') .action(function () { bozon.runGulp(['package']) }) program.parse(process.argv)
#! /usr/bin/env node var path = require('path') var program = require('commander') var bozon = require('../bozon') var json = require('../../package.json') program .version(json.version) program .command('new <name>') .description('Generate scaffold for new Electron application') .action(function (name, options) { var Generator = require('./generator') new Generator(name, options).generate() }) program .command('start') .description('Compile and run application') .action(function () { bozon.runGulp(['start']) }) program .command('test [spec]') .description('Run tests from spec/ directory') .action(function (spec) { if (!spec) { spec = bozon.specPath() } if (spec.match(/spec\/features/)) { bozon.runGulp(['package:test']) } bozon.runMocha(['--recursive', spec]) }) program .command('clear') .description('Clear builds and releases directories') .action(function () { bozon.runGulp(['clear']) }) program .command('package') .description('Build and Package applications for platforms defined in package.json') .action(function () { bozon.runGulp(['package']) }) program.parse(process.argv)
Fix tree builder without a root node deprecation in Symfony/Config 4.2+
<?php namespace BW\ActiveMenuItemBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('bw_active_menu_item'); if (\method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->getRootNode(); } else { // BC layer for symfony/config 4.1 and older $rootNode = $treeBuilder->root('bw_active_menu_item'); } return $treeBuilder; } }
<?php namespace BW\ActiveMenuItemBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('bw_active_menu_item'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
Save stocks when prices change
(function(exports) { const randInt = (min, max) => { const range = max - min; return Math.round( min + Math.random() * range ); }; function generateStocks({minPrice, maxPrice}) { const symbols = [ 'Amazon', 'Google', 'Facebook', 'Microsoft', 'Facebook', 'McDonald\'s', 'ExxonMobil' ].sort(); const stocks = symbols.map(symbol => new Stock({ symbol, price: randInt(minPrice, maxPrice) }) ); return stocks; } function StockFactory() { let stocks = Db.get('stocks'); if (typeof stocks !== 'object' || stocks === null) { stocks = generateStocks({ minPrice: 100, maxPrice: 1000 }); } let pricesChanged = false; stocks.forEach(stock => { if (stock.shouldUpdatePrice()) { stock.updatePrice(); pricesChanged = true; } }); if (pricesChanged) { Db.save('stocks', stocks); } return stocks; } exports.StockFactory = StockFactory; })(window);
(function(exports) { const randInt = (min, max) => { const range = max - min; return Math.round( min + Math.random() * range ); }; function generateStocks({minPrice, maxPrice}) { const symbols = [ 'Amazon', 'Google', 'Facebook', 'Microsoft', 'Facebook', 'McDonald\'s', 'ExxonMobil' ].sort(); const stocks = symbols.map(symbol => new Stock({ symbol, price: randInt(minPrice, maxPrice) }) ); return stocks; } function StockFactory() { let stocks = Db.get('stocks'); if (typeof stocks !== 'object' || stocks === null) { stocks = generateStocks({ minPrice: 100, maxPrice: 1000 }); } stocks.forEach(stock => { if (stock.shouldUpdatePrice()) { stock.updatePrice(); } }); return stocks; } exports.StockFactory = StockFactory; })(window);
Use simpler syntax for webpack CSS loaders
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname }, { test: /\.css$/, loaders: ['style', 'css'] } ] } }
var path = require('path'); var webpack = require('webpack'); module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin() ], module: { loaders: [ { test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname }, { test: /\.css$/, loader: 'style.css?modules&localIdentName=[name]---[local]---[hash:base64:5]' } ] } }
Refresh annotation using annotations command
<?php declare(strict_types=1); namespace ApiClients\Client\Travis\Resource\Async; use ApiClients\Client\Travis\CommandBus\Command\AnnotationsCommand; use ApiClients\Client\Travis\Resource\Annotation as BaseAnnotation; use ApiClients\Client\Travis\Resource\AnnotationInterface; use React\Promise\PromiseInterface; use Rx\React\Promise; use function ApiClients\Tools\Rx\unwrapObservableFromPromise; use function React\Promise\reject; use function React\Promise\resolve; class Annotation extends BaseAnnotation { /** * @return PromiseInterface */ public function refresh() : PromiseInterface { return Promise::fromObservable(unwrapObservableFromPromise($this->handleCommand( new AnnotationsCommand($this->jobId()) ))->filter(function (AnnotationInterface $annotation) { return $this->id() === $annotation->id(); })); } }
<?php declare(strict_types=1); namespace ApiClients\Client\Travis\Resource\Async; use ApiClients\Foundation\Hydrator\CommandBus\Command\HydrateCommand; use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand; use React\Promise\PromiseInterface; use ApiClients\Client\Travis\Resource\Annotation as BaseAnnotation; use function React\Promise\reject; use function React\Promise\resolve; class Annotation extends BaseAnnotation { /** * @return PromiseInterface */ public function refresh() : PromiseInterface { return $this->handleCommand( new SimpleRequestCommand('jobs/' . $this->jobId() . '/annotations') )->then(function ($json) { foreach ($json['annotations'] as $annotation) { if ($annotation['id'] != $this->id()) { continue; } return resolve($this->handleCommand(new HydrateCommand('Annotation', $annotation))); } return reject(); }); } }
Support spring loaded for remote process.
package org.jetbrains.plugins.groovy.springloaded; import com.intellij.debugger.PositionManager; import com.intellij.debugger.PositionManagerFactory; import com.intellij.debugger.engine.DebugProcess; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.psi.JavaPsiFacade; /** * Factory for position manager to debug classes reloaded by com.springsource.springloaded * @author Sergey Evdokimov */ public class SpringLoadedPositionManagerFactory extends PositionManagerFactory { @Override public PositionManager createPositionManager(final DebugProcess process) { AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock(); try { JavaPsiFacade facade = JavaPsiFacade.getInstance(process.getProject()); if (facade.findPackage("com.springsource.loaded") != null || facade.findPackage("org.springsource.loaded") != null) { return new SpringLoadedPositionManager(process); } } finally { accessToken.finish(); } try { // Check spring loaded for remote process if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0 || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) { return new SpringLoadedPositionManager(process); } } catch (Exception ignored) { // Some problem with virtual machine. } return null; } }
package org.jetbrains.plugins.groovy.springloaded; import com.intellij.debugger.PositionManager; import com.intellij.debugger.PositionManagerFactory; import com.intellij.debugger.engine.DebugProcess; /** * Factory for position manager to debug classes reloaded by com.springsource.springloaded * @author Sergey Evdokimov */ public class SpringLoadedPositionManagerFactory extends PositionManagerFactory { @Override public PositionManager createPositionManager(final DebugProcess process) { try { if (process.getVirtualMachineProxy().classesByName("com.springsource.loaded.agent.SpringLoadedAgent").size() > 0 || process.getVirtualMachineProxy().classesByName("org.springsource.loaded.agent.SpringLoadedAgent").size() > 0) { return new SpringLoadedPositionManager(process); } } catch (Exception ignored) { // Some problem with virtual machine. } return null; } }
Update up to changes in es5-ext
'use strict'; var copy = require('es5-ext/lib/List/copy') , curry = require('es5-ext/lib/Function/curry').call , merge = require('es5-ext/lib/Object/merge').call , ee = require('event-emitter'); var o = ee(exports = { init: function () { this.msg = []; this.passed = []; this.errored = []; this.failed = []; this.started = new Date; return this; }, in: function (msg) { this.msg.push(msg); }, out: function () { this.msg.pop(); }, log: function (type, data) { var o = { type: type, time: new Date, data: data, msg: copy(this.msg) }; this.push(o); this[type + 'ed'].push(o); this.emit('data', o); }, end: function () { this.emit('end'); } }); o.error = curry(o.log, 'error'); o.pass = curry(o.log, 'pass'); o.fail = curry(o.log, 'fail'); module.exports = function () { return merge([], o).init(); };
'use strict'; var clone = require('es5-ext/lib/Array/clone').call , curry = require('es5-ext/lib/Function/curry').call , merge = require('es5-ext/lib/Object/merge').call , ee = require('event-emitter'); var o = ee(exports = { init: function () { this.msg = []; this.passed = []; this.errored = []; this.failed = []; this.started = new Date; return this; }, in: function (msg) { this.msg.push(msg); }, out: function () { this.msg.pop(); }, log: function (type, data) { var o = { type: type, time: new Date, data: data, msg: clone(this.msg) }; this.push(o); this[type + 'ed'].push(o); this.emit('data', o); }, end: function () { this.emit('end'); } }); o.error = curry(o.log, 'error'); o.pass = curry(o.log, 'pass'); o.fail = curry(o.log, 'fail'); module.exports = function () { return merge([], o).init(); };
Hide search and delegate options
// custom mods document.addEventListener("DOMContentLoaded", function(event) { // hide email right/sharing menu entries (as they do not work with some imap servers) var hideElements = [ 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(2)', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-divider[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*="account.id"]', 'md-dialog > md-dialog-content > div > md-autocomplete[md-selected-item-change="acl.addUser(user)"]', 'md-dialog > md-dialog-content > div > md-icon', ]; var css = hideElements.join(', ') + ' { display: none !important; }\n'; css += 'input[ng-model="$AccountDialogController.account.identities[0].email"] { pointer-events: none; tabindex: -1; color: rgba(0,0,0,0.38);}' // insert styles var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet){ style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); });
// custom mods document.addEventListener("DOMContentLoaded", function(event) { // hide email right/sharing menu entries (as they do not work with some imap servers) var hideElements = [ 'body > main > md-sidenav > md-content > section > md-list > md-list-item > div > div.md-secondary-container > button:nth-child(1)', '.md-open-menu-container > md-menu-content > md-menu-item[ng-show*=additional]', '.md-open-menu-container > md-menu-content > md-menu-divider[ng-show*=additional]', ]; var css = hideElements.join(', ') + ' { display: none !important; }\n'; css += 'input[ng-model="$AccountDialogController.account.identities[0].email"] { pointer-events: none; tabindex: -1; color: rgba(0,0,0,0.38);}' // insert styles var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet){ style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); });
Test that Functional Interfaces has only one declared method
package es.sandbox.spikes.java8.interfaces; import es.sandbox.spikes.java8.InvocationSpy; import org.junit.Before; import org.junit.Test; import java.lang.reflect.Method; import static es.sandbox.spikes.java8.FunctionalInterfaceCaller.call; import static es.sandbox.spikes.java8.InvocationSpy.spy; import static org.assertj.core.api.Assertions.assertThat; /** * Created by jeslopalo on 30/12/15. */ public class FunctionalInterfaceSpecs { private InvocationSpy spy; @Before public void setup() { this.spy = spy(); } @Test public void has_only_one_declared_method() { final Method[] methods = SimpleFunctionalInterface.class.getDeclaredMethods(); assertThat(methods).hasSize(1); } @Test public void when_is_used_in_a_lambda_it_invokes_the_unique_declared_method() { call(() -> this.spy.invocation()); assertThat(this.spy.invoked()).isTrue(); } }
package es.sandbox.spikes.java8.interfaces; import es.sandbox.spikes.java8.InvocationSpy; import org.junit.Before; import org.junit.Test; import static es.sandbox.spikes.java8.FunctionalInterfaceCaller.call; import static es.sandbox.spikes.java8.InvocationSpy.spy; import static org.assertj.core.api.Assertions.assertThat; /** * Created by jeslopalo on 30/12/15. */ public class FunctionalInterfaceSpecs { private InvocationSpy spy; @Before public void setup() { this.spy = spy(); } @Test public void has_one_callable_method() { call(() -> this.spy.invocation()); assertThat(this.spy.invoked()).isTrue(); } }
Change the return type to boolean
''' prime_test(n) returns a True if n is a prime number else it returns False ''' def prime_test(n): if n <= 1: return False if n==2 or n==3: return True if n%2==0 or n%3==0: return False j = 5 while(j*j <= n): if n%(j)==0 or n%(j+2)==0: return False j += 6 return True def prime_test(n): # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: #print(num,"is not a prime number") #print(i,"times",num//i,"is",num) return False break else: #print(num,"is a prime number") return True # if input number is less than # or equal to 1, it is not prime else: #print(num,"is not a prime number") return False
''' prime_test(n) returns a True if n is a prime number else it returns False ''' def prime_test(n): if n <= 1: return False if n==2 or n==3: return True if n%2==0 or n%3==0: return False j = 5 while(j*j <= n): if n%(j)==0 or n%(j+2)==0: return False j += 6 return True def prime_test(n): # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number")
Make sparse / complete more distinguishable
package org.jusecase.properties.ui; import org.jusecase.properties.entities.Key; import org.jusecase.properties.entities.KeyPopulation; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map; public class KeyListCellRenderer extends DefaultListCellRenderer { Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>(); public KeyListCellRenderer() { backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(231, 211, 186)); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Key key = (Key) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (!isSelected) { Color color = backgroundColorForPopulation.get(key.getPopulation()); if (color != null) { label.setBackground(color); } } return label; } }
package org.jusecase.properties.ui; import org.jusecase.properties.entities.Key; import org.jusecase.properties.entities.KeyPopulation; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map; public class KeyListCellRenderer extends DefaultListCellRenderer { Map<KeyPopulation, Color> backgroundColorForPopulation = new HashMap<>(); public KeyListCellRenderer() { backgroundColorForPopulation.put(KeyPopulation.Complete, new Color(240, 255, 230)); backgroundColorForPopulation.put(KeyPopulation.Sparse, new Color(255, 251, 230)); } @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Key key = (Key) value; JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (!isSelected) { Color color = backgroundColorForPopulation.get(key.getPopulation()); if (color != null) { label.setBackground(color); } } return label; } }
Add pid in log statement
package in.dream_lab.goffish.giraph.examples; import in.dream_lab.goffish.api.*; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import java.io.IOException; import java.util.LinkedList; /** * Created by anirudh on 08/03/17. */ public class GiraphSandbox extends AbstractSubgraphComputation<NullWritable, DoubleWritable, DoubleWritable, BytesWritable, LongWritable, LongWritable, LongWritable> { @Override public void compute(Iterable<IMessage<LongWritable,BytesWritable>> subgraphMessages) throws IOException { ISubgraph<NullWritable, DoubleWritable, DoubleWritable, LongWritable, LongWritable, LongWritable> subgraph = getSubgraph(); for (IVertex subgraphVertex : subgraph.getLocalVertices()) { System.out.println("Vertex: " + subgraphVertex.getVertexId()); Iterable<IEdge> outEdges = subgraphVertex.getOutEdges(); for (IEdge subgraphEdge : outEdges) { System.out.println("Edges: " + subgraphEdge.getSinkVertexId()); } } System.out.println("Printing remote"); for (IRemoteVertex subgraphVertex : subgraph.getRemoteVertices()) { System.out.println("Remote Vertex: " + subgraphVertex.getVertexId() + ",RSID:" + subgraphVertex.getSubgraphId()); } voteToHalt(); } }
package in.dream_lab.goffish.giraph.examples; import in.dream_lab.goffish.api.*; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import java.io.IOException; import java.util.LinkedList; /** * Created by anirudh on 08/03/17. */ public class GiraphSandbox extends AbstractSubgraphComputation<NullWritable, DoubleWritable, DoubleWritable, BytesWritable, LongWritable, LongWritable, LongWritable> { @Override public void compute(Iterable<IMessage<LongWritable,BytesWritable>> subgraphMessages) throws IOException { ISubgraph<NullWritable, DoubleWritable, DoubleWritable, LongWritable, LongWritable, LongWritable> subgraph = getSubgraph(); for (IVertex subgraphVertex : subgraph.getLocalVertices()) { System.out.println("Vertex: " + subgraphVertex.getVertexId()); Iterable<IEdge> outEdges = subgraphVertex.getOutEdges(); for (IEdge subgraphEdge : outEdges) { System.out.println("Edges: " + subgraphEdge.getSinkVertexId()); } } System.out.println("Printing remote"); for (IVertex subgraphVertex : subgraph.getRemoteVertices()) { System.out.println("Remote Vertex: " + subgraphVertex.getVertexId()); } voteToHalt(); } }
Fix the ‘arr1 is not defined’ error
/** * IsEqual * * @param {object} obj1 * @param {object} obj2 */ var isEqual = function(obj1, obj2) { /** * Arrays */ if (isArray(obj1, obj2)) { if (obj1.length !== obj2.length) { return false; } return every(obj1, function(value, index, context) { return obj2[index] === value; }); } /** * Objects */ if (isObject(obj1, obj2)) { var keys1 = keys(obj1), keys2 = keys(obj2); if (!isEqual(keys1, keys2)) { return false; } for (key in obj1) { if (!obj2[key] || obj1[key] !== obj2[key]) { return false; } } return true; } return false; };
/** * IsEqual * * @param {object} obj1 * @param {object} obj2 */ var isEqual = function(obj1, obj2) { /** * Arrays */ if (isArray(obj1, obj2)) { if (arr1.length !== arr2.length) { return false; } return every(arr1, function(value, index, context) { return arr2[index] === value; }); } /** * Objects */ if (isObject(obj1, obj2)) { var keys1 = keys(obj1), keys2 = keys(obj2); if (!isEqual(keys1, keys2)) { return false; } for (key in obj1) { if (!obj2[key] || obj1[key] !== obj2[key]) { return false; } } return true; } return false; };
Format simple timers when they are printed.
package org.yi.happy.metric; /** * I am a simple timer. */ public class SimpleTimer { /** * create started. */ public SimpleTimer() { startTime = System.currentTimeMillis(); stopTime = startTime - 1; } /** * when the timer started. */ private long startTime; /** * when the timer was stopped. (initially: startTime - 1) */ private long stopTime; /** * stop the timer. A timer may only be stopped once. */ public void stop() { if (stopTime >= startTime) { throw new IllegalStateException("stop may only be called once"); } stopTime = System.currentTimeMillis(); } /** * get the time on the timer. if the timer has not been stopped get the time * from when it was started to now. if the timer has been stopped get the * time between when it was started and when it was stopped. * * @return the elapsed time in ms */ public long getTime() { if (stopTime < startTime) { return System.currentTimeMillis() - startTime; } return stopTime - startTime; } @Override public String toString() { return "[" + getClass().getName() + ": time=" + getTime() + " ms]"; } }
package org.yi.happy.metric; /** * I am a simple timer. */ public class SimpleTimer { /** * create started. */ public SimpleTimer() { startTime = System.currentTimeMillis(); stopTime = startTime - 1; } /** * when the timer started. */ private long startTime; /** * when the timer was stopped. (initially: startTime - 1) */ private long stopTime; /** * stop the timer. A timer may only be stopped once. */ public void stop() { if (stopTime >= startTime) { throw new IllegalStateException("stop may only be called once"); } stopTime = System.currentTimeMillis(); } /** * get the time on the timer. if the timer has not been stopped get the time * from when it was started to now. if the timer has been stopped get the * time between when it was started and when it was stopped. * * @return the elapsed time in ms */ public long getTime() { if (stopTime < startTime) { return System.currentTimeMillis() - startTime; } return stopTime - startTime; } }
Use new (?) repository transferred hook.
import json import uuid from flask_hookserver import Hooks from .db import redis from .members.models import User from .projects.tasks import update_project_by_hook from .tasks import spinach hooks = Hooks() @hooks.hook("ping") def ping(data, guid): return "pong" @hooks.hook("membership") def membership(data, guid): if data["scope"] != "team": return member = User.query.filter_by(id=data["member"]["id"]).first() if member is None: return if data["action"] == "added": member.is_member = True member.save() elif data["action"] == "removed": member.is_member = False member.save() return "Thanks" @hooks.hook("repository") def repository(data, guid): # only if the action is to add a member and if there is repo data if data.get("action") == "transferred" and "repository" in data: hook_id = f"repo-added-{uuid.uuid4()}" redis.setex( hook_id, 60 * 5, json.dumps(data) # expire the hook hash in 5 minutes ) spinach.schedule(update_project_by_hook, hook_id) return hook_id return "Thanks"
import json import uuid from flask_hookserver import Hooks from .db import redis from .members.models import User from .projects.tasks import update_project_by_hook from .tasks import spinach hooks = Hooks() @hooks.hook("ping") def ping(data, guid): return "pong" @hooks.hook("membership") def membership(data, guid): if data["scope"] != "team": return member = User.query.filter_by(id=data["member"]["id"]).first() if member is None: return if data["action"] == "added": member.is_member = True member.save() elif data["action"] == "removed": member.is_member = False member.save() return "Thanks" @hooks.hook("member") def member(data, guid): # only if the action is to add a member and if there is repo data if data.get("action") == "added" and "repository" in data: hook_id = f"repo-added-{uuid.uuid4()}" redis.setex( hook_id, 60 * 5, json.dumps(data) # expire the hook hash in 5 minutes ) spinach.schedule(update_project_by_hook, hook_id) return hook_id return "Thanks"
git: Put prod back on the list of branches to send notices about. (imported from commit e608d7050b4e68045b03341dc41e8654e45a3af3)
# Humbug Inc's internal git plugin configuration. # The plugin and example config are under api/integrations/ # Leaving all the instructions out of this file to avoid having to # sync them as we update the comments. HUMBUG_USER = "humbug+commits@humbughq.com" HUMBUG_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # commit_notice_destination() lets you customize where commit notices # are sent to. # # It takes the following arguments: # * repo = the name of the git repository # * branch = the name of the branch that was pushed to # * commit = the commit id # # Returns a dictionary encoding the stream and subject to send the # notification to (or None to send no notification, e.g. for ). # # The default code below will send every commit pushed to "master" to # * stream "commits" # * subject "deploy => master" (using a pretty unicode right arrow) # And similarly for branch "test-post-receive" (for use when testing). def commit_notice_destination(repo, branch, commit): if branch in ["master", "prod", "post-receive-test"]: return dict(stream = "commits", subject = u"deploy \u21D2 %s" % (branch,)) # Return None for cases where you don't want a notice sent return None HUMBUG_API_PATH = "/home/humbug/humbug/api" HUMBUG_SITE = "https://staging.humbughq.com"
# Humbug Inc's internal git plugin configuration. # The plugin and example config are under api/integrations/ # Leaving all the instructions out of this file to avoid having to # sync them as we update the comments. HUMBUG_USER = "humbug+commits@humbughq.com" HUMBUG_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # commit_notice_destination() lets you customize where commit notices # are sent to. # # It takes the following arguments: # * repo = the name of the git repository # * branch = the name of the branch that was pushed to # * commit = the commit id # # Returns a dictionary encoding the stream and subject to send the # notification to (or None to send no notification, e.g. for ). # # The default code below will send every commit pushed to "master" to # * stream "commits" # * subject "deploy => master" (using a pretty unicode right arrow) # And similarly for branch "test-post-receive" (for use when testing). def commit_notice_destination(repo, branch, commit): if branch in ["master", "post-receive-test"]: return dict(stream = "commits", subject = u"deploy \u21D2 %s" % (branch,)) # Return None for cases where you don't want a notice sent return None HUMBUG_API_PATH = "/home/humbug/humbug/api" HUMBUG_SITE = "https://staging.humbughq.com"
Add docs to server init
// {{{ Express HTTP server setup let express = require('express'); let less = require('less-middleware'); let app = express(); // Set up EJS views app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); // Set LESS for CSS pre-processing app.use(less(__dirname + '/static')); // Set up static directory app.use(express.static(__dirname + '/static')); const port = 3000; // Routers let index = require('./routes/index'); app.use('/', index); // }}} // {{{ MongoDB database client setup let mongo = require('mongodb').MongoClient; let config = require('config'); let mConf = config.get('mongo'); let url = 'mongodb://' + mConf.host + ':' + mConf.port + '/' + mConf.database; console.log(url); mongo.connect(url, function(err, db) { if (err) { console.log('Unable to connect to database. Exiting...'); exit(1); } else { console.log('Successfully connected to database'); } }); // }}} app.listen(port); // Log to console console.log('Pigeon has started.'); console.log(__dirname); console.log('Listening for connections on port ' + port + '.');
// {{{ Express HTTP server setup let express = require('express'); let less = require('less-middleware'); let app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.use(less(__dirname + '/static')); app.use(express.static(__dirname + '/static')); const port = 3000; // Routers let index = require('./routes/index'); app.use('/', index); // }}} // {{{ MongoDB database client setup let mongo = require('mongodb').MongoClient; let config = require('config'); let mConf = config.get('mongo'); let url = 'mongodb://' + mConf.host + ':' + mConf.port + '/' + mConf.database; console.log(url); mongo.connect(url, function(err, db) { if (err) { console.log('Unable to connect to database. Exiting...'); exit(1); } else { console.log('Successfully connected to database'); } }); // }}} app.listen(port); // Log to console console.log('Pigeon has started.'); console.log(__dirname); console.log('Listening for connections on port ' + port + '.');
Change geometry name in the basic example
const createContext = require('pex-context') //const createRenderer = require('pex-renderer') const createRenderer = require('../..') const createSphere = require('primitive-sphere') const ctx = createContext({ width: 800, height: 600 }) const renderer = createRenderer({ ctx: ctx }) const camera = renderer.entity([ renderer.transform({ position: [0, 0, 3] }), renderer.camera({ fov: Math.PI / 2, aspect: ctx.gl.drawingBufferWidth / ctx.gl.drawingBufferHeight, near: 0.1, far: 100 }) ]) renderer.add(camera) const geom = renderer.entity([ renderer.transform({ position: [0, 0, 0] }), renderer.geometry(createSphere(1)), renderer.material({ baseColor: [1, 0, 0, 1] }) ]) renderer.add(geom) const skybox = renderer.entity([ renderer.skybox({ sunPosition: [1, 1, 1] }) ]) renderer.add(skybox) const reflectionProbe = renderer.entity([ renderer.reflectionProbe() ]) renderer.add(reflectionProbe) ctx.frame(() => { renderer.draw() })
const createContext = require('pex-context') //const createRenderer = require('pex-renderer') const createRenderer = require('../..') const createSphere = require('primitive-sphere') const ctx = createContext({ width: 800, height: 600 }) const renderer = createRenderer({ ctx: ctx }) const camera = renderer.entity([ renderer.transform({ position: [0, 0, 3] }), renderer.camera({ fov: Math.PI / 2, aspect: ctx.gl.drawingBufferWidth / ctx.gl.drawingBufferHeight, near: 0.1, far: 100 }) ]) renderer.add(camera) const cube = renderer.entity([ renderer.transform({ position: [0, 0, 0] }), renderer.geometry(createSphere(1)), renderer.material({ baseColor: [1, 0, 0, 1] }) ]) renderer.add(cube) const skybox = renderer.entity([ renderer.skybox({ sunPosition: [1, 1, 1] }) ]) renderer.add(skybox) const reflectionProbe = renderer.entity([ renderer.reflectionProbe() ]) renderer.add(reflectionProbe) ctx.frame(() => { renderer.draw() })
Fix bad comma in object
/*global angular */ require.config({ shim: { 'angular': { exports: 'angular' } }, paths: { app: 'js/app', angular: './components/angular/angular' }, baseUrl: '/' }); (function() { console.time('requirejs'); require([ // application 'app', 'js/mobile-nav.js', 'js/lib/event_emitter.js', // dependencies 'angular', // 'shared/js/async_storage.js', // 1p libs // 'js/lib/date_format.js', 'js/lib/gibberish-aes.js', 'js/lib/keychain.js', // services // 'js/services/database.js', 'js/services/dates.js', 'js/services/http-cache.js', 'js/services/install.js', // controllers 'js/controllers/login.js', 'js/controllers/list.js', 'js/controllers/category.js', 'js/controllers/detail.js' ], function() { console.timeEnd('requirejs'); angular.bootstrap(document, ['app']); }); })();
/*global angular */ require.config({ shim: { 'angular': { exports: 'angular' } }, paths: { app: 'js/app', angular: './components/angular/angular' }, baseUrl: '/' }); (function() { console.time('requirejs'); require([ // application 'app', 'js/mobile-nav.js', 'js/lib/event_emitter.js', // dependencies 'angular', // 'shared/js/async_storage.js', // 1p libs // 'js/lib/date_format.js', 'js/lib/gibberish-aes.js', 'js/lib/keychain.js', // services // 'js/services/database.js', 'js/services/dates.js', 'js/services/http-cache.js', 'js/services/install.js', // controllers 'js/controllers/login.js', 'js/controllers/list.js', 'js/controllers/detail.js', 'js/controllers/category.js' ], function() { console.timeEnd('requirejs'); angular.bootstrap(document, ['app']); }); })();
Add notice on how to add custom apps for development
""" Django settings for laufpartner_server project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ from laufpartner_server.settings_global import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1b^azltf1pvzs$^p+2xlg=rot9!b%8(aj4%d4_e(xu@%!uf89u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'database.sqlite3'), } } # Additional apps, e.g. for development INSTALLED_APPS += ( #'django_extensions', )
""" Django settings for laufpartner_server project. Generated by 'django-admin startproject' using Django 1.8.1. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ from laufpartner_server.settings_global import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1b^azltf1pvzs$^p+2xlg=rot9!b%8(aj4%d4_e(xu@%!uf89u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'database.sqlite3'), } }
Update Sharing Tweet message (add emojis too :))
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018-2019, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Admin / Inc / Class */ namespace PH7; use PH7\Framework\Core\Kernel; use PH7\Framework\Url\Url; final class TweetSharing { const TWITTER_TWEET_URL = 'https://twitter.com/intent/tweet?text='; const TWITTER_TWEET_MSG = "I built my Social #DatingWebApp with #pH7CMS 😍, #DatingSoftware -> %0% \n%1% 🚀"; /** * @return string */ public static function getMessage() { $sMsg = t(self::TWITTER_TWEET_MSG, Kernel::SOFTWARE_TWITTER, Kernel::SOFTWARE_GIT_REPO_URL); return self::TWITTER_TWEET_URL . Url::encode($sMsg); } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Module / Admin / Inc / Class */ namespace PH7; use PH7\Framework\Core\Kernel; use PH7\Framework\Url\Url; final class TweetSharing { const TWITTER_TWEET_URL = 'https://twitter.com/intent/tweet?text='; const TWITTER_TWEET_MSG = "I built my social #DatingBusiness with #pH7CMS, #DatingSoftware -> %0% \n%1%"; /** * @return string */ public static function getMessage() { $sMsg = t(self::TWITTER_TWEET_MSG, Kernel::SOFTWARE_TWITTER, Kernel::SOFTWARE_GIT_REPO_URL); return self::TWITTER_TWEET_URL . Url::encode($sMsg); } }
Update how we parse svg
import path from 'path'; import fs from 'fs'; const getViewBoxDimensions = dir => file => { const fileContent = fs.readFileSync(path.join(dir, file), 'utf-8'); const matches = fileContent.match(/viewBox=\"(\d+(?:\.\d+)?) (\d+(?:\.\d+)?) (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)\"/); if ( ! matches) return; return { width: parseFloat(matches[3]), height: parseFloat(matches[4]) } }; const walkSync = function(dir) { const isDirectory = dir => file => fs.statSync(path.join(dir, file)).isDirectory(); const filter = dir => file => file.match(/\.svg$/) || isDirectory(dir)(file); return fs.readdirSync(dir).filter(filter(dir)).map(function(file) { if (isDirectory(dir)(file)) { return { isFile: false, id: file, colors: walkSync(path.join(dir, file)) }; } else { return { isFile: true, id: file, style: getViewBoxDimensions(dir)(file) }; } }); }; export const getFiles = () => { return walkSync('public/svg/'); };
import path from 'path'; import fs from 'fs'; const getViewBoxDimensions = dir => file => { const fileContent = fs.readFileSync(path.join(dir, file), 'utf-8'); const matches = fileContent.match(/viewBox=\"0 0 (\d+(?:\.\d+)?) (\d+(?:\.\d+)?)\"/); if ( ! matches) return; return { width: parseFloat(matches[1]), height: parseFloat(matches[2]) } }; const walkSync = function(dir) { const isDirectory = dir => file => fs.statSync(path.join(dir, file)).isDirectory(); const filter = dir => file => file.match(/\.svg$/) || isDirectory(dir)(file); return fs.readdirSync(dir).filter(filter(dir)).map(function(file) { if (isDirectory(dir)(file)) { return { isFile: false, id: file, colors: walkSync(path.join(dir, file)) }; } else { return { isFile: true, id: file, style: getViewBoxDimensions(dir)(file) }; } }); }; export const getFiles = () => { return walkSync('public/svg/'); };
Fix text file overflowing message below it
'use strict' import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import Highlight from '../Highlight' import { getFileExtension } from '../../utils/file-helpers' function PreviewTextFile ({ blob, filename, onLoad, ...rest }) { const [fileContent, setfileContent] = useState(null) useEffect(() => { const fileReader = new FileReader() fileReader.onload = ({ target: { result } }) => { setfileContent( <Highlight extension={getFileExtension(filename)} {...rest}> {result} </Highlight> ) } fileReader.onerror = () => { fileReader.abort() throw new Error('Unable to read file') } fileReader.readAsText(blob, 'utf-8') }, [filename]) useEffect(() => { setTimeout(onLoad, 0) }, [fileContent]) return fileContent || null } PreviewTextFile.propTypes = { blob: PropTypes.object.isRequired, filename: PropTypes.string.isRequired } export default PreviewTextFile
'use strict' import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import Highlight from '../Highlight' import { getFileExtension } from '../../utils/file-helpers' function PreviewTextFile ({ blob, filename, onLoad, ...rest }) { const [fileContent, setfileContent] = useState(null) useEffect(() => { const fileReader = new FileReader() fileReader.onload = ({ target: { result } }) => { setfileContent( <Highlight extension={getFileExtension(filename)} {...rest}> {result} </Highlight> ) onLoad() } fileReader.onerror = () => { fileReader.abort() throw new Error('Unable to read file') } fileReader.readAsText(blob, 'utf-8') }, [filename]) return fileContent || null } PreviewTextFile.propTypes = { blob: PropTypes.object.isRequired, filename: PropTypes.string.isRequired } export default PreviewTextFile
Change get_preview_image to same as other blocks (because we fix ipl to pil convert for 1-channel images)
# -*- coding: utf-8 -*- import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return self.output_ports["output_image"]._value
# -*- coding: utf-8 -*- import ipfblock import ioport import ipf.ipfblock.processing from ipf.ipftype.ipfimage3ctype import IPFImage3cType from ipf.ipftype.ipfimage1ctype import IPFImage1cType class RGB2Gray(ipfblock.IPFBlock): """ Convert 3 channel image to 1 channel gray block class """ type = "RGB2Gray" category = "Channel operations" is_abstract_block = False def __init__(self): super(RGB2Gray, self).__init__() self.input_ports["input_image"] = ioport.IPort(self, IPFImage3cType) self.output_ports["output_image"] = ioport.OPort(self, IPFImage1cType) self.processing_function = ipf.ipfblock.processing.rgb2gray def get_preview_image(self): return IPFImage3cType.convert(self.output_ports["output_image"]._value)
Add Request/Response import points for pylons. --HG-- branch : trunk
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config from pylons.controllers.util import Request from pylons.controllers.util import Response __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url', 'Request', 'Response'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
Replace call_user_func_array() with unpack syntax
<?php namespace util; use lang\reflect\InvocationHandler; use lang\Throwable; use lang\ClassCastException; /** * Lazy initializable InvokationHandler * * @test xp://net.xp_framework.unittest.util.DeferredInvokationHandlerTest */ abstract class AbstractDeferredInvokationHandler extends \lang\Object implements InvocationHandler { private $_instance= null; /** * Lazy initialization callback * * @return lang.Generic */ public abstract function initialize(); /** * Processes a method invocation on a proxy instance and returns * the result. * * @param lang.reflect.Proxy $proxy * @param string $method the method name * @param var... $args an array of arguments * @return var * @throws util.DeferredInitializationException */ public function invoke($proxy, $method, $args) { if (null === $this->_instance) { try { $this->_instance= $this->initialize(); } catch (Throwable $e) { $this->_instance= null; throw new DeferredInitializationException($method, $e); } if (!is_object($this->_instance)) { throw new DeferredInitializationException( $method, new ClassCastException('Initializer returned '.\xp::typeOf($this->_instance)) ); } } return $this->_instance->{$method}(...$args); } }
<?php namespace util; use lang\reflect\InvocationHandler; use lang\Throwable; use lang\ClassCastException; /** * Lazy initializable InvokationHandler * * @test xp://net.xp_framework.unittest.util.DeferredInvokationHandlerTest */ abstract class AbstractDeferredInvokationHandler extends \lang\Object implements InvocationHandler { private $_instance= null; /** * Lazy initialization callback * * @return lang.Generic */ public abstract function initialize(); /** * Processes a method invocation on a proxy instance and returns * the result. * * @param lang.reflect.Proxy $proxy * @param string $method the method name * @param var... $args an array of arguments * @return var * @throws util.DeferredInitializationException */ public function invoke($proxy, $method, $args) { if (null === $this->_instance) { try { $this->_instance= $this->initialize(); } catch (Throwable $e) { $this->_instance= null; throw new DeferredInitializationException($method, $e); } if (!is_object($this->_instance)) { throw new DeferredInitializationException( $method, new ClassCastException('Initializer returned '.\xp::typeOf($this->_instance)) ); } } return call_user_func_array([$this->_instance, $method], $args); } }
Fix Apollo Client instance caching on client-side
import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client" import fetch from "isomorphic-fetch" /** * @typedef {import("@apollo/client").NormalizedCacheObject} NormalizedCacheObject */ /** * @type {ApolloClient<NormalizedCacheObject>} */ let cachedClient = null const createApollo = () => new ApolloClient({ ssrMode: process.browser === false || typeof window === "undefined", link: new HttpLink({ uri: process.env.NEXT_PUBLIC_GRAPHQL, credentials: "same-origin", fetch }), cache: new InMemoryCache() }) /** * @param {Object.<string, any>} initialState */ function initializeApollo(initialState = null) { /** * @type {ApolloClient<NormalizedCacheObject>} */ const client = cachedClient ?? createApollo() if (initialState) { const oldCache = client.extract() client.cache.restore({...oldCache, ...initialState}) } // Always return a new client for SSR if (process.browser === false) { return client } // Cache client if it wasn't cached before if (!cachedClient) { cachedClient = client } return client } export default initializeApollo
import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client" import fetch from "isomorphic-fetch" /** * @typedef {import("@apollo/client").NormalizedCacheObject} NormalizedCacheObject */ /** * @type {ApolloClient<NormalizedCacheObject>} */ let cachedClient = null const createApollo = () => new ApolloClient({ ssrMode: process.browser === false || typeof window === "undefined", link: new HttpLink({ uri: process.env.NEXT_PUBLIC_GRAPHQL, credentials: "same-origin", fetch }), cache: new InMemoryCache() }) /** * @param {Object.<string, any>} initialState */ function initializeApollo(initialState = null) { /** * @type {ApolloClient<NormalizedCacheObject>} */ const client = cachedClient ?? createApollo() if (initialState) { const oldCache = client.extract() client.cache.restore({...oldCache, ...initialState}) } // Always return a new client for SSR if (process.browser === false) { return client } if (cachedClient) { cachedClient = client } return client } export default initializeApollo
Convert module code to upper case for routing
define(['underscore', 'require', 'app', 'backbone.marionette'], function (_, require, App, Marionette) { 'use strict'; var navigationItem = App.request('addNavigationItem', { name: 'Modules', icon: 'search', url: '#modules' }); return Marionette.Controller.extend({ showModules: function () { require(['../views/ModulesView'], function (ModulesView) { navigationItem.select(); App.mainRegion.show(new ModulesView()); }); }, showModule: function (id) { require(['../views/ModuleView', 'nusmods', 'common/models/ModuleModel'], function (ModuleView, NUSMods, ModuleModel) { navigationItem.select(); var modCode = id.toUpperCase(); NUSMods.getMod(modCode, _.bind(function (mod) { mod.id = modCode; var moduleModel = new ModuleModel(mod); App.mainRegion.show(new ModuleView({model: moduleModel})); }, this)); }); } }); });
define(['underscore', 'require', 'app', 'backbone.marionette'], function (_, require, App, Marionette) { 'use strict'; var navigationItem = App.request('addNavigationItem', { name: 'Modules', icon: 'search', url: '#modules' }); return Marionette.Controller.extend({ showModules: function () { require(['../views/ModulesView'], function (ModulesView) { navigationItem.select(); App.mainRegion.show(new ModulesView()); }); }, showModule: function (id) { require(['../views/ModuleView', 'nusmods', 'common/models/ModuleModel'], function (ModuleView, NUSMods, ModuleModel) { navigationItem.select(); NUSMods.getMod(id, _.bind(function (mod) { mod.id = id; var moduleModel = new ModuleModel(mod); App.mainRegion.show(new ModuleView({model: moduleModel})); }, this)); }); } }); });
Update copyright notice with MIT license
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --*/ package com.nasmlanguage; import com.intellij.openapi.util.IconLoader; import javax.swing.Icon; public class NASMIcons { public static final Icon ASM_FILE = IconLoader.getIcon("/com/nasmlanguage/icons/FileType_asm.png"); }
/*++ NASM Assembly Language Plugin Copyright (c) 2017-2018 Aidan Khoury. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --*/ package com.nasmlanguage; import com.intellij.openapi.util.IconLoader; import javax.swing.Icon; public class NASMIcons { public static final Icon ASM_FILE = IconLoader.getIcon("/com/nasmlanguage/icons/FileType_asm.png"); }
Rename base exception class; less ugly
""" Custom *xml4h* exceptions. """ class Xml4hException(Exception): """ Base exception class for all non-standard exceptions raised by *xml4h*. """ pass class FeatureUnavailableException(Xml4hException): """ User has attempted to use a feature that is available in some *xml4h* implementations/adapters, but is not available in the current one. """ pass class IncorrectArgumentTypeException(ValueError, Xml4hException): """ Richer flavour of a ValueError that describes exactly what argument types are expected. """ def __init__(self, arg, expected_types): msg = (u'Argument %s is not one of the expected types: %s' % (arg, expected_types)) super(IncorrectArgumentTypeException, self).__init__(msg)
""" Custom *xml4h* exceptions. """ class BaseXml4hException(Exception): """ Base exception class for all non-standard exceptions raised by *xml4h*. """ pass class FeatureUnavailableException(BaseXml4hException): """ User has attempted to use a feature that is available in some *xml4h* implementations/adapters, but is not available in the current one. """ pass class IncorrectArgumentTypeException(ValueError, BaseXml4hException): """ Richer flavour of a ValueError that describes exactly what argument types are expected. """ def __init__(self, arg, expected_types): msg = (u'Argument %s is not one of the expected types: %s' % (arg, expected_types)) super(IncorrectArgumentTypeException, self).__init__(msg)
Convert path to lowercase when normalizing
import re import os def normalize_path(path): """ Normalizes a path: * Removes extra and trailing slashes * Converts special characters to underscore """ if path is None: return "" path = re.sub(r'/+', '/', path) # repeated slash path = re.sub(r'/*$', '', path) # trailing slash path = [to_slug(p) for p in path.split(os.sep)] return os.sep.join(path) # preserves leading slash def to_slug(value): """ Convert a string to a URL slug. """ value = value.lower() # Space to dashes value = re.sub(r'[\s_]+', '-', value) # Special characters value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I) # Extra dashes value = re.sub(r'\-{2,}', '-', value) value = re.sub(r'(^\-)|(\-$)', '', value) return value
import re import os def normalize_path(path): """ Normalizes a path: * Removes extra and trailing slashes * Converts special characters to underscore """ path = re.sub(r'/+', '/', path) # repeated slash path = re.sub(r'/*$', '', path) # trailing slash path = [to_slug(p) for p in path.split(os.sep)] return os.sep.join(path) # preserves leading slash def to_slug(value): """ Convert a string to a URL slug """ # Space to dashes value = re.sub(r'[\s_]+', '-', value) # Special characters value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I) # Extra dashes value = re.sub(r'\-{2,}', '-', value) value = re.sub(r'(^\-)|(\-$)', '', value) return value
Add s2TakeId properties in S2 model to match PEPS S2 definition
<?php /* * Copyright 2014 Jérôme Gasperi * * 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. */ /** * resto Sentinel-2 model to ingest GeoJSON metadata * from PEPS server at https://peps.cnes.fr/resto/api/collections/S2/search.json */ class RestoModel_S2 extends RestoModel { public $extendedProperties = array( 's2TakeId' => array( 'name' => 's2takeid', 'type' => 'TEXT' ) ); /** * Constructor */ public function __construct() { parent::__construct(); } }
<?php /* * Copyright 2014 Jérôme Gasperi * * 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. */ /** * resto Sentinel-2 model to ingest GeoJSON metadata * from PEPS server at https://peps.cnes.fr/resto/api/collections/S2/search.json */ class RestoModel_S2 extends RestoModel { public $extendedProperties = array( ); /** * Constructor */ public function __construct() { parent::__construct(); } }
Make the return link work again
# -*- coding: utf-8 -*- from selenium.webdriver.support.ui import Select from page_objects import PageObject, PageElement, MultiPageElement class SettingsPage(PageObject): return_link = PageElement(css='#sidebar-brand a') inlist_delete_confirm = PageElement(name='inlist_delete_confirm') action_delete_confirm = PageElement(name='action_delete_confirm') confirm = PageElement(name='confirm') content = PageElement(id_='content') sidebar = PageElement(id_='sidebar') sidebar_return_link = PageElement(css='#sidebar a#return') _settings_list = MultiPageElement(tag_name='label') @property def settings_list(self): return [setting.text for setting in self._settings_list] _language_elem = PageElement(name='language') @property def language(self): return Select(self._language_elem)
# -*- coding: utf-8 -*- from selenium.webdriver.support.ui import Select from page_objects import PageObject, PageElement, MultiPageElement class SettingsPage(PageObject): return_link = PageElement(css='.mui--text-title a.appbar-correct') inlist_delete_confirm = PageElement(name='inlist_delete_confirm') action_delete_confirm = PageElement(name='action_delete_confirm') confirm = PageElement(name='confirm') content = PageElement(id_='content') sidebar = PageElement(id_='sidebar') sidebar_return_link = PageElement(css='#sidebar a#return') _settings_list = MultiPageElement(tag_name='label') @property def settings_list(self): return [setting.text for setting in self._settings_list] _language_elem = PageElement(name='language') @property def language(self): return Select(self._language_elem)
Fix an issue where the latest Node-RED no longer requires RED.init() and RED.nodes.init() prior to running tests
'use strict'; import * as sinon from 'sinon'; import { assert } from 'chai'; import RED from 'node-red'; import asakusaGikenModule from '../../../../dist/nodes/local-node-asakusa_giken/asakusa_giken.js'; import * as ble from '../../../../dist/nodes/local-node-asakusa_giken/lib/ble'; RED.debug = true; RED._ = sinon.spy(); describe('asakusa_giken node', () => { describe('asakusa_giken module', () => { it('should have valid Node-RED plugin classes', done => { assert.isNotNull(RED); asakusaGikenModule(RED).then(() => { assert.isNotNull(RED.nodes.getType('BLECAST_BL').name); assert.isNotNull(RED.nodes.getType('BLECAST_BL in').name); assert.isNotNull(RED.nodes.getType('BLECAST_TM').name); assert.isNotNull(RED.nodes.getType('BLECAST_TM in').name); ble.stop(RED); done(); }).catch(err => { done(err); }); }); }); });
'use strict'; import { assert } from 'chai'; import RED from 'node-red'; import asakusaGikenModule from '../../../../dist/nodes/local-node-asakusa_giken/asakusa_giken.js'; import * as ble from '../../../../dist/nodes/local-node-asakusa_giken/lib/ble'; RED.debug = true; RED.init({ init: function() {} }, {}); RED.nodes.init(RED.settings); RED._ = function() {}; describe('asakusa_giken node', () => { describe('asakusa_giken module', () => { it('should have valid Node-RED plugin classes', done => { assert.isNotNull(RED); asakusaGikenModule(RED).then(() => { assert.isNotNull(RED.nodes.getType('BLECAST_BL').name); assert.isNotNull(RED.nodes.getType('BLECAST_BL in').name); assert.isNotNull(RED.nodes.getType('BLECAST_TM').name); assert.isNotNull(RED.nodes.getType('BLECAST_TM in').name); ble.stop(RED); done(); }).catch(err => { done(err); }); }); }); });
Use requests package instead of urllib2
import requests import json def send_gcm_message(api_key, regs_id, data, collapse_key=None): """ Send a GCM message for one or more devices, using json data api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in Google Cloud Messaging for Android) regs_id: A list with the devices which will be receiving a message data: The dict data which will be send collapse_key: A string to group messages, look at the documentation about it: http://developer.android.com/google/gcm/gcm.html#request """ values = { 'registration_ids': regs_id, 'collapse_key': collapse_key, 'data': data } values = json.dumps(values) headers = { 'UserAgent': "GCM-Server", 'Content-Type': 'application/json', 'Authorization': 'key=' + api_key, } response = requests.post(url="https://android.googleapis.com/gcm/send", data=values, headers=headers) return response.content
import urllib2 import json def send_gcm_message(api_key, regs_id, data, collapse_key=None): """ Send a GCM message for one or more devices, using json data api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in Google Cloud Messaging for Android) regs_id: A list with the devices which will be receiving a message data: The dict data which will be send collapse_key: A string to group messages, look at the documentation about it: http://developer.android.com/google/gcm/gcm.html#request """ values = { 'registration_ids': regs_id, 'collapse_key': collapse_key, 'data': data } values = json.dumps(values) headers = { 'UserAgent': "GCM-Server", 'Content-Type': 'application/json', 'Authorization': 'key=' + api_key, } request = urllib2.Request("https://android.googleapis.com/gcm/send", data=values, headers=headers) response = urllib2.urlopen(request) result = response.read() return result
Use filename based type if DetectContentType fails. DetectContentType returns text/plain for our stylesheets and javascripts. That causes chrome to ignore those files.
package blob import ( "bytes" "compress/gzip" "io" "log" "net/http" "strings" ) const ( TemplateFiles = "templates" StaticFiles = "static" ) var mimeMap = map[string]string{ "css": "text/css", "js": "text/javascript", } func GetFile(bucket string, name string) ([]byte, error) { reader := bytes.NewReader(files[bucket][name]) gz, err := gzip.NewReader(reader) if err != nil { return nil, err } var b bytes.Buffer io.Copy(&b, gz) gz.Close() return b.Bytes(), nil } type Handler struct{} func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { name := r.URL.String() if name == "" { name = "index.html" } file, err := GetFile(StaticFiles, name) if err != nil { if err != io.EOF { log.Printf("Could not get file: %s", err) } w.WriteHeader(http.StatusNotFound) return } contentType := http.DetectContentType(file) if strings.Contains(contentType, "text/plain") || strings.Contains(contentType, "application/octet-stream") { parts := strings.Split(name, ".") contentType = mimeMap[parts[len(parts)-1]] } w.Header().Set("Content-Type", contentType) w.Write(file) }
package blob import ( "bytes" "compress/gzip" "io" "log" "net/http" ) const ( TemplateFiles = "templates" StaticFiles = "static" ) func GetFile(bucket string, name string) ([]byte, error) { reader := bytes.NewReader(files[bucket][name]) gz, err := gzip.NewReader(reader) if err != nil { return nil, err } var b bytes.Buffer io.Copy(&b, gz) gz.Close() return b.Bytes(), nil } type Handler struct{} func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { name := r.URL.String() if name == "" { name = "index.html" } file, err := GetFile(StaticFiles, name) if err != nil { if err != io.EOF { log.Printf("Could not get file: %s", err) } w.WriteHeader(http.StatusNotFound) return } w.Header().Set("Content-Type", http.DetectContentType(file)) w.Write(file) }
Fix incorrect variable name in Array2d.each.
define(function() { var Array2d = function () { this._columns = {}; }; Array2d.prototype.get = function(location) { var row = this._columns[location.x]; if (row) return row[location.y]; }; Array2d.prototype.set = function (location, value) { var row = this._columns[location.x] || (this._columns[location.x] = {}); if (row[location.y]) return false; row[location.y] = value; return true; }; Array2d.prototype.each = function (callback, context) { var context = context || this; var columns; Object.keys(this._columns).forEach(function (outerKey) { columns = this._columns[outerKey]; Object.keys(columns).forEach(function (innerKey) { callback.call(context, outerKey, innerKey, columns[innerKey]); }, this); }, this); }; Array2d.prototype.clear = function (location) { var row = this._columns[location.x]; if (!row) return false; var value = row[location.y]; if (value) { delete row[location.y]; return value; } return false; }; return Array2d; });
define(function() { var Array2d = function () { this._columns = {}; }; Array2d.prototype.get = function(location) { var row = this._columns[location.x]; if (row) return row[location.y]; }; Array2d.prototype.set = function (location, value) { var row = this._columns[location.x] || (this._columns[location.x] = {}); if (row[location.y]) return false; row[location.y] = value; return true; }; Array2d.prototype.each = function (callback, context) { var context = context || this; var columns; Object.keys(this._columns).forEach(function (outerKey) { columns = this._columns[key]; Object.keys(columns).forEach(function (innerKey) { callback.call(context, outerKey, innerKey, columns[innerKey]); }, this); }, this); }; Array2d.prototype.clear = function (location) { var row = this._columns[location.x]; if (!row) return false; var value = row[location.y]; if (value) { delete row[location.y]; return value; } return false; }; return Array2d; });
Update pyyaml requirement from <5.2,>=5.1 to >=5.1,<5.3 Updates the requirements on [pyyaml](https://github.com/yaml/pyyaml) to permit the latest version. - [Release notes](https://github.com/yaml/pyyaml/releases) - [Changelog](https://github.com/yaml/pyyaml/blob/master/CHANGES) - [Commits](https://github.com/yaml/pyyaml/compare/5.1...5.2) Signed-off-by: dependabot-preview[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptescli', version='1.1.1', url='https://github.com/zooniverse/panoptes-cli', author='Adam McMaster', author_email='adam@zooniverse.org', description=( 'A command-line client for Panoptes, the API behind the Zooniverse' ), packages=find_packages(), include_package_data=True, install_requires=[ 'Click>=6.7,<7.1', 'PyYAML>=5.1,<5.3', 'panoptes-client>=1.0,<2.0', 'humanize>=0.5.1,<0.6', 'pathvalidate>=0.29.0,<0.30', ], entry_points=''' [console_scripts] panoptes=panoptes_cli.scripts.panoptes:cli ''', )
from setuptools import setup, find_packages setup( name='panoptescli', version='1.1.1', url='https://github.com/zooniverse/panoptes-cli', author='Adam McMaster', author_email='adam@zooniverse.org', description=( 'A command-line client for Panoptes, the API behind the Zooniverse' ), packages=find_packages(), include_package_data=True, install_requires=[ 'Click>=6.7,<7.1', 'PyYAML>=5.1,<5.2', 'panoptes-client>=1.0,<2.0', 'humanize>=0.5.1,<0.6', 'pathvalidate>=0.29.0,<0.30', ], entry_points=''' [console_scripts] panoptes=panoptes_cli.scripts.panoptes:cli ''', )
Fix tests for human readable numbers
import unittest from LinkMeBot.utils import get_text_from_markdown, human_readable_download_number class TestUtils(unittest.TestCase): def test_get_text_from_markdown(self): markdown = '**test** [^this](https://google.com) ~~is~~ _a_ test! https://google.com' text = 'test this is a test!' self.assertEqual(get_text_from_markdown(markdown), text) # make sure quoted text is discarded markdown = '''test > this is a test hello world ''' text = 'test\n\nhello world' self.assertEqual(get_text_from_markdown(markdown), text) def test_human_readable_download_number(self): self.assertEqual(human_readable_download_number('12'), '12') self.assertEqual(human_readable_download_number('12000'), '12 thousand') self.assertEqual(human_readable_download_number('12000000'), '12 million') self.assertEqual(human_readable_download_number('12,000,000 - 15,000,000'), '12 million') if __name__ == '__main__': unittest.main()
import unittest from LinkMeBot.utils import get_text_from_markdown, human_readable_download_number class TestUtils(unittest.TestCase): def test_get_text_from_markdown(self): markdown = '**test** [^this](https://google.com) ~~is~~ _a_ test! https://google.com' text = 'test this is a test!' self.assertEqual(get_text_from_markdown(markdown), text) # make sure quoted text is discarded markdown = '''test > this is a test hello world ''' text = 'test\n\nhello world' self.assertEqual(get_text_from_markdown(markdown), text) def test_human_readable_download_number(self): self.assertEqual(human_readable_download_number('12'), '12') self.assertEqual(human_readable_download_number('12000'), '12 Thousand') self.assertEqual(human_readable_download_number('12000000'), '12 Million') self.assertEqual(human_readable_download_number('12,000,000 - 15,000,000'), '12 Million') if __name__ == '__main__': unittest.main()
Remove chaves do redis referentes a votaçãoi
# coding: utf-8 from django.core.management.base import BaseCommand from ...models import Poll, Option import redis cache = redis.StrictRedis(host='127.0.0.1', port=6379, db=0) class Command(BaseCommand): def handle(self, *args, **kwargs): options = [1, 2, 3, 4] Poll.objects.filter(id=1).delete() Option.objects.filter(id__in=options).delete() [cache.delete('votacao:option:{}'.format(opt)) for opt in options] question = Poll.objects.create(id=1, title="Quem deve ser o vencedor") option1 = Option.objects.create(id=1, name="Mario", pool=question, votes=0) option2 = Option.objects.create(id=2, name="Luigi", pool=question, votes=0) option3 = Option.objects.create(id=3, name="Yoshi", pool=question, votes=0) option4 = Option.objects.create(id=4, name="Princesa", pool=question, votes=0) question.save() option1.save() option2.save() option3.save() option4.save() print "Pesquisa e Opções cadastradas com sucesso"
# coding: utf-8 from django.core.management.base import BaseCommand from ...models import Poll, Option class Command(BaseCommand): def handle(self, *args, **kwargs): Poll.objects.filter(id=1).delete() Option.objects.filter(id__in=[1, 2, 3, 4]).delete() question = Poll.objects.create(id=1, title="Quem deve ser o vencedor") option1 = Option.objects.create(id=1, name="Mario", pool=question, votes=0) option2 = Option.objects.create(id=2, name="Luigi", pool=question, votes=0) option3 = Option.objects.create(id=3, name="Yoshi", pool=question, votes=0) option4 = Option.objects.create(id=4, name="Princesa", pool=question, votes=0) question.save() option1.save() option2.save() option3.save() option4.save() print "Pesquisa e Opções cadastradas com sucesso"