text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Remove server-side rendering of styled-components as it doesn't work yet
import React, { Component } from 'react' import Helmet from 'react-helmet' export default function HTML (props) { const head = Helmet.rewind() return ( <html lang='en'> <head> <meta charSet='utf-8' /> {props.headComponents} {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} <meta httpEquiv='X-UA-Compatible' content='IE=edge' /> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <link rel='icon' href='/favicon.ico' type='image/x-icon' /> <link rel='apple-touch-icon' sizes='600x600' href='/icon.png' type='image/x-icon' /> </head> <body> <div id='react-mount' dangerouslySetInnerHTML={{ __html: props.body }} /> {props.postBodyComponents} </body> </html> ) }
import React, { Component } from 'react' import Helmet from 'react-helmet' import styleSheet from 'styled-components/lib/models/StyleSheet'; export default function HTML (props) { const head = Helmet.rewind() let css; if (process.env.NODE_ENV === 'production') { const styles = styleSheet.rules().map(rule => rule.cssText).join('\n'); css = <style dangerouslySetInnerHTML={{ __html: styles }} />; } return ( <html lang='en'> <head> <meta charSet='utf-8' /> {props.headComponents} {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} <meta httpEquiv='X-UA-Compatible' content='IE=edge' /> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <link rel='icon' href='/favicon.ico' type='image/x-icon' /> <link rel='apple-touch-icon' sizes='600x600' href='/icon.png' type='image/x-icon' /> {css} </head> <body> <div id='react-mount' dangerouslySetInnerHTML={{ __html: props.body }} /> { props.postBodyComponents} </body> </html> ) }
Handle classes that don't have a constructor Useful for mixins
// These are mostly a simplification of // augment.js (https://github.com/javascript/augment, MIT Licensed) and // Douglas Crockford's protoypical inheritance pattern. var noop = function() {}; /** * Usage: * var Animal = defclass({ constructor: function(name) { this.name = name || 'unnamed'; this.sleeping = false; }, sayHi: function() { console.log('Hi, my name is ' + this.name); } }); */ function defclass(prototype) { var constructor = prototype.hasOwnProperty('constructor') ? prototype.constructor : noop; constructor.prototype = prototype; return constructor; } /** * Usage: * * var Person = extend(Animal, { * constructor: function(name) { * this.super.constructor(name); * this.name = name || 'Steve'; * } * }); */ function extend(constructor, sub) { var prototype = Object.create(constructor.prototype); for (var key in sub) { prototype[key] = sub[key]; } prototype.super = constructor.prototype; return defclass(prototype); } module.exports = { defclass: defclass, extend: extend };
// These are mostly a simplification of // augment.js (https://github.com/javascript/augment, MIT Licensed) and // Douglas Crockford's protoypical inheritance pattern. /** * Usage: * * var Animal = defclass({ * constructor: function(name) { * this.name = name || 'unnamed'; * this.sleeping = false; * }, * sayHi: function() { * console.log('Hi, my name is ' + this.name); * } * }); */ function defclass(prototype) { var constructor = prototype.constructor; constructor.prototype = prototype; return constructor; } /** * Usage: * * var Person = extend(Animal, { * constructor: function(name) { * this.super.constructor(name); * this.name = name || 'Steve'; * } * }); */ function extend(constructor, sub) { var prototype = Object.create(constructor.prototype); for (var key in sub) { prototype[key] = sub[key]; } prototype.super = constructor.prototype; return defclass(prototype); } module.exports = { defclass: defclass, extend: extend };
Increase request buffer as workaround for stackoverflow in asyncio
from japronto import Application from services.articles import ArticleService from mongoengine import * article_service = ArticleService() def index(req): """ The main index """ return req.Response(text='You reached the index!') def articles(req): """ Get alll articles """ #AsyncIO buffer problem req.transport.set_write_buffer_limits(high=4096) docs = article_service.all() return req.Response(text=docs.to_json()) def keywords(req): """ Retrieve articles by keywords """ #AsyncIO buffer problem req.transport.set_write_buffer_limits(high=4096) words = req.match_dict['keywords'] docs = article_service.keywords(words) headers = {'Content-Type': 'application/json'} body = docs.to_json().encode() return req.Response(body=body, headers=headers) app = Application() app.router.add_route('/', index) app.router.add_route('/articles', articles) app.router.add_route('/articles/keywords/{keywords}', keywords) #Some bugs require us to dial to MongoDB just before server is listening host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news' connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False) app.run(debug=True)
from japronto import Application from services.articles import ArticleService from mongoengine import * article_service = ArticleService() def index(req): """ The main index """ return req.Response(text='You reached the index!') def articles(req): """ Get alll articles """ #AsyncIO buffer problem req.transport.set_write_buffer_limits=4096 docs = article_service.all() return req.Response(text=docs.to_json()) def keywords(req): """ Retrieve articles by keywords """ #AsyncIO buffer problem req.transport.set_write_buffer_limits=4096 words = req.match_dict['keywords'] docs = article_service.keywords(words) headers = {'Content-Type': 'application/json'} body = docs.to_json().encode() return req.Response(body=body, headers=headers) app = Application() app.router.add_route('/', index) app.router.add_route('/articles', articles) app.router.add_route('/articles/keywords/{keywords}', keywords) #Some bugs require us to dial to MongoDB just before server is listening host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news' connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False) app.run(debug=True)
Move p tag into conditional rendering
import React, { Component } from 'react'; import { connect } from 'react-redux'; class ResultList extends Component { renderResults(resultData) { const name = resultData.name; const url = resultData.url; return ( <div key={name} className="col-md-12 well"> <p>{name}</p> {url && <p><a href={url} target="_blank" rel="noopener noreferrer" className="btn btn-danger">Yelp Page</a></p>} </div> ); } render() { return ( <div className="container col-md-6 col-md-offset-3"> {this.props.results.map(this.renderResults)} </div> ); } } function mapStateToProps(state) { return { results: state.searchResults }; } export default connect(mapStateToProps)(ResultList);
import React, { Component } from 'react'; import { connect } from 'react-redux'; class ResultList extends Component { renderResults(resultData) { const name = resultData.name; const url = resultData.url; return ( <div key={name} className="col-md-12 well"> <p>{name}</p> <p> {url && <a href={url} target="_blank" rel="noopener noreferrer" className="btn btn-danger">Yelp Page</a>} </p> </div> ); } render() { return ( <div className="container col-md-6 col-md-offset-3"> {this.props.results.map(this.renderResults)} </div> ); } } function mapStateToProps(state) { return { results: state.searchResults }; } export default connect(mapStateToProps)(ResultList);
Print node version and environment architecture
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write("node " + process.version + " " + process.arch + ".\n"); sql.query(connectionString, testQuery, function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result: " + result[0]['Column0'] + " \n"); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
var sql = require('msnodesql'); // Change the connectionString. Example // "Driver={SQL Server Native Client 11.0};Server=tcp:?????.database.windows.net,1433;Database=????;Uid=?????@?????;Pwd=?????"; var connectionString = ""; var testQuery = "SELECT 1"; if(connectionString == "") { console.log("This script cannot run without a connection string"); return; } var http = require('http'); var port = process.env.PORT || 1337; var httpServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); sql.query(connectionString, testQuery, function(err, result) { if(err) res.end("Query Failed \n"); else res.end("Query result: " + result[0]['Column0'] + " \n"); }); }); httpServer.listen(port); console.log('Server running at localhost:'+port);
Disable chrome sandbox in tests
import puppeteer from 'puppeteer'; export async function evaluatePage (url, matches, timeout = 4000) { const args = await puppeteer.defaultArgs(); const browser = await puppeteer.launch({ args: [ ...args, '--no-sandbox', '--disable-setuid-sandbox', '--enable-experimental-web-platform-features' ] }); const page = await browser.newPage(); await page.goto(url); try { return await new Promise((resolve, reject) => { page.on('console', msg => { const text = msg.text(); if (text.match(matches)) { clearTimeout(timer); resolve(text); } }); const timer = setTimeout(() => reject(Error('Timed Out')), timeout); }); } finally { await browser.close(); } }
import puppeteer from 'puppeteer'; export async function evaluatePage (url, matches, timeout = 4000) { const args = await puppeteer.defaultArgs(); const browser = await puppeteer.launch({ args: [...args, '--enable-experimental-web-platform-features'] }); const page = await browser.newPage(); await page.goto(url); try { return await new Promise((resolve, reject) => { page.on('console', msg => { const text = msg.text(); if (text.match(matches)) { clearTimeout(timer); resolve(text); } }); const timer = setTimeout(() => reject(Error('Timed Out')), timeout); }); } finally { await browser.close(); } }
CHANGED: Switch back to port 3000 to avoid possible conflict with IIS.
module.exports = { server: { app: { message: 'Band Tile service for BKK Futár' }, connections: { router: { isCaseSensitive: false } } }, connections: [ { port: process.env.PORT || 3000, labels: ['api'] } ], registrations: [ { plugin: './next-ride', options: { routes: { prefix: '/nextride' } } } ] };
module.exports = { server: { app: { message: 'Band Tile service for BKK Futár' }, connections: { router: { isCaseSensitive: false } } }, connections: [ { port: 80, labels: ['api'] } ], registrations: [ { plugin: './next-ride', options: { routes: { prefix: '/nextride' } } } ] };
Fix console appended to work correctly.
package com.vaguehope.mikuru; import android.view.View; import android.widget.ScrollView; import android.widget.TextView; public class ConsoleAppender { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private final TextView tv; protected final ScrollView sv; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public ConsoleAppender (TextView tv, ScrollView sv) { this.tv = tv; this.sv = sv; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public void append (String... msgs) { for (String msg : msgs) this.tv.append(msg); this.sv.post(this.scrollDown); } private final Runnable scrollDown = new Runnable() { @Override public void run() { ConsoleAppender.this.sv.fullScroll(View.FOCUS_DOWN); } }; public void clear () { this.tv.setText(""); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
package com.vaguehope.mikuru; import android.widget.ScrollView; import android.widget.TextView; public class ConsoleAppender { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private final TextView tv; private final ScrollView sv; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public ConsoleAppender (TextView tv, ScrollView sv) { this.tv = tv; this.sv = sv; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - public void append (String... msgs) { for (String msg : msgs) { this.tv.append(msg); } this.sv.smoothScrollTo(0, this.tv.getHeight()); } public void clear () { this.tv.setText(""); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
Automate registration of application main functions: every module in sgg.app must have a main() and is a named console_script.
#! /usr/bin/env python import os import glob from setuptools import setup, find_packages setup(name='spiralgalaxygame', description='Spiral Galaxy Game', url='https://github.com/nejucomo/spiralgalaxygame', license='GPLv3', version='0.1.dev0', author='Nathan Wilcox', author_email='nejucomo@gmail.com', packages=find_packages(), install_requires=[ 'twisted >= 13.1', ], entry_points = { 'console_scripts': [ 'sgg-%s = sgg.app.%s:main' % (n, n) for n in [ os.path.basename(n)[:-3] for n in glob.glob('sgg/app/*.py') if not n.endswith('__init__.py') ] ], }, package_data = {'sgg': ['web/static/*']}, )
#! /usr/bin/env python from setuptools import setup, find_packages setup(name='spiralgalaxygame', description='Spiral Galaxy Game', url='https://github.com/nejucomo/spiralgalaxygame', license='GPLv3', version='0.1.dev0', author='Nathan Wilcox', author_email='nejucomo@gmail.com', packages=find_packages(), install_requires=[ 'twisted >= 13.1', ], entry_points = { 'console_scripts': [ 'sgg-httpd = sgg.app.httpd:main', ], }, package_data = {'sgg': ['web/static/*']}, )
Add support for jsx in webpack
const path = require('path'); module.exports = { entry: { app: ['./src/index.js'] }, output: { path: path.resolve(__dirname, 'build'), publicPath: '/assets/', //virtual filename: 'bundle.js' }, devServer: { contentBase: path.resolve(__dirname, 'build'), publicPath: '/assets/', //virtual inline: true, port: 8080 }, module: { loaders: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, loader: 'babel-loader' } ] } };
const path = require('path'); module.exports = { entry: { app: ['./src/index.js'] }, output: { path: path.resolve(__dirname, 'build'), publicPath: '/assets/', //virtual filename: 'bundle.js' }, devServer: { contentBase: path.resolve(__dirname, 'build'), publicPath: '/assets/', //virtual inline: true, port: 8080 }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' } ] } };
Add link to autopilot guide in operator autopilot CLI help text
package command import ( "strings" "github.com/mitchellh/cli" ) type OperatorAutopilotCommand struct { Meta } func (c *OperatorAutopilotCommand) Run(args []string) int { return cli.RunResultHelp } func (c *OperatorAutopilotCommand) Synopsis() string { return "Provides tools for modifying Autopilot configuration" } func (c *OperatorAutopilotCommand) Help() string { helpText := ` Usage: nomad operator autopilot <subcommand> [options] This command groups subcommands for interacting with Nomad's Autopilot subsystem. Autopilot provides automatic, operator-friendly management of Nomad servers. The command can be used to view or modify the current Autopilot configuration. For a full guide see: https://www.nomadproject.io/guides/autopilot.html Get the current Autopilot configuration: $ nomad operator autopilot get-config Set a new Autopilot configuration, enabling automatic dead server cleanup: $ nomad operator autopilot set-config -cleanup-dead-servers=true Please see the individual subcommand help for detailed usage information. ` return strings.TrimSpace(helpText) }
package command import ( "strings" "github.com/mitchellh/cli" ) type OperatorAutopilotCommand struct { Meta } func (c *OperatorAutopilotCommand) Run(args []string) int { return cli.RunResultHelp } func (c *OperatorAutopilotCommand) Synopsis() string { return "Provides tools for modifying Autopilot configuration" } func (c *OperatorAutopilotCommand) Help() string { helpText := ` Usage: nomad operator autopilot <subcommand> [options] This command groups subcommands for interacting with Nomad's Autopilot subsystem. Autopilot provides automatic, operator-friendly management of Nomad servers. The command can be used to view or modify the current Autopilot configuration. Get the current Autopilot configuration: $ nomad operator autopilot get-config Set a new Autopilot configuration, enabling automatic dead server cleanup: $ nomad operator autopilot set-config -cleanup-dead-servers=true Please see the individual subcommand help for detailed usage information. ` return strings.TrimSpace(helpText) }
Set Content-Length to 0 when no body is set
class HttpResponse(object): def __init__(self): self.body = '' self.headers = {} self.status_code = 200 self.status_string = 'OK' self.version = 'HTTP/1.1' def to_string(self): h = '%s %d %s\r\n' % ( self.version, self.status_code, self.status_string) for k,v in self.headers.iteritems(): h = '%s%s: %s\r\n' % (h, k, v) h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body)) if len(self.body): h = '%s%s' % (h, self.body) return h
class HttpResponse(object): def __init__(self): self.body = '' self.headers = {} self.status_code = 200 self.status_string = 'OK' self.version = 'HTTP/1.1' def to_string(self): h = '%s %d %s\r\n' % ( self.version, self.status_code, self.status_string) for k,v in self.headers.iteritems(): h = '%s%s: %s\r\n' % (h, k, v) if len(self.body): h = '%sContent-Length: %d\r\n\r\n' % (h, len(self.body)) h = '%s%s' % (h, self.body) return h
Remove Before hook from startpoint
const assert = require('assert') const { Given, When, Then } = require('@cucumber/cucumber') const Shouty = require('../../lib/shouty') const Coordinate = require('../../lib/coordinate') const ARBITARY_MESSAGE = 'Hello, world' let shouty = new Shouty() Given('Lucy is at {int}, {int}', function (x, y) { shouty.setLocation('Lucy', new Coordinate(x, y)) }) Given('Sean is at {int}, {int}', function (x, y) { shouty.setLocation('Sean', new Coordinate(x, y)) }) When('Sean shouts', function () { shouty.shout('Sean', ARBITARY_MESSAGE) }) Then('Lucy should hear Sean', function () { assert.strictEqual(shouty.getShoutsHeardBy('Lucy').size, 1) }) Then('Lucy should hear nothing', function () { assert.strictEqual(shouty.getShoutsHeardBy('Lucy').size, 0) })
const assert = require('assert') const { Before, Given, When, Then } = require('@cucumber/cucumber') const Shouty = require('../../lib/shouty') const Coordinate = require('../../lib/coordinate') const ARBITARY_MESSAGE = 'Hello, world' let shouty Before(function() { shouty = new Shouty() }) Given('Lucy is at {int}, {int}', function (x, y) { shouty.setLocation('Lucy', new Coordinate(x, y)) }) Given('Sean is at {int}, {int}', function (x, y) { shouty.setLocation('Sean', new Coordinate(x, y)) }) When('Sean shouts', function () { shouty.shout('Sean', ARBITARY_MESSAGE) }) Then('Lucy should hear Sean', function () { assert.strictEqual(shouty.getShoutsHeardBy('Lucy').size, 1) }) Then('Lucy should hear nothing', function () { assert.strictEqual(shouty.getShoutsHeardBy('Lucy').size, 0) })
Fix a possible undefined variable Summary: I pulled this out of the logs; not sure how anyone hit it, but this controller could bump into an undefined variable here: ``` 2015/06/24 22:59:55 [error] 10150#0: *172493 FastCGI sent in stderr: "PHP message: [2015-06-24 22:59:55] EXCEPTION: (RuntimeException) Undefined variable: subscriber_phids at [<phutil>/src/error/PhutilErrorHandler.php:210] PHP message: arcanist(head=master, ref.master=b697a3b80bdc), phabricator(head=redesign-2015, ref.master=0fd0f171f10f, ref.redesign-2015=1a5f986d73dd), phutil(head=master, ref.master=74c9cb3a266e) PHP message: #0 <#2> PhutilErrorHandler::handleError(integer, string, string, integer, array) called at [<phabricator>/src/applications/subscriptions/controller/PhabricatorSubscriptionsListController.php:32] PHP message: #1 <#2> PhabricatorSubscriptionsListController::processRequest() called at [<phabricator>/src/aphront/AphrontController.php:33] PHP message: #2 <#2> AphrontController::handleRequest(AphrontRequest) called at [<phabricator>/src/aphront/configuration/AphrontApplicationConfiguration.php:226] PHP message: #3 phlog(RuntimeException) called at [<phabricator>/src/aphront/configuration/AphrontDefaultApplicationConfiguration.php:229] PHP message: #4 AphrontDefaultApplicationConfiguration::handleException(RuntimeException) called at [<phabricator>/src/aphront/configuration/AphrontApplicationConfiguration.php:230] PHP message: #5 AphrontApplicationConfiguration::processRequest(AphrontRequest, PhutilDeferredLog, AphrontPHPHTTPSink, MultimeterControl) called at [<phabricator>/src/aphront/configuration/AphrontApplicationConfiguration.php:140] PHP message: #6 AphrontApplicationConfiguration::runHTTPRequest(AphrontPHPHTTPSink) called at [<phabricator>/webroot/index.php:21]" while reading response header from upstream, client: 167.114.156.198, server: , request: "GET /subscriptions/list/phid-wiki-366842d394398204f305/ HTTP/1.1", upstream: "fastcgi://unix:/core/var/pool/fpm.sock:", host: "secure.phabricator.com" ``` Clean things up a bit. Test Plan: Clicked "6 others" subscriber link on a task with a bunch of subscribers. Reviewers: btrahan Reviewed By: btrahan Subscribers: epriestley Differential Revision: https://secure.phabricator.com/D13430
<?php final class PhabricatorSubscriptionsListController extends PhabricatorController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getUser(); $object = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withPHIDs(array($request->getURIData('phid'))) ->executeOne(); if (!$object) { return new Aphront404Response(); } if (!($object instanceof PhabricatorSubscribableInterface)) { return new Aphront404Response(); } $phid = $object->getPHID(); $handle_phids = PhabricatorSubscribersQuery::loadSubscribersForPHID($phid); $handle_phids[] = $phid; $handles = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs($handle_phids) ->execute(); $object_handle = $handles[$phid]; $dialog = id(new SubscriptionListDialogBuilder()) ->setViewer($viewer) ->setTitle(pht('Subscribers')) ->setObjectPHID($phid) ->setHandles($handles) ->buildDialog(); return id(new AphrontDialogResponse())->setDialog($dialog); } }
<?php final class PhabricatorSubscriptionsListController extends PhabricatorController { private $phid; public function willProcessRequest(array $data) { $this->phid = idx($data, 'phid'); } public function shouldAllowPublic() { return true; } public function processRequest() { $request = $this->getRequest(); $viewer = $request->getUser(); $phid = $this->phid; $object = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withPHIDs(array($phid)) ->executeOne(); if ($object instanceof PhabricatorSubscribableInterface) { $subscriber_phids = PhabricatorSubscribersQuery::loadSubscribersForPHID( $phid); } $handle_phids = $subscriber_phids; $handle_phids[] = $phid; $handles = id(new PhabricatorHandleQuery()) ->setViewer($viewer) ->withPHIDs($handle_phids) ->execute(); $object_handle = $handles[$phid]; $dialog = id(new SubscriptionListDialogBuilder()) ->setViewer($viewer) ->setTitle(pht('Subscribers')) ->setObjectPHID($phid) ->setHandles($handles) ->buildDialog(); return id(new AphrontDialogResponse())->setDialog($dialog); } }
Change the default to false
package com.hubspot.jackson.datatype.protobuf; import com.google.protobuf.ExtensionRegistry; public class ProtobufJacksonConfig { private final ExtensionRegistryWrapper extensionRegistry; private final boolean acceptLiteralFieldnames; private ProtobufJacksonConfig(ExtensionRegistryWrapper extensionRegistry, boolean acceptLiteralFieldnames) { this.extensionRegistry = extensionRegistry; this.acceptLiteralFieldnames = acceptLiteralFieldnames; } public static Builder builder() { return new Builder(); } public ExtensionRegistryWrapper extensionRegistry() { return extensionRegistry; } public boolean acceptLiteralFieldnames() { return acceptLiteralFieldnames; } public static class Builder { private ExtensionRegistryWrapper extensionRegistry = ExtensionRegistryWrapper.empty(); private boolean acceptLiteralFieldnames = false; private Builder() {} public Builder extensionRegistry(ExtensionRegistry extensionRegistry) { return extensionRegistry(ExtensionRegistryWrapper.wrap(extensionRegistry)); } public Builder extensionRegistry(ExtensionRegistryWrapper extensionRegistry) { this.extensionRegistry = extensionRegistry; return this; } public Builder acceptLiteralFieldnames(boolean acceptLiteralFieldnames) { this.acceptLiteralFieldnames = acceptLiteralFieldnames; return this; } public ProtobufJacksonConfig build() { return new ProtobufJacksonConfig(extensionRegistry, acceptLiteralFieldnames); } } }
package com.hubspot.jackson.datatype.protobuf; import com.google.protobuf.ExtensionRegistry; public class ProtobufJacksonConfig { private final ExtensionRegistryWrapper extensionRegistry; private final boolean acceptLiteralFieldnames; private ProtobufJacksonConfig(ExtensionRegistryWrapper extensionRegistry, boolean acceptLiteralFieldnames) { this.extensionRegistry = extensionRegistry; this.acceptLiteralFieldnames = acceptLiteralFieldnames; } public static Builder builder() { return new Builder(); } public ExtensionRegistryWrapper extensionRegistry() { return extensionRegistry; } public boolean acceptLiteralFieldnames() { return acceptLiteralFieldnames; } public static class Builder { private ExtensionRegistryWrapper extensionRegistry = ExtensionRegistryWrapper.empty(); private boolean acceptLiteralFieldnames = true; private Builder() {} public Builder extensionRegistry(ExtensionRegistry extensionRegistry) { return extensionRegistry(ExtensionRegistryWrapper.wrap(extensionRegistry)); } public Builder extensionRegistry(ExtensionRegistryWrapper extensionRegistry) { this.extensionRegistry = extensionRegistry; return this; } public Builder acceptLiteralFieldnames(boolean acceptLiteralFieldnames) { this.acceptLiteralFieldnames = acceptLiteralFieldnames; return this; } public ProtobufJacksonConfig build() { return new ProtobufJacksonConfig(extensionRegistry, acceptLiteralFieldnames); } } }
Add prefixes for timers and counters to emulate StatsD behavior.
package de.is24.util.monitoring.metrics; import com.codahale.metrics.MetricRegistry; import de.is24.util.monitoring.AbstractMonitorPlugin; import java.util.concurrent.TimeUnit; public class MetricsPlugin extends AbstractMonitorPlugin { private MetricRegistry metricRegistry; public MetricsPlugin(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } @Override public String getUniqueName() { return null; } @Override public void initializeCounter(String name) { } @Override public void incrementCounter(String name, int increment) { metricRegistry.counter(withCountersPrefix(name)).inc(increment); } @Override public void incrementHighRateCounter(String name, int increment) { incrementCounter(name, increment); } @Override public void addTimerMeasurement(String name, long timing) { metricRegistry.timer(withTimersPrefix(name)).update(timing, TimeUnit.MILLISECONDS); } @Override public void addSingleEventTimerMeasurement(String name, long timing) { addTimerMeasurement(name, timing); } @Override public void addHighRateTimerMeasurement(String name, long timing) { addTimerMeasurement(name, timing); } @Override public void initializeTimerMeasurement(String name) { } @Override public void afterRemovalNotification() { } private String withTimersPrefix(String name) { return "timers." + name; } private String withCountersPrefix(String name) { return "counters." + name; } }
package de.is24.util.monitoring.metrics; import com.codahale.metrics.MetricRegistry; import de.is24.util.monitoring.AbstractMonitorPlugin; import java.util.concurrent.TimeUnit; public class MetricsPlugin extends AbstractMonitorPlugin { private MetricRegistry metricRegistry; public MetricsPlugin(MetricRegistry metricRegistry) { this.metricRegistry = metricRegistry; } @Override public String getUniqueName() { return null; } @Override public void initializeCounter(String name) { } @Override public void incrementCounter(String name, int increment) { metricRegistry.counter(name).inc(increment); } @Override public void incrementHighRateCounter(String name, int increment) { incrementCounter(name, increment); } @Override public void addTimerMeasurement(String name, long timing) { metricRegistry.timer(name).update(timing, TimeUnit.MILLISECONDS); } @Override public void addSingleEventTimerMeasurement(String name, long timing) { metricRegistry.timer(name).update(timing, TimeUnit.MILLISECONDS); } @Override public void addHighRateTimerMeasurement(String name, long timing) { metricRegistry.timer(name).update(timing, TimeUnit.MILLISECONDS); } @Override public void initializeTimerMeasurement(String name) { } @Override public void afterRemovalNotification() { } }
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-align/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/typography/text-align/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-text-align/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-text-align/tachyons-text-align.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_text-align.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/text-align/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/typography/text-align/index.html', html)
Put un-stash in finally block Without it a failure will lead to us not putting the user back in the state they expect to be in
import contextlib import logging import subprocess LOGGER = logging.getLogger(__name__) def execute(command): LOGGER.debug("Executing %s", ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate(input=None) if proc.returncode != 0: raise Exception("Failed to execute command {}".format(' '.join(command))) LOGGER.debug("stdout %s", stdout) LOGGER.debug("stderr %s", stderr) @contextlib.contextmanager def stash(): execute(['git', 'stash', '-u', '--keep-index']) try: yield finally: execute(['git', 'reset', '--hard']) execute(['git', 'stash', 'pop', '--quiet', '--index'])
import contextlib import logging import subprocess LOGGER = logging.getLogger(__name__) def execute(command): LOGGER.debug("Executing %s", ' '.join(command)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate(input=None) if proc.returncode != 0: raise Exception("Failed to execute command {}".format(' '.join(command))) LOGGER.debug("stdout %s", stdout) LOGGER.debug("stderr %s", stderr) @contextlib.contextmanager def stash(): execute(['git', 'stash', '-u', '--keep-index']) yield execute(['git', 'reset', '--hard']) execute(['git', 'stash', 'pop', '--quiet', '--index'])
Fix search:audit to work with "doc"
<?php namespace App\Console\Commands; use Elasticsearch; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class SearchAudit extends BaseCommand { protected $signature = 'search:audit'; protected $description = 'Compare the counts of database records with those in the search index'; public function handle() { $prefix = env('ELASTICSEARCH_INDEX'); $models = app('Search')->getSearchableModels(); foreach ($models as $model) { $endpoint = app('Resources')->getEndpointForModel($model); $index = $prefix . '-' . $endpoint; $this->audit( $model, $index, $endpoint ); } } public function audit( $model, $index, $endpoint ) { $response = Elasticsearch::search([ 'index' => $index, 'type' => 'doc', 'size' => 0 ]); $es_count = $response['hits']['total']; $db_count = $model::count(); $method = ( $es_count == $db_count ) ? 'info' : 'warn'; $this->$method( "{$endpoint} = {$db_count} in db, {$es_count} in es"); } }
<?php namespace App\Console\Commands; use Elasticsearch; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class SearchAudit extends BaseCommand { protected $signature = 'search:audit'; protected $description = 'Compare the counts of database records with those in the search index'; public function handle() { $prefix = env('ELASTICSEARCH_INDEX'); $models = app('Search')->getSearchableModels(); foreach ($models as $model) { $endpoint = app('Resources')->getEndpointForModel($model); $index = $prefix . '-' . $endpoint; $this->audit( $model, $index, $endpoint ); } } public function audit( $model, $index, $endpoint ) { $response = Elasticsearch::search([ 'index' => $index, 'type' => $endpoint, 'size' => 0 ]); $es_count = $response['hits']['total']; $db_count = $model::count(); $method = ( $es_count == $db_count ) ? 'info' : 'warn'; $this->$method( "{$endpoint} = {$db_count} in db, {$es_count} in es"); } }
Add logic to convert reddit dot com cookies
import { atob } from 'Base64'; import { PrivateAPI } from '@r/private'; import Session from '../../app/models/Session'; import makeSessionFromData from './makeSessionFromData'; import setSessionCookies from './setSessionCookies'; import * as sessionActions from '../../app/actions/session'; export default async (ctx, dispatch, apiOptions) => { // try to create a session from the existing cookie // if the session is malformed somehow, the catch will trigger when trying // to access it const tokenCookie = ctx.cookies.get('token'); const redditSessionExists = ctx.cookies.get('reddit_session'); if (!(tokenCookie || redditSessionExists)) { return; } let session; let sessionData; if (tokenCookie) { sessionData = JSON.parse(atob(tokenCookie)); session = new Session(sessionData); } else { // try to convert reddit session cookie const cookies = ctx.headers.cookie.replace(/__cf_mob_redir=1/, '__cf_mob_redir=0').split(';'); sessionData = await PrivateAPI.convertCookiesToAuthToken(apiOptions, cookies); session = new Session(sessionData); } // if the session is invalid, try to use the refresh token to grab a new // session. if (!session.isValid) { const data = await PrivateAPI.refreshToken(apiOptions, sessionData.refreshToken); session = makeSessionFromData({ ...data, refresh_token: sessionData.refreshToken }); // don't forget to set the cookies with the new session, or the session // will remain invalid the next time the page is fetched setSessionCookies(ctx, session); } // push the session into the store dispatch(sessionActions.setSession(session)); };
import { atob } from 'Base64'; import { PrivateAPI } from '@r/private'; import Session from '../../app/models/Session'; import makeSessionFromData from './makeSessionFromData'; import setSessionCookies from './setSessionCookies'; import * as sessionActions from '../../app/actions/session'; export default async (ctx, dispatch, apiOptions) => { // try to create a session from the existing cookie // if the session is malformed somehow, the catch will trigger when trying // to access it const tokenCookie = ctx.cookies.get('token'); if (!tokenCookie) { return; } const sessionData = JSON.parse(atob(tokenCookie)); let session = new Session(sessionData); // if the session is invalid, try to use the refresh token to grab a new // session. if (!session.isValid) { const data = await PrivateAPI.refreshToken(apiOptions, sessionData.refreshToken); session = makeSessionFromData({ ...data, refresh_token: sessionData.refreshToken }); // don't forget to set the cookies with the new session, or the session // will remain invalid the next time the page is fetched setSessionCookies(ctx, session); } // push the session into the store dispatch(sessionActions.setSession(session)); };
Update Plugin state entity refactoring
package com.epam.ta.reportportal.ws.model.integration; import com.fasterxml.jackson.annotation.JsonInclude; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdatePluginStateRQ implements Serializable { @NotNull private Boolean isEnabled; public UpdatePluginStateRQ() { } public Boolean getEnabled() { return isEnabled; } public void setEnabled(Boolean enabled) { isEnabled = enabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdatePluginStateRQ that = (UpdatePluginStateRQ) o; return isEnabled != null ? isEnabled.equals(that.isEnabled) : that.isEnabled == null; } @Override public int hashCode() { return isEnabled != null ? isEnabled.hashCode() : 0; } }
package com.epam.ta.reportportal.ws.model.integration; import com.epam.ta.reportportal.ws.annotations.NotEmpty; import com.fasterxml.jackson.annotation.JsonInclude; import javax.validation.constraints.NotNull; import java.io.Serializable; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdatePluginStateRQ implements Serializable { @NotNull @NotEmpty private String name; @NotNull private Boolean isEnabled; public UpdatePluginStateRQ() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getEnabled() { return isEnabled; } public void setEnabled(Boolean enabled) { isEnabled = enabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UpdatePluginStateRQ that = (UpdatePluginStateRQ) o; if (name != null ? !name.equals(that.name) : that.name != null) { return false; } return isEnabled != null ? isEnabled.equals(that.isEnabled) : that.isEnabled == null; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (isEnabled != null ? isEnabled.hashCode() : 0); return result; } }
Add __unicode__ method to UserAccount model
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') def __unicode__(self): return u'{}'.format(self.user.username) @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
# coding: utf-8 from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from registration.signals import user_activated from django.dispatch import receiver class UserAccount(models.Model): """ A user account. Used to store any information related to users. """ user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='account') class Meta: verbose_name = _('user account') verbose_name_plural = _('user accounts') @receiver(user_activated) def registration_completed(sender, user, request, **kwargs): account, created = UserAccount.objects.get_or_create(user=user) print account, created
Set env and default time for Root Daily Report
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * OVERRIDING PARENT CLASS * The bootstrap classes for the application. * * @var array */ protected $bootstrappers = [ 'Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\SetRequestForConsole', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders', ]; /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ 'App\Console\Commands\SendRootReport', ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('root:report')->dailyAt(env('ROOT_REPORT_TIME', '20:00')); } }
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * OVERRIDING PARENT CLASS * The bootstrap classes for the application. * * @var array */ protected $bootstrappers = [ 'Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\SetRequestForConsole', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders', ]; /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ 'App\Console\Commands\SendRootReport', ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('root:report')->daily(); } }
Fix for unterminated entity reference Solution for issue https://github.com/kbsali/php-redmine-api/issues/54 was incorrectly implemented. It throw "unterminated entity reference" for "&" character.
<?php namespace Redmine\Api; class SimpleXMLElement extends \SimpleXMLElement { /** * Makes sure string is properly escaped * http://stackoverflow.com/questions/552957/rationale-behind-simplexmlelements-handling-of-text-values-in-addchild-and-adda) */ public function addChild($name, $value = null, $ns = null) { $args = func_get_args(); if (count($args) > 1 && is_string($args[1])) { // use the property assignment to set the text correctly $text = $args[1]; // we need to clear "$value" argument value cause it will product Unterminated entity reference for "&" $args[1] = ''; $node = call_user_func_array(array('parent', 'addChild'), $args); // next, all characters like "&", "<", ">" will be properly escaped $node->{0} = $text; } else { $node = call_user_func_array(array('parent', 'addChild'), $args); } return $node; } }
<?php namespace Redmine\Api; class SimpleXMLElement extends \SimpleXMLElement { /** * Makes sure string is properly escaped * http://stackoverflow.com/questions/552957/rationale-behind-simplexmlelements-handling-of-text-values-in-addchild-and-adda) */ public function addChild($name, $value = null, $ns = null) { $args = func_get_args(); if (count($args) > 1 && is_string($args[1])) { // use the property assignment to set the text correctly $text = $args[1]; $node = call_user_func_array(array('parent', 'addChild'), $args); $node->{0} = $text; } else { $node = call_user_func_array(array('parent', 'addChild'), $args); } return $node; } }
Test actor: Don't draw until position is set in first update cycle
class GuyActor extends SquareActor { constructor() { super(); this.didInit = false; } update(u) { super.update(u); if (!this.didInit) { this.position.x = SquareMath.rand(-u.resolution.w, u.resolution.w); this.position.y = SquareMath.rand(-u.resolution.h, u.resolution.h); this.velocity.x = SquareMath.rand(-10, +10) / 100; this.velocity.y = SquareMath.rand(-10, +10) / 100; this.didInit = true; } this.velocity.y += SquareMath.rand(-10, +10) / 1000; this.velocity.x -= SquareMath.rand(-10, +10) / 1000; } draw(d) { if (!this.didInit) { return; } super.draw(d); d.context.fillStyle = '#fff'; d.context.fillRect(this.drawPosition.x, this.drawPosition.y, 32, 32); } }
class GuyActor extends SquareActor { constructor() { super(); this.didInit = false; } update(u) { super.update(u); if (!this.didInit) { this.position.x = SquareMath.rand(-u.resolution.w, u.resolution.w); this.position.y = SquareMath.rand(-u.resolution.h, u.resolution.h); this.velocity.x = SquareMath.rand(-10, +10) / 100; this.velocity.y = SquareMath.rand(-10, +10) / 100; this.didInit = true; } this.velocity.y += SquareMath.rand(-10, +10) / 1000; this.velocity.x -= SquareMath.rand(-10, +10) / 1000; } draw(d) { super.draw(d); d.context.fillStyle = '#fff'; d.context.fillRect(this.drawPosition.x, this.drawPosition.y, 32, 32); } }
Add width and height to pixbuf_from_string() and scale the image if any of them are set
# # Kiwi: a Framework and Enhanced Widgets for Python # # Copyright (C) 2012 Async Open Source # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA # # Author(s): Johan Dahlin <jdahlin@async.com.br> # from gtk import gdk def pixbuf_from_string(pixbuf_data, format='png', width=None, height=None): loader = gdk.PixbufLoader(format) loader.write(pixbuf_data) loader.close() pixbuf = loader.get_pixbuf() if width is not None or height is not None: scaled_pixbuf = pixbuf.scale_simple(width, height, gdk.INTERP_BILINEAR) if scaled_pixbuf is None: print 'Warning: could not scale image' else: pixbuf = scaled_pixbuf return pixbuf
# # Kiwi: a Framework and Enhanced Widgets for Python # # Copyright (C) 2012 Async Open Source # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA # # Author(s): Johan Dahlin <jdahlin@async.com.br> # from gtk import gdk def pixbuf_from_string(pixbuf_data, format='png'): loader = gdk.PixbufLoader(format) loader.write(pixbuf_data) loader.close() return loader.get_pixbuf()
Use rich for printing in ipython
"""Imports for IPython""" # pylint: disable=W0611 # import this import os import re import sys import inspect pyprint = print mores = [] try: from rich.console import Console console = Console(color_system="standard") print = console.print mores += ["rich"] from rich import pretty pretty.install() except ImportError: pass try: from importlib import reload except ImportError: def reload(x): raise NotImplementedError("importlib.reload is not available") try: import requests mores += ["requests"] except ModuleNotFoundError: pass try: import pysyte from pysyte.types import paths from pysyte.types.paths import path from pysyte import cli except ImportError as e: print(e) sys.stderr.write("pip install pysyte # please") try: from pathlib import Path mores += ["Path"] except ImportError: pass more = ", ".join([" "] + mores) if mores else "" executable = sys.executable.replace(os.environ['HOME'], '~') version = sys.version.split()[0] stdout = lambda x: sys.stdout.write(f"{x}\n") stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}") stdout("") stdout(f"{executable} {version}")
"""Imports for IPython""" # pylint: disable=W0611 # import this import os import re import sys import inspect pyprint = print mores = [] try: from rich.console import Console console = Console(color_system="standard") print = console.print mores += ["rich"] except ImportError: pass try: from importlib import reload except ImportError: def reload(x): raise NotImplementedError("importlib.reload is not available") try: import requests mores += ["requests"] except ModuleNotFoundError: pass try: import pysyte from pysyte.types import paths from pysyte.types.paths import path from pysyte import cli except ImportError as e: print(e) sys.stderr.write("pip install pysyte # please") try: from pathlib import Path mores += ["Path"] except ImportError: pass more = ", ".join([" "] + mores) if mores else "" executable = sys.executable.replace(os.environ['HOME'], '~') version = sys.version.split()[0] stdout = lambda x: sys.stdout.write(f"{x}\n") stdout(f"import os, re, sys, inspect, pysyte, paths, path, cli{more}") stdout("") stdout(f"{executable} {version}")
Create test articles via service
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from byceps.services.shop.article import service as article_service from testfixtures.shop_article import create_article from testfixtures.shop_shop import create_shop from tests.base import AbstractAppTestCase from tests.helpers import DEFAULT_EMAIL_CONFIG_ID class ShopTestBase(AbstractAppTestCase): # -------------------------------------------------------------------- # # helpers def create_shop( self, shop_id='shop-1', email_config_id=DEFAULT_EMAIL_CONFIG_ID ): shop = create_shop(shop_id, email_config_id) self.db.session.add(shop) self.db.session.commit() return shop def create_article(self, shop_id, **kwargs): article = create_article(shop_id, **kwargs) return article_service.create_article( shop_id, article.item_number, article.description, article.price, article.tax_rate, article.quantity, )
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from testfixtures.shop_article import create_article from testfixtures.shop_shop import create_shop from tests.base import AbstractAppTestCase from tests.helpers import DEFAULT_EMAIL_CONFIG_ID class ShopTestBase(AbstractAppTestCase): # -------------------------------------------------------------------- # # helpers def create_shop( self, shop_id='shop-1', email_config_id=DEFAULT_EMAIL_CONFIG_ID ): shop = create_shop(shop_id, email_config_id) self.db.session.add(shop) self.db.session.commit() return shop def create_article(self, shop_id, **kwargs): article = create_article(shop_id, **kwargs) self.db.session.add(article) self.db.session.commit() return article
Add reminder to look at the number of terms returned
from gensim.models import Word2Vec import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) class Word2VecSuggester(): def __init__(self, modelfile): try: self.model = Word2Vec.load(modelfile) logger.info('Load Word2Vec model "{}"'.format(modelfile)) except IOError: logger.warn('Unable to load Word2Vec model "{}"'.format(modelfile)) logger.warn('Was the train_word2vec script run?') self.model = None def suggest_terms(self, query_word): # TODO: make the number of terms returned a parameter of the function if self.model is not None: results = self.model.most_similar(positive=[query_word], negative=[], topn=10) suggestions = {} for word, weight in results: suggestions[word] = weight return suggestions else: return {}
from gensim.models import Word2Vec import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) class Word2VecSuggester(): def __init__(self, modelfile): try: self.model = Word2Vec.load(modelfile) logger.info('Load Word2Vec model "{}"'.format(modelfile)) except IOError: logger.warn('Unable to load Word2Vec model "{}"'.format(modelfile)) logger.warn('Was the train_word2vec script run?') self.model = None def suggest_terms(self, query_word): if self.model is not None: results = self.model.most_similar(positive=[query_word], negative=[]) suggestions = {} for word, weight in results: suggestions[word] = weight return suggestions else: return {}
Fix js error on touite input when not authenticated
jQuery(document).ready(function($) { if ($('#new_tweet').length) { function update_chars_left() { var max_len = 140; var textarea = $('#new_tweet')[0]; var tweet_len = textarea.value.length; if (tweet_len >= max_len) { textarea.value = textarea.value.substring(0, max_len); // truncate $('#chars_left').html("0"); } else { $('#chars_left').html(max_len - tweet_len); } } $('#new_tweet').keyup(function() { update_chars_left(); }); update_chars_left(); $('#new_tweet').focus(); } });
jQuery(document).ready(function($) { function update_chars_left() { var max_len = 140; var textarea = $('#new_tweet')[0]; var tweet_len = textarea.value.length; if (tweet_len >= max_len) { textarea.value = textarea.value.substring(0, max_len); // truncate $('#chars_left').html("0"); } else { $('#chars_left').html(max_len - tweet_len); } } $('#new_tweet').keyup(function() { update_chars_left(); }); update_chars_left(); $('#new_tweet').focus(); });
Add missing doc block type and type hint
<?php declare(strict_types=1); namespace Roave\SignatureTest; use PHPUnit\Framework\TestCase; use Roave\Signature\Encoder\Base64Encoder; use Roave\Signature\FileContentSigner; /** * @covers \Roave\Signature\FileContentSigner */ final class FileContentSignerTest extends TestCase { /** * @return string[][] */ public function signProvider(): array { return [ ['Roave/Signature: PD9waHA=', '<?php'], ['Roave/Signature: PD9waHAK', '<?php' . "\n"], ['Roave/Signature: PGh0bWw+', '<html>'], ['Roave/Signature: cGxhaW4gdGV4dA==', 'plain text'], ]; } /** * @dataProvider signProvider */ public function testSign(string $expected, string $inputString) { $signer = new FileContentSigner(new Base64Encoder()); self::assertSame($expected, $signer->sign($inputString)); } }
<?php declare(strict_types=1); namespace Roave\SignatureTest; use PHPUnit\Framework\TestCase; use Roave\Signature\Encoder\Base64Encoder; use Roave\Signature\FileContentSigner; /** * @covers \Roave\Signature\FileContentSigner */ final class FileContentSignerTest extends TestCase { public function signProvider() { return [ ['Roave/Signature: PD9waHA=', '<?php'], ['Roave/Signature: PD9waHAK', '<?php' . "\n"], ['Roave/Signature: PGh0bWw+', '<html>'], ['Roave/Signature: cGxhaW4gdGV4dA==', 'plain text'], ]; } /** * @dataProvider signProvider */ public function testSign($expected, $inputString) { $signer = new FileContentSigner(new Base64Encoder()); self::assertSame($expected, $signer->sign($inputString)); } }
Update ws endpoint to localhost
import {Entity} from 'aframe-react'; import React from 'react'; import Wsgamepad from './Wsgamepad'; export default ({ position=[0, 0, 5], id="camera", active="false", userHeight="4.8", rotation=[0, 0, 0], far="10000", looksControlsEnabeld="true", fov="80", near="0.005", velocity=[3, 3, 3], ...props }) => ( <Entity position={[0, 5, 0]} static-body=""> <Entity id={id} active={active} camera={{ 'user-height': userHeight, active, far, fov, near }} rotation={rotation} mouse-controls="" touch-controls="" hmd-controls="" ws-gamepad={{ endpoint: "ws://127.0.0.1:7878" }} look-controls="" universal-controls="" gamepad-controls="" kinematic-body="" {...props}/> </Entity> ); /* add back `universal-controls=""` to `Entity` to enable universal control again */
import {Entity} from 'aframe-react'; import React from 'react'; import Wsgamepad from './Wsgamepad'; export default ({ position=[0, 0, 5], id="camera", active="false", userHeight="4.8", rotation=[0, 0, 0], far="10000", looksControlsEnabeld="true", fov="80", near="0.005", velocity=[3, 3, 3], ...props }) => ( <Entity position={[0, 5, 0]} static-body=""> <Entity id={id} active={active} camera={{ 'user-height': userHeight, active, far, fov, near }} rotation={rotation} mouse-controls="" touch-controls="" hmd-controls="" ws-gamepad={{ endpoint: "ws://192.168.0.14:7878" }} look-controls="" universal-controls="" gamepad-controls="" kinematic-body="" {...props}/> </Entity> ); /* add back `universal-controls=""` to `Entity` to enable universal control again */
Change failure callback to show responding html embedded failure message from Active Record.
$(document).ready( function () { $(".upvote").click( function() { var commentId = $(".upvote").data("id"); event.preventDefault(); $.ajax({ url: '/response/up_vote', method: 'POST', data: { id: commentId }, dataType: 'JSON' }).done( function (voteCount) { if (voteCount == 1) { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } else { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } }).fail( function (failureInfo) { console.log("Failed. Here is why:"); console.log(failureInfo.responseText); }) }) })
$(document).ready( function () { $(".upvote").click( function() { var commentId = $(".upvote").data("id"); event.preventDefault(); $.ajax({ url: '/response/up_vote', method: 'POST', data: { id: commentId }, dataType: 'JSON' }).done( function (voteCount) { if (voteCount == 1) { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } else { $("span[data-id=" + commentId + "]").html(voteCount + " vote"); } }).fail( function (voteCount) { console.log("Failed. Here is the voteCount:"); console.log(voteCount); }) }) })
Use a regex to test for build servers
'use strict' const path = require('path') const gulp = require('gulp') const replace = require('gulp-replace') const config = require('../config') const NodeGitVersion = require('@hmrc/node-git-versioning') let version = '' const errorPages = (v) => { const nextMinorVersion = parseInt(NodeGitVersion().split('.')[1]) + 1 if (/https?:\/\/.*\.tax\.service\.gov\.uk\//.test(process.env.JENKINS_URL)) { version = [v.slice(1), nextMinorVersion, '0'].join('.') } else { version = path.parse(config.snapshotDir[v]).name } return gulp.src(config.errorPages.src) .pipe(replace('{{ assetsPath }}', `${config.errorPages.assetsBaseUri}${version}/`)) .pipe(gulp.dest(config.snapshotDir[v])) } gulp.task('error-pages:v3', () => { return errorPages('v3') }) gulp.task('error-pages:v4', () => { return errorPages('v4') })
'use strict' const path = require('path') const gulp = require('gulp') const replace = require('gulp-replace') const config = require('../config') const NodeGitVersion = require('@hmrc/node-git-versioning') let version = '' const errorPages = (v) => { const nextMinorVersion = parseInt(NodeGitVersion().split('.')[1]) + 1 if (process.env.JENKINS_URL === 'https://build.tax.service.gov.uk/') { version = [v.slice(1), nextMinorVersion, '0'].join('.') } else { version = path.parse(config.snapshotDir[v]).name } return gulp.src(config.errorPages.src) .pipe(replace('{{ assetsPath }}', `${config.errorPages.assetsBaseUri}${version}/`)) .pipe(gulp.dest(config.snapshotDir[v])) } gulp.task('error-pages:v3', () => { return errorPages('v3') }) gulp.task('error-pages:v4', () => { return errorPages('v4') })
Use the description, remove debug reference. git-svn-id: 3b6cb4556d214d66df54bca2662d7ef408f367bf@3232 46e82423-29d8-e211-989e-002590a4cdd4
<?php # # $Id: ports-broken.php,v 1.1.2.20 2005-01-23 03:41:33 dan Exp $ # # Copyright (c) 1998-2004 DVL Software Limited # require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports_page_list_ports.php'); $page = new freshports_page_list_ports(); $page->setDB($db); $page->setTitle('Broken ports'); $page->setDescription('These are the broken ports'); $page->setSQL("ports.broken <> ''", $User->id); $page->display(); ?>
<?php # # $Id: ports-broken.php,v 1.1.2.19 2005-01-23 03:12:54 dan Exp $ # # Copyright (c) 1998-2004 DVL Software Limited # require_once($_SERVER['DOCUMENT_ROOT'] . '/include/common.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/databaselogin.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/getvalues.php'); require_once($_SERVER['DOCUMENT_ROOT'] . '/include/freshports_page_list_ports.php'); $Debug = 0; $Title = 'Broken ports'; $page = new freshports_page_list_ports(); $page->setDB($db); $page->setTitle($Title); $page->setSQL("ports.broken <> ''", $User->id); $page->display(); ?>
Upgrade to 0.3.1 to avoid broken 0.3
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'cssselect', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.3.1', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
#!/usr/bin/env python from setuptools import find_packages, Command setup_params = dict( name='bugimporters', version=0.1, author='Various contributers to the OpenHatch project, Berry Phillips', author_email='all@openhatch.org, berryphillips@gmail.com', packages=find_packages(), description='Bug importers for the OpenHatch project', install_requires=[ 'gdata', 'lxml', 'cssselect', 'pyopenssl', 'unicodecsv', 'feedparser', 'twisted', 'python-dateutil', 'decorator', 'scrapy>0.9', 'argparse', 'mock', 'PyYAML', 'autoresponse>=0.2', ], ) ### Python 2.7 already has importlib. Because of that, ### we can't put it in install_requires. We test for ### that here; if needed, we add it. try: import importlib except ImportError: setup_params['install_requires'].append('importlib') if __name__ == '__main__': from setuptools import setup setup(**setup_params)
:wrench: Put songs as new for 2 months
import _ from 'lodash' const grouping = [ { title: 'Custom Song', criteria: song => song.custom }, { title: 'Tutorial', criteria: song => song.tutorial }, { title: 'Unreleased', criteria: song => song.unreleased }, { title: 'New Songs', criteria: song => song.added && Date.now() - Date.parse(song.added) < 60 * 86400000, sort: song => song.added, reverse: true }, { title: '☆', criteria: () => true } ] export function groupSongsIntoCategories (songs) { let groups = grouping.map(group => ({ input: group, output: { title: group.title, songs: [] } })) for (let song of songs) { for (let { input, output } of groups) { if (input.criteria(song)) { output.songs.push(song) break } } } for (let { input, output } of groups) { if (input.sort) output.songs = _.sortBy(output.songs, input.sort) if (input.reverse) output.songs.reverse() } return _(groups) .map('output') .filter(group => group.songs.length > 0) .value() } export default groupSongsIntoCategories
import _ from 'lodash' const grouping = [ { title: 'Custom Song', criteria: song => song.custom }, { title: 'Tutorial', criteria: song => song.tutorial }, { title: 'Unreleased', criteria: song => song.unreleased }, { title: 'New Songs', criteria: song => song.added && Date.now() - Date.parse(song.added) < 14 * 86400000, sort: song => song.added, reverse: true }, { title: '☆', criteria: () => true } ] export function groupSongsIntoCategories (songs) { let groups = grouping.map(group => ({ input: group, output: { title: group.title, songs: [] } })) for (let song of songs) { for (let { input, output } of groups) { if (input.criteria(song)) { output.songs.push(song) break } } } for (let { input, output } of groups) { if (input.sort) output.songs = _.sortBy(output.songs, input.sort) if (input.reverse) output.songs.reverse() } return _(groups) .map('output') .filter(group => group.songs.length > 0) .value() } export default groupSongsIntoCategories
Add missing data to the projects table.
'use strict'; const Sequelize = require('sequelize'); // projects-model.js - A sequelize model // // See http://docs.sequelizejs.com/en/latest/docs/models-definition/ // for more of what you can do here. module.exports = function(sequelize) { const Projects = sequelize.define('Projects', { name: { type: Sequelize.STRING, allowNull: false }, description:{ type: Sequelize.STRING, allowNull: false }, bounty: { type: Sequelize.INTERGER, allowNull: false, }, videoUrl: { type: Sequelize.STRING, allowNull: true }, image: { type: Sequelize.BLOB('long'), allowNull: true } }, { classMethods: { associate() { Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'}); Projects.belongsTo(sequelize.models.Submissions, {foreignKey: 'submissionid'}); } } }); // Projects.sync(); return Projects; };
'use strict'; const Sequelize = require('sequelize'); // projects-model.js - A sequelize model // // See http://docs.sequelizejs.com/en/latest/docs/models-definition/ // for more of what you can do here. module.exports = function(sequelize) { const Projects = sequelize.define('Projects', { name: { type: Sequelize.STRING, allowNull: false }, description:{ type: Sequelize.STRING, allowNull: false }, }, { classMethods: { associate() { Projects.belongsTo(sequelize.models.Users, {foreignKey: 'userid'}); Projects.belongsTo(sequelize.models.Submissions, {foreignKey: 'submissionid'}); } } }); // Projects.sync(); return Projects; };
Fix prefetch_translations() -- be sure we only deal with iteratables.
# -*- coding: utf-8 -*- import collections import itertools from . import utils def prefetch_translations(instances, **kwargs): """ Prefetches translations for the given instances. Can be useful for a list of instances. """ from .mixins import ModelMixin if not isinstance(instances, collections.Iterable): instances = [instances] populate_missing = kwargs.get('populate_missing', True) grouped_translations = utils.get_grouped_translations(instances, **kwargs) # In the case of no translations objects if not grouped_translations and populate_missing: for instance in instances: instance.populate_missing_translations() for instance in instances: if issubclass(instance.__class__, ModelMixin) and instance.pk in grouped_translations: for translation in grouped_translations[instance.pk]: instance._linguist.set_cache(instance=instance, translation=translation) if populate_missing: instance.populate_missing_translations()
# -*- coding: utf-8 -*- import collections import itertools from . import utils def prefetch_translations(instances, **kwargs): """ Prefetches translations for the given instances. Can be useful for a list of instances. """ from .mixins import ModelMixin populate_missing = kwargs.get('populate_missing', True) grouped_translations = utils.get_grouped_translations(instances, **kwargs) # In the case of no translations objects if not grouped_translations and populate_missing: for instance in instances: instance.populate_missing_translations() for instance in instances: if issubclass(instance.__class__, ModelMixin) and instance.pk in grouped_translations: for translation in grouped_translations[instance.pk]: instance._linguist.set_cache(instance=instance, translation=translation) if populate_missing: instance.populate_missing_translations()
Test Heap Sort: Sort array with equal vals
/* eslint-env mocha */ const HeapSort = require('../../../src').algorithms.Sorting.HeapSort; const assert = require('assert'); describe('HeapSort', () => { it('should have no data when empty initialization', () => { const inst = new HeapSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new HeapSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); it('should sort the array in ascending order with few equal vals', () => { const inst = new HeapSort([2, 1, 3, 4, 2], (a, b) => a < b); assert.equal(inst.size, 5); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]); assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 2, 3, 4'); }); });
/* eslint-env mocha */ const HeapSort = require('../../../src').algorithms.Sorting.HeapSort; const assert = require('assert'); describe('HeapSort', () => { it('should have no data when empty initialization', () => { const inst = new HeapSort(); assert.equal(inst.size, 0); assert.deepEqual(inst.unsortedList, []); assert.deepEqual(inst.sortedList, []); }); it('should sort the array', () => { const inst = new HeapSort([2, 1, 3, 4]); assert.equal(inst.size, 4); assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]); assert.deepEqual(inst.sortedList, [1, 2, 3, 4]); assert.equal(inst.toString(), '1, 2, 3, 4'); }); });
nrf: Update the PCA10056 example to use new pin naming
import board import digitalio import gamepad import time pad = gamepad.GamePad( digitalio.DigitalInOut(board.P0_11), digitalio.DigitalInOut(board.P0_12), digitalio.DigitalInOut(board.P0_24), digitalio.DigitalInOut(board.P0_25), ) prev_buttons = 0 while True: buttons = pad.get_pressed() if buttons != prev_buttons: for i in range(0, 4): bit = (1 << i) if (buttons & bit) != (prev_buttons & bit): print('Button %d %s' % (i + 1, 'pressed' if buttons & bit else 'released')) prev_buttons = buttons time.sleep(0.1)
import board import digitalio import gamepad import time pad = gamepad.GamePad( digitalio.DigitalInOut(board.PA11), digitalio.DigitalInOut(board.PA12), digitalio.DigitalInOut(board.PA24), digitalio.DigitalInOut(board.PA25), ) prev_buttons = 0 while True: buttons = pad.get_pressed() if buttons != prev_buttons: for i in range(0, 4): bit = (1 << i) if (buttons & bit) != (prev_buttons & bit): print('Button %d %s' % (i + 1, 'pressed' if buttons & bit else 'released')) prev_buttons = buttons time.sleep(0.1)
MOX-182: Handle missing external files gracefully
from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) try: response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) except IOError: eis.delete() raise Http404() response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
from email.utils import formatdate from datetime import datetime, timedelta from time import mktime from django.shortcuts import get_object_or_404 from django.http import HttpResponse, Http404 from molly.utils.views import BaseView from molly.utils.breadcrumbs import NullBreadcrumb from models import ExternalImageSized class IndexView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context): raise Http404 class ExternalImageView(BaseView): breadcrumb = NullBreadcrumb def handle_GET(self, request, context, slug): eis = get_object_or_404(ExternalImageSized, slug=slug) response = HttpResponse(open(eis.get_filename(), 'rb').read(), mimetype=eis.content_type.encode('ascii')) response['ETag'] = slug response['Expires'] = formatdate(mktime((datetime.now() + timedelta(days=7)).timetuple())) response['Last-Modified'] = formatdate(mktime(eis.external_image.last_updated.timetuple())) return response
Add Completed Event to Piece Bank
var events = require('events') var banks = {}; module.exports = function(infoHash) { var newObj = {}; newObj.create = function(engine) { banks[engine.infoHash] = { downloaded: 0, total: engine.torrent.pieces.length, ev: new events.EventEmitter(), pieceLength: engine.torrent.pieceLength, map: Array.apply(null, Array(engine.torrent.pieces.length)).map(function () { return false }) }; }; newObj.clear = function() { delete banks[infoHash]; }; newObj.update = function(piece) { banks[infoHash].downloaded++; banks[infoHash].map[piece] = true; if (banks[infoHash].downloaded == banks[infoHash].total) banks[infoHash].ev.emit('completed') }; newObj.filePercent = function(offset, length) { var distance = Math.ceil(length / banks[infoHash].pieceLength); offset = Math.floor(offset / banks[infoHash].pieceLength) -1; var downloaded = 0; for (var i = offset; i <= offset + distance && i < banks[infoHash].total; i++) { if (banks[infoHash].map[i]) downloaded++; } return downloaded / distance; }; newObj.get = function() { return banks[infoHash]; }; return newObj; };
var banks = {}; module.exports = function(infoHash) { var newObj = {}; newObj.create = function(engine) { banks[engine.infoHash] = { downloaded: 0, total: engine.torrent.pieces.length, pieceLength: engine.torrent.pieceLength, map: Array.apply(null, Array(engine.torrent.pieces.length)).map(function () { return false }) }; }; newObj.clear = function() { delete banks[infoHash]; }; newObj.update = function(piece) { banks[infoHash].downloaded++; banks[infoHash].map[piece] = true; }; newObj.filePercent = function(offset, length) { var distance = Math.ceil(length / banks[infoHash].pieceLength); offset = Math.floor(offset / banks[infoHash].pieceLength) -1; var downloaded = 0; for (var i = offset; i <= offset + distance && i < banks[infoHash].total; i++) { if (banks[infoHash].map[i]) downloaded++; } return downloaded / distance; }; newObj.get = function() { return banks[infoHash]; }; return newObj; };
Add param description for index argument
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var logger = require( 'debug' ); var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; // VARIABLES // var debug = logger( 'plot:accessor:is-defined' ); // MAIN // /** * Accessor function which determines whether a datum is defined. * * @private * @param {number} d - datum * @param {integer} i - index * @returns {boolean} boolean indicating whether a datum is defined */ function isDefined( d ) { var bool = !isnan( d ); debug( 'Datum: %s. Defined: %s.', JSON.stringify( d ), bool ); return bool; } // EXPORTS // module.exports = isDefined;
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var logger = require( 'debug' ); var isnan = require( '@stdlib/assert/is-nan' ).isPrimitive; // VARIABLES // var debug = logger( 'plot:accessor:is-defined' ); // MAIN // /** * Accessor function which determines whether a datum is defined. * * @private * @param {number} d - datum * @returns {boolean} boolean indicating whether a datum is defined */ function isDefined( d ) { var bool = !isnan( d ); debug( 'Datum: %s. Defined: %s.', JSON.stringify( d ), bool ); return bool; } // EXPORTS // module.exports = isDefined;
Add recently-created model method to mock model.
<?php if ( ! defined('EXT')) exit('Invalid file request.'); /** * Mock SuperSticky model. * * @author Stephen Lewis (http://github.com/experience/) * @copyright Experience Internet * @package Supersticky */ class Mock_supersticky_model { public function get_package_name() {} public function get_package_theme_url() {} public function get_package_version() {} public function get_site_id() {} public function get_supersticky_entry_by_id($entry_id) {} public function install_module() {} public function install_module_actions() {} public function install_module_register() {} public function install_module_tables() {} public function install_module_tabs() {} public function save_supersticky_entry(Supersticky_entry $entry) {} public function uninstall_module() {} public function update_module($installed_version = '') {} public function update_supersticky_entry_with_post_data( Supersticky_entry $entry) {} } /* End of file : mock.supersticky_model.php */ /* File location : third_party/supersticky/tests/mocks/mock.supersticky_model.php */
<?php if ( ! defined('EXT')) exit('Invalid file request.'); /** * Mock SuperSticky model. * * @author Stephen Lewis (http://github.com/experience/) * @copyright Experience Internet * @package Supersticky */ class Mock_supersticky_model { public function get_package_name() {} public function get_package_theme_url() {} public function get_package_version() {} public function get_site_id() {} public function install_module() {} public function install_module_actions() {} public function install_module_register() {} public function uninstall_module() {} public function update_module($installed_version = '') {} } /* End of file : mock.supersticky_model.php */ /* File location : third_party/supersticky/tests/mocks/mock.supersticky_model.php */
Clean up weak initial position constraints.
var scrollingExample = { box: { id: "clip", className: "clip", children: { id: "image", className: "image" } }, constraints: [ "clip.left == 0", "clip.top == 0", "clip.right == 300", "clip.bottom == 300", // Specify the bounds of the image and hint its position. "image.right == image.left + 800 !strong", "image.bottom == image.top + 800 !strong", "image.left == 0 !weak", "image.top == 0 !weak" ], motionConstraints: [ // Ensure that the image stays within the clip with springs. // XXX: We can't yet express motion constraints relative to other linear variables. [ "image.left", "<=", 0 ],//"clip.left" ], [ "image.top", "<=", 0 ],//"clip.top" ], [ "image.bottom", ">=", 300],//"clip.bottom" ], [ "image.right", ">=", 300]//"clip.right" ], ], manipulators: [ { box: "clip", x: "image.left", y: "image.top" } ] } Slalom.Serialization.assemble(scrollingExample, document.body);
var scrollingExample = { box: { id: "clip", className: "clip", children: { id: "image", className: "image" } }, constraints: [ "clip.left == 0", "clip.top == 0", "clip.right == 300", "clip.bottom == 300", // Specify the bounds of the image and hint its position. "image.right == image.left + 800 !strong", "image.bottom == image.top + 800 !strong", "image.left == 0",// !weak", "image.top == 0",// !weak" ], motionConstraints: [ // Ensure that the image stays within the clip with springs. // XXX: We can't yet express motion constraints relative to other linear variables. [ "image.left", "<=", 0 ],//"clip.left" ], [ "image.top", "<=", 0 ],//"clip.top" ], [ "image.bottom", ">=", 300],//"clip.bottom" ], [ "image.right", ">=", 300]//"clip.right" ], ], manipulators: [ { box: "clip", x: "image.left", y: "image.top" } ] } Slalom.Serialization.assemble(scrollingExample, document.body);
Add custom placeholder for empty value
// @flow export function roundValue(value: number | string | void, placeholder: boolean | void): number | string { if (typeof value !== 'number') { return placeholder ? '—' : ''; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
// @flow export function roundValue(value: number | string | void): number | string { if (typeof value !== 'number') { return '—'; } const parsedValue = parseFloat(value.toString()); const sizes = ['', ' K', ' M', ' G', ' T', ' P', ' E', ' Z', ' Y']; if (parsedValue === 0) { return '0'; } let x = 0; while (Math.pow(1000, x + 1) < Math.abs(parsedValue)) { x++; } let prefix = (parsedValue / Math.pow(1000, x)).toFixed(2).toString(); if (x === 0) { prefix = value.toFixed(2).toString(); } let tailToCut = 0; while (prefix[prefix.length - (tailToCut + 1)] === '0') { tailToCut++; } if (prefix[prefix.length - (tailToCut + 1)] === '.') { tailToCut++; } return prefix.substring(0, prefix.length - tailToCut) + (sizes[x] || ''); } export function getJSONContent(data: { [key: string]: any }): string { return 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2)); }
Switch to runtime.Goexit instead of sync.WaitGroup as goroutines run forever
package main import ( "log" "os" "runtime" "github.com/joho/godotenv" ) func init() { log.Println("Starting RFC-Bot") if err := godotenv.Load(); err != nil { log.Fatal("Error loading .env file") } } func main() { log.Println("Initialising Writers") writer := NewWriter() log.Println("Initialising Twitter") twitter, err := NewTwitter(os.Getenv("TWITTER_CONSUMER_KEY"), os.Getenv("TWITTER_CONSUMER_SECRET"), os.Getenv("TWITTER_ACCESS_TOKEN"), os.Getenv("TWITTER_ACCESS_TOKEN_SECRET")) if err != nil { log.Fatal("Could not authenticate to twitter:", err) } writer.AddWriter(twitter) log.Println("Initialising Readers") go ietfRFC(writer.Wchan) go ietfDraftRFC(writer.Wchan) log.Println("Initialised") runtime.Goexit() }
package main import ( "log" "os" "sync" "github.com/joho/godotenv" ) func init() { log.Println("Starting RFC-Bot") if err := godotenv.Load(); err != nil { log.Fatal("Error loading .env file") } } func main() { log.Println("Initialising Writers") writer := NewWriter() log.Println("Initialising Twitter") twitter, err := NewTwitter(os.Getenv("TWITTER_CONSUMER_KEY"), os.Getenv("TWITTER_CONSUMER_SECRET"), os.Getenv("TWITTER_ACCESS_TOKEN"), os.Getenv("TWITTER_ACCESS_TOKEN_SECRET")) if err != nil { log.Fatal("Could not authenticate to twitter:", err) } writer.AddWriter(twitter) log.Println("Initialising Readers") var wg sync.WaitGroup wg.Add(2) go ietfRFC(writer.Wchan) go ietfDraftRFC(writer.Wchan) log.Println("Initialised") wg.Wait() }
Add a universal option for bindingProviderInstance
// // This becomes ko.options // -- // // This is the root 'options', which must be extended by others. var options = { deferUpdates: false, useOnlyNativeEvents: false, protoProperty: '__ko_proto__', // Modify the default attribute from `data-bind`. defaultBindingAttribute: 'data-bind', // Enable/disable <!-- ko binding: ... -> style bindings allowVirtualElements: true, // Global variables that can be accessed from bindings. bindingGlobals: {}, // An instance of the binding provider. bindingProviderInstance: null, // jQuery will be automatically set to window.jQuery in applyBindings // if it is (strictly equal to) undefined. Set it to false or null to // disable automatically setting jQuery. jQuery: window && window.jQuery, debug: false, onError: function (e) { throw e; }, set: function (name, value) { options[name] = value; } }; Object.defineProperty(options, '$', { get: function () { return options.jQuery; } }); export default options;
// // This becomes ko.options // -- // // This is the root 'options', which must be extended by others. var options = { deferUpdates: false, useOnlyNativeEvents: false, protoProperty: '__ko_proto__', // Modify the default attribute from `data-bind`. defaultBindingAttribute: 'data-bind', // Enable/disable <!-- ko binding: ... -> style bindings allowVirtualElements: true, // Global variables that can be accessed from bindings. bindingGlobals: {}, // jQuery will be automatically set to window.jQuery in applyBindings // if it is (strictly equal to) undefined. Set it to false or null to // disable automatically setting jQuery. jQuery: window && window.jQuery, debug: false, onError: function (e) { throw e; }, set: function (name, value) { options[name] = value; } }; Object.defineProperty(options, '$', { get: function () { return options.jQuery; } }); export default options;
Add site footer to each documentation generator
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-box-sizing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-box-sizing/tachyons-box-sizing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_box-sizing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var siteFooter = fs.readFileSync('./templates/footer.html', 'utf8') var template = fs.readFileSync('./templates/docs/box-sizing/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs, siteFooter: siteFooter }) fs.writeFileSync('./docs/layout/box-sizing/index.html', html)
var _ = require('lodash') var fs = require('fs') var gzip = require('gzip-size') var filesize = require('filesize') var cssstats = require('cssstats') var module = require('tachyons-box-sizing/package.json') var moduleCss = fs.readFileSync('node_modules/tachyons-box-sizing/tachyons-box-sizing.min.css', 'utf8') var moduleObj = cssstats(moduleCss) var moduleSize = filesize(moduleObj.gzipSize) var srcCSS = fs.readFileSync('./src/_box-sizing.css', 'utf8') var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8') var template = fs.readFileSync('./templates/docs/box-sizing/index.html', 'utf8') var tpl = _.template(template) var html = tpl({ moduleVersion: module.version, moduleSize: moduleSize, moduleObj: moduleObj, srcCSS: srcCSS, navDocs: navDocs }) fs.writeFileSync('./docs/layout/box-sizing/index.html', html)
Revise doc string for selection sort’s concept
def selection_sort(a_list): """Selection Sort algortihm. Concept: - Find out the maximun item's original slot first, - then swap it and the item at the max slot. - Iterate the procedure. """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slot + 1): if a_list[slot] > a_list[select_slot]: select_slot = slot temp = a_list[max_slot] a_list[max_slot] = a_list[select_slot] a_list[select_slot] = temp def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: {}'.format(a_list)) print('By selection sort: ') selection_sort(a_list) print(a_list) if __name__ == '__main__': main()
def selection_sort(a_list): """Selection Sort algortihm. Concept: Find out the maximun item's original slot first, then switch it to the max slot. Iterate the procedure. """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slot + 1): if a_list[slot] > a_list[select_slot]: select_slot = slot temp = a_list[max_slot] a_list[max_slot] = a_list[select_slot] a_list[select_slot] = temp def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: {}'.format(a_list)) print('By selection sort: ') selection_sort(a_list) print(a_list) if __name__ == '__main__': main()
Revert "Add podModulePrefix to app blueprint" This reverts commit f6ada104a403e48ae0aa64174a7e5ef1baca0e72.
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: '<%= modulePrefix %>', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: '<%= modulePrefix %>', podModulePrefix: '<%= modulePrefix %>/pods', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
Add spinning animation back in
var config = require('config'); var debug = require('debug')(config.application() + ':otp'); var Profiler = require('otp-profiler'); var spin = require('spinner'); /** * Create profiler */ var profiler = new Profiler({ host: '/api/otp' }); /** * Expose `journey` */ module.exports = function profile(query, callback) { debug('--> profiling %s', JSON.stringify(query)); var spinner = spin(); profiler.profile(query, function(err, data) { if (err || !data) { spinner.remove(); debug('<-- error profiling', err); callback(err); } else { query.profile = data; profiler.journey(query, function(err, journey) { spinner.remove(); if (err) { debug('<-- error profiling', err); callback(err); } else { debug('<-- profiled %s options', data.options.length); callback(null, { journey: journey, options: data.options }); } }); } }); };
var config = require('config'); var debug = require('debug')(config.application() + ':otp'); var Profiler = require('otp-profiler'); var spin = require('spinner'); /** * Create profiler */ var profiler = new Profiler({ host: '/api/otp' }); /** * Expose `journey` */ module.exports = function profile(query, callback) { debug('--> profiling %s', JSON.stringify(query)); var spinner = spin(); profiler.profile(query, function(err, data) { if (err || !data) { spinner.stop(); debug('<-- error profiling', err); callback(err); } else { query.profile = data; profiler.journey(query, function(err, journey) { spinner.stop(); if (err) { debug('<-- error profiling', err); callback(err); } else { debug('<-- profiled %s options', data.options.length); callback(null, { journey: journey, options: data.options }); } }); } }); };
Fix bug in project-specific backbone model mixin
"use strict"; var _ = require('underscore') , Project = require('./project') /* * Mixin for models which require a project to be set. * * Looks for attribute, collection, and explicit passing in options. Will raise * an error if no project is found, or if different projects are found. */ module.exports = { constructor: function (attributes, options) { var candidates, results, slug; candidates = { options: options && options.project, collection: options && options.collection && options.collection.project, attributes: attributes && attributes.project } if (candidates.attributes) { slug = candidates.attributes.url.match(/[^\/]+/g).slice(-1); candidates.attributes = new Project({ name: candidates.attributes.name, slug: slug }); } results = _.chain(candidates).filter(function (p) { return p instanceof Project }); if (!results.value().length) { throw new Error('Must pass a project object, either in options, collection, or attributes.'); } if (results.map(function (p) { return p.get('slug') }).flatten().uniq().value().length > 1) { throw new Error('Two different projects passed.') } // Take the first result this.project = results.first().value(); } }
"use strict"; var _ = require('underscore') , Project = require('./project') /* * Mixin for models which require a project to be set. * * Looks for attribute, collection, and explicit passing in options. Will raise * an error if no project is found, or if different projects are found. */ module.exports = { constructor: function (attributes, options) { var candidates, results, slug; candidates = { options: options && options.project, collection: options && options.collection && options.collection.project, attributes: attributes && attributes.project } if (candidates.attributes) { slug = candidates.attributes.url.match(/[^\/]+/g).slice(-1); candidates.attributes = new Project({ name: candidates.attributes.name, slug: slug }); } results = _.chain(candidates).filter(function (p) { return p instanceof Project }); if (!results.value().length) { throw new Error('Must pass a project object, either in options, collection, or attributes.'); } if (results.map(function (p) { return p.get('slug') }).uniq().value().length > 1) { throw new Error('Two different projects passed. Not possible.') } // Take the first result this.project = results.first().value(); } }
Cover some edge cases in utility funtions
export function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) ).toString(16) ); } export function createEmptyDocument() { return { time: Date.now(), size: 0, textContent: "", content: { type: "doc", content: [ { type: "paragraph", content: [] } ] } }; } export function isEmptyDoc(doc) { return !doc.textContent || !doc.textContent.length; } export function sliceStr(str, from, to) { if (!str) return ""; if (str.length <= from) return ""; if (str.length < to) return str.slice(from, to); if (to) { const newTo = Math.min(Math.max(str.indexOf(" ", to), to), str.length); return str.slice(from, newTo) + (str.length > newTo ? "..." : ""); } return str.slice(from); }
export function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4))) ).toString(16) ); } export function createEmptyDocument() { return { time: Date.now(), size: 0, textContent: "", content: { type: "doc", content: [ { type: "paragraph", content: [] } ] } }; } export function isEmptyDoc(doc) { return !Boolean(doc.textContent.length); } export function sliceStr(str, from, to) { if (str.length <= from) return ""; if (str.length < to) return str.slice(from, to); if (to) { const newTo = Math.min(Math.max(str.indexOf(" ", to), to), str.length); return str.slice(from, newTo) + (str.length > newTo ? "..." : ""); } return str.slice(from); }
GEODE-209: Change subTearDown to destroy process
package com.gemstone.gemfire.test.golden; import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import com.gemstone.gemfire.test.process.ProcessWrapper; import com.gemstone.gemfire.test.junit.categories.IntegrationTest; @Category(IntegrationTest.class) public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase { private static final long timeoutMillis = 1000; private ProcessWrapper process; public void subTearDown() throws Exception { this.process.destroy(); } @Override String problem() { return "This is an extra line"; } @Override void outputProblemInProcess(final String message) { System.out.println(message); } /** * Process output has an extra line and should fail */ @Test public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception { this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass()); this.process.execute(createProperties()); this.process.waitForOutputToMatch("Begin " + name() + "\\.main"); try { this.process.waitForOutputToMatch(problem()); fail("assertOutputMatchesGoldenFile should have failed due to " + problem()); } catch (AssertionError expected) { assertTrue(expected.getMessage().contains(problem())); } } public static void main(String[] args) throws Exception { new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess(); } }
package com.gemstone.gemfire.test.golden; import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import com.gemstone.gemfire.test.process.ProcessWrapper; import com.gemstone.gemfire.test.junit.categories.IntegrationTest; @Category(IntegrationTest.class) public class FailWithTimeoutOfWaitForOutputToMatchJUnitTest extends FailOutputTestCase { private static final long timeoutMillis = 1000; private ProcessWrapper process; public void subTearDown() throws Exception { this.process.waitFor(); assertFalse(this.process.isAlive()); } @Override String problem() { return "This is an extra line"; } @Override void outputProblemInProcess(final String message) { System.out.println(message); } /** * Process output has an extra line and should fail */ @Test public void testFailWithTimeoutOfWaitForOutputToMatch() throws Exception { this.process = createProcessWrapper(new ProcessWrapper.Builder().timeoutMillis(timeoutMillis), getClass()); this.process.execute(createProperties()); this.process.waitForOutputToMatch("Begin " + name() + "\\.main"); try { this.process.waitForOutputToMatch(problem()); fail("assertOutputMatchesGoldenFile should have failed due to " + problem()); } catch (AssertionError expected) { assertTrue(expected.getMessage().contains(problem())); } } public static void main(String[] args) throws Exception { new FailWithTimeoutOfWaitForOutputToMatchJUnitTest().executeInProcess(); } }
Make live queries read only
import { operationType } from 'orbit-common/lib/operations'; import ReadOnlyArrayProxy from 'ember-orbit/system/read-only-array-proxy'; export default ReadOnlyArrayProxy.extend({ _orbitCache: null, _query: null, _identityMap: null, init() { this._super(); const orbitCache = this.get('_orbitCache'); const query = this.get('_query'); this.set('content', []); const orbitLiveQuery = orbitCache.liveQuery(query); orbitLiveQuery.subscribe((operation) => { const handler = `_${operationType(operation)}`; if (!this[handler]) return; this[handler](operation); }); }, _addRecord(operation) { const record = this._recordFor(operation); this.get('content').pushObject(record); }, _removeRecord(operation) { const record = this._recordFor(operation); this.get('content').removeObject(record); }, _recordFor(operation) { const identityMap = this.get('_identityMap'); const [type, id] = operation.path; const record = identityMap.lookup({id, type}); return record; } });
import { operationType } from 'orbit-common/lib/operations'; export default Ember.ArrayProxy.extend({ _orbitCache: null, _query: null, _identityMap: null, init() { this._super(); const orbitCache = this.get('_orbitCache'); const query = this.get('_query'); this.set('content', []); const orbitLiveQuery = orbitCache.liveQuery(query); orbitLiveQuery.subscribe((operation) => { const handler = `_${operationType(operation)}`; if (!this[handler]) return; this[handler](operation); }); }, _addRecord(operation) { const record = this._recordFor(operation); this.get('content').pushObject(record); }, _removeRecord(operation) { const record = this._recordFor(operation); this.get('content').removeObject(record); }, _recordFor(operation) { const identityMap = this.get('_identityMap'); const [type, id] = operation.path; const record = identityMap.lookup({id, type}); return record; } });
Fix the datalogger example script to use roll mode and a high decimation
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku('192.168.1.104') i = m.discover_instrument() if i is None or i.type != 'oscilloscope': print "No or wrong instrument deployed" i = Oscilloscope() m.attach_instrument(i) else: print "Attached to existing Oscilloscope" i.set_defaults() i.decimation_rate = 5e6 # 100Hz i.set_xmode(OSC_ROLL) i.commit() i.datalogger_start(1) while True: time.sleep(1) s = i.datalogger_status() b = i.datalogger_transferred() print "Status %d (%d samples)" % (s, b) # TODO: Symbolic constants if s == 0 or s == 7: break i.datalogger_stop() m.close()
from pymoku import Moku from pymoku.instruments import * import time, logging logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku('192.168.1.117') i = m.discover_instrument() if i is None or i.type != 'oscilloscope': print "No or wrong instrument deployed" i = Oscilloscope() m.attach_instrument(i) else: print "Attached to existing Oscilloscope" i.set_defaults() i.datalogger_start(1) while True: time.sleep(1) s = i.datalogger_status() b = i.datalogger_transferred() print "Status %d (%d samples)" % (s, b) # TODO: Symbolic constants if s == 0 or s == 7: break i.datalogger_stop() m.close()
Add empty line to the end of file.
package com.cisco.trex.stateless.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class RPCResponseError { @JsonProperty("code") private Integer code; @JsonProperty("message") private String message; @JsonProperty("specific_err") private String specificErr; @JsonProperty("code") public Integer getCode() { return code; } @JsonProperty("code") public void setCode(Integer code) { this.code = code; } @JsonProperty("message") public String getMessage() { return message; } @JsonProperty("message") public void setMessage(String message) { this.message = message; } @JsonProperty("specific_err") public String getSpecificErr() { return specificErr; } @JsonProperty("specific_err") public void setSpecificErr(String specificErr) { this.specificErr = specificErr; } }
package com.cisco.trex.stateless.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class RPCResponseError { @JsonProperty("code") private Integer code; @JsonProperty("message") private String message; @JsonProperty("specific_err") private String specificErr; @JsonProperty("code") public Integer getCode() { return code; } @JsonProperty("code") public void setCode(Integer code) { this.code = code; } @JsonProperty("message") public String getMessage() { return message; } @JsonProperty("message") public void setMessage(String message) { this.message = message; } @JsonProperty("specific_err") public String getSpecificErr() { return specificErr; } @JsonProperty("specific_err") public void setSpecificErr(String specificErr) { this.specificErr = specificErr; } }
Fix for date convert not traversing arrays
/* jshint maxdepth:5 */ 'use strict'; var _ = require('underscore'); module.exports = function convertDateStrings(kontx, next){ kontx.args = convertDates( kontx.args ); next(); }; function isNumber(number) { return !isNaN(parseFloat(number)) && isFinite(number); } function convertDates( obj ){ var dateTest, monthTest; _.each(obj, function(value, key) { if ( Object === value.constructor || Array === value.constructor ) { convertDates( value ); } else { if ( !isNumber( value ) && !_.isBoolean( value )) { dateTest = new Date( value ); monthTest = dateTest.getMonth() + 1; if ( !_.isNaN( monthTest ) ) { obj[key] = dateTest; } } } }); return obj; }
/* jshint maxdepth:4 */ 'use strict'; var _ = require('underscore'); module.exports = function convertDateStrings(kontx, next){ kontx.args = convertDates( kontx.args ); next(); }; function isNumber(number) { return !isNaN(parseFloat(number)) && isFinite(number); } function convertDates( obj ){ var dateTest, monthTest; for ( var property in obj ) { if ( obj.hasOwnProperty( property ) ) { if ( obj[ property ].constructor == Object ) { convertDates( obj[ property ] ); } else { if ( !isNumber( obj[property] ) && !_.isBoolean( obj[property] )) { dateTest = new Date( obj[ property ] ); monthTest = dateTest.getMonth() + 1; if ( !_.isNaN( monthTest ) ) { obj[ property ] = dateTest; } } } } } return obj; }
ember: Generalize regex for meta tag config replacement
#!/usr/bin/env node const fs = require('fs'); const newConfig = require('./config.json'); const filename = '/code/dist/index.html'; const page = fs.readFileSync(filename, {encoding: 'utf8'}); const rawConfig = /<meta name=".+?\/config\/environment" content="(.+?)"\W*\/?>/.exec(page)[1]; const config = JSON.parse(unescape(rawConfig)); // Deep merge, overrides config with newConfig recursively (function deepMerge(newObj, oldObj) { for (const [key, val] of Object.entries(newObj)) { if (val && typeof val === 'object' && !Array.isArray(val)) { deepMerge(val, oldObj[key]); } else { oldObj[key] = newObj[key]; } } })(newConfig, config); // Stringify and escape the new config const updatedConfig = escape(JSON.stringify(config)); // Replace the old config on the page with the new config const updatedPage = page.replace(rawConfig, updatedConfig); // Write out the file fs.writeFileSync(filename, updatedPage);
#!/usr/bin/env node const fs = require('fs'); const newConfig = require('./config.json'); const filename = '/code/dist/index.html'; const page = fs.readFileSync(filename, {encoding: 'utf8'}); const rawConfig = /<meta name=".+?\/config\/environment" content="(.+?)" \/>/.exec(page)[1]; const config = JSON.parse(unescape(rawConfig)); // Deep merge, overrides config with newConfig recursively (function deepMerge(newObj, oldObj) { for (const [key, val] of Object.entries(newObj)) { if (val && typeof val === 'object' && !Array.isArray(val)) { deepMerge(val, oldObj[key]); } else { oldObj[key] = newObj[key]; } } })(newConfig, config); // Stringify and escape the new config const updatedConfig = escape(JSON.stringify(config)); // Replace the old config on the page with the new config const updatedPage = page.replace(rawConfig, updatedConfig); // Write out the file fs.writeFileSync(filename, updatedPage);
Revert "Fixed a bug where you can not change the path freely"
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with the CLI serve command to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. * */ // @codeCoverageIgnoreStart // Avoid this file run when listing commands if (php_sapi_name() === 'cli') { return; } // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // Front Controller path - expected to be in the default folder $fcpath = realpath(__DIR__ . '/../../../public') . DIRECTORY_SEPARATOR; // Full path $path = $fcpath . ltrim($uri, '/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. require_once $fcpath . 'index.php'; // @codeCoverageIgnoreEnd
<?php /** * CodeIgniter PHP-Development Server Rewrite Rules * * This script works with the CLI serve command to help run a seamless * development server based around PHP's built-in development * server. This file simply tries to mimic Apache's mod_rewrite * functionality so the site will operate as normal. * */ // @codeCoverageIgnoreStart // Avoid this file run when listing commands if (php_sapi_name() === 'cli') { return; } // If we're serving the site locally, then we need // to let the application know that we're in development mode $_SERVER['CI_ENVIRONMENT'] = 'development'; $uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); // Front Controller path - expected to be in the default folder $fcpath = FCPATH; // Full path $path = $fcpath . ltrim($uri, '/'); // If $path is an existing file or folder within the public folder // then let the request handle it like normal. if ($uri !== '/' && (is_file($path) || is_dir($path))) { return false; } // Otherwise, we'll load the index file and let // the framework handle the request from here. require_once $fcpath . 'index.php'; // @codeCoverageIgnoreEnd
Remove stale MD5 reference in mt digest help Specific digest function is not relevant. Closes #10517. PiperOrigin-RevId: 287990399
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.ssd; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionsBase; /** * Options that tune Bazel's performance in order to increase performance on workstations with an * SSD. */ public class SsdOptions extends OptionsBase { @Option( name = "experimental_multi_threaded_digest", defaultValue = "true", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, help = "Whether to always compute digests of files with multiple threads. Setting this to " + "false may improve performance when using a spinning platter.") public boolean experimentalMultiThreadedDigest; }
// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.ssd; import com.google.devtools.common.options.Option; import com.google.devtools.common.options.OptionDocumentationCategory; import com.google.devtools.common.options.OptionEffectTag; import com.google.devtools.common.options.OptionsBase; /** * Options that tune Bazel's performance in order to increase performance on workstations with an * SSD. */ public class SsdOptions extends OptionsBase { @Option( name = "experimental_multi_threaded_digest", defaultValue = "true", documentationCategory = OptionDocumentationCategory.UNCATEGORIZED, effectTags = {OptionEffectTag.UNKNOWN}, help = "Whether to always compute MD5 digests of files with multiple threads. Setting this to " + "false may improve performance when using a spinning platter.") public boolean experimentalMultiThreadedDigest; }
Move along, nothing to see here.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Template </title> <link rel="shortcut icon" href="/includes/img/kp.ico"> <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet"> <link href="/includes/css/style.css" rel="stylesheet"> <script src="/includes/js/konami.js"> var easter_egg = new Konami(function() { alert('Konami code!')}); easter_egg.load(); </script> </head> <body> <?php include 'includes/php/header.php'; ?> <div class="container"> <div class="row"> <h1> Page content </h1> <p> This be your page content... </p> </div> </div> <?php include 'includes/php/footer.php'; ?> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Template </title> <link rel="shortcut icon" href="/includes/img/kp.ico"> <link href="/includes/css/bootstrap.min.css" rel="stylesheet" type="text/css"/> <link href="/includes/css/flat-ui-pro.min.css" rel="stylesheet"> <link href="/includes/css/style.css" rel="stylesheet"> <link href="/includes/js/konami.js"> <script> var easter_egg = new Konami(function() { alert('Konami code!')}); easter_egg.load(); </script> </head> <body> <?php include 'includes/php/header.php'; ?> <div class="container"> <div class="row"> <h1> Page content </h1> <p> This be your page content... </p> </div> </div> <?php include 'includes/php/footer.php'; ?> </body> </html>
Swap over to using fateBus.
// Install the configuration interface and set default values require('configuration.js'); // Use DIM styling overrides and our own custom styling require('beautification.js'); // Stores weapons pulled from our custom database require('weaponDatabase.js'); // Pulls down weapon data and broadcasts updates require('weaponDataRefresher.js'); // Removes DIM's native tagging elements require('dimTagRemover.js'); // Store original details about the weapon in 'data-fate' attributes require('weaponDecorator.js'); // Update weapon comments from our database require('commentDecorator.js'); // Rejigger how weapons with legendary mods are displayed require('modIndicator.js'); // Show higher/lower dupes require('dupeIndicator.js'); /* The nicest change-refresh flow means loading the development version of the script from Tampermonkey while editing. This lets us skip kicking off the app when running under Karma. */ if (!window.navigator.userAgent.includes('HeadlessChrome')) { const logger = require('logger'); logger.log('main.js: Initializing'); fateBus.publish(module, 'fate.init'); setInterval(function() { fateBus.publish(module, 'fate.refresh'); }, 5000); setInterval(function() { fateBus.publish(module, 'fate.weaponDataStale'); }, 30000); }
// Install the configuration interface and set default values require('configuration.js'); // Use DIM styling overrides and our own custom styling require('beautification.js'); // Stores weapons pulled from our custom database require('weaponDatabase.js'); // Pulls down weapon data and broadcasts updates require('weaponDataRefresher.js'); // Removes DIM's native tagging elements require('dimTagRemover.js'); // Store original details about the weapon in 'data-fate' attributes require('weaponDecorator.js'); // Update weapon comments from our database require('commentDecorator.js'); // Rejigger how weapons with legendary mods are displayed require('modIndicator.js'); // Show higher/lower dupes require('dupeIndicator.js'); /* The nicest change-refresh flow means loading the development version of the script from Tampermonkey while editing. This lets us skip kicking off the app when running under Karma. */ if (!window.navigator.userAgent.includes('HeadlessChrome')) { // const logger = require('logger'); // const postal = require('postal'); // logger.log('main.js: Initializing'); // postal.publish({topic:'fate.init'}); // // setInterval(function() { // postal.publish({topic:'fate.refresh'}); // }, 5000); // // setInterval(function() { // postal.publish({topic:'fate.weaponDataStale'}); // }, 30000); }
Add bower_components to the default excludes.
var fs = require('fs-extra'); var assign = require('lodash-node/modern').assign; var union = require('lodash-node/modern').union; var defaults = { // build options source: '.', destination: '_site', excludeFiles: [], includeFiles: [], // e.g. .htaccess // timezone timezone: 'America/Los_Angeles', // environment options env: 'production', // template options partialsDirectory: '_partials', layoutsDirectory: '_layouts', // plugin options pluginDirectory: '_plugins', excludePlugins: [], // post options postTypes: ['post'], excerptLength: 40, includeDrafts: false, // page options permalink: '/:title', // taxonomy options taxonomyTypes: [], // serve options port: 4000, watch: false, watchExcludes: [] }; function Config(options) { assign(this, defaults); this.set(options || {}); } Config.prototype.set = function(options) { assign(this, options); // make sure certain files are always excluded this.excludeFiles = union( this.excludeFiles, [ '.*', '_*', '_*/**/*', 'package.json', 'bower_components', 'node_modules' ] ); // make sure certain directories are never watched this.watchExcludes = union( this.watchExcludes, ['node_modules', this.destination] ); } module.exports = Config
var fs = require('fs-extra'); var assign = require('lodash-node/modern').assign; var union = require('lodash-node/modern').union; var defaults = { // build options source: '.', destination: '_site', excludeFiles: [], includeFiles: [], // e.g. .htaccess // timezone timezone: 'America/Los_Angeles', // environment options env: 'production', // template options partialsDirectory: '_partials', layoutsDirectory: '_layouts', // plugin options pluginDirectory: '_plugins', excludePlugins: [], // post options postTypes: ['post'], excerptLength: 40, includeDrafts: false, // page options permalink: '/:title', // taxonomy options taxonomyTypes: [], // serve options port: 4000, watch: false, watchExcludes: [] }; function Config(options) { assign(this, defaults); if (typeof options == 'object') this.set(options); } Config.prototype.set = function(options) { assign(this, options); // make sure certain files are always excluded this.excludeFiles = union( this.excludeFiles, [ '_*', '_*/**/*', 'package.json', 'node_modules/**/*' ] ); // make sure certain directories are never watched this.watchExcludes = union( this.watchExcludes, ['node_modules', this.destination] ); } module.exports = Config
Fix usage of id instead of _id
const assert = require('assert'); const chai = require('chai'); const chaiHttp = require('chai-http'); const app = require('../../../src/app'); chai.use(chaiHttp); describe('link service', () => { const service = app.service('link'); it('registered the links service', () => { assert.ok(service); }); it(`generates a link of length ${service.Model.linkLength} that has the correct target set`, function test() { this.timeout(10000); const url = 'https://schul-cloud.org/'; return service.create({ target: url }) .then((data) => { chai.expect(data._id).to.have.lengthOf(service.Model.linkLength); chai.expect(data.target).to.equal(url); return Promise.resolve(data._id); }) .then((id) => new Promise((resolve, reject) => { chai.request(app) .get(`/link/${id}`) .end((error, result) => { if (error) return reject(error); chai.expect(result.redirects[0]).to.equal(url); return resolve(); }); })); }); });
const assert = require('assert'); const chai = require('chai'); const chaiHttp = require('chai-http'); const app = require('../../../src/app'); chai.use(chaiHttp); describe('link service', () => { const service = app.service('link'); it('registered the links service', () => { assert.ok(service); }); it(`generates a link of length ${service.Model.linkLength} that has the correct target set`, function () { this.timeout(10000); const url = 'https://schul-cloud.org/'; return service.create({ target: url }) .then((data) => { chai.expect(data.id).to.have.lengthOf(service.Model.linkLength); chai.expect(data.target).to.equal(url); return Promise.resolve(data.id); }) .then((id) => new Promise((resolve, reject) => { chai.request(app) .get(`/link/${id}`) .end((error, result) => { if (error) return reject(error); chai.expect(result.redirects[0]).to.equal(url); resolve(); }); })); }); });
Use query instead of params (from router), and set up events instead of pointless delegate.
var app = require('ridge'); var FormView = require('ridge/views/form'); module.exports = FormView.extend({ events: { 'submit': 'submit' }, submit: function(e) { e.preventDefault(); var query = []; _.each(this.$el.prop('elements'), function(elem) { if (elem.name && elem.value) query.push(encodeURIComponent(elem.name) + '=' + encodeURIComponent(elem.value).replace('%20', '+')); }); var url = '/' + Backbone.history.fragment.split('?')[0]; if (query.length) url += '?' + query.join('&'); Backbone.history.navigate(url, { trigger: true }); }, initialize: function() { this.listenTo(this.state, 'change:query', this.attach); }, attach: function(model, value) { var query = this.state.get('query'); _.each(this.$el.prop('elements'), function(elem) { if (elem.name) $(elem).val(query[elem.name]).trigger('change'); }); } });
var app = require('ridge'); var FormView = require('ridge/views/form'); module.exports = FormView.extend({ submit: function(e) { e.preventDefault(); var query = []; _.each(this.$el.prop('elements'), function(elem) { if (elem.name && elem.value) query.push(encodeURIComponent(elem.name) + '=' + encodeURIComponent(elem.value).replace('%20', '+')); }); var url = '/' + Backbone.history.fragment.split('?')[0]; if (query.length) url += '?' + query.join('&'); Backbone.history.navigate(url, { trigger: true }); }, initialize: function() { this.listenTo(this.state, 'change:query', this.attach); this.delegate('submit', this.submit.bind(this)); }, attach: function() { var params = this.state.get('params'); _.each(this.$el.prop('elements'), function(elem) { if (elem.name) $(elem).val(params[elem.name]).trigger('change'); }); } });
feat: Change default audio state to play sound
import settings from 'electron-settings'; import { SET_APP_SETTINGS, SET_AUDIO_OFF, SET_AUDIO_ON, SET_ELECTRON_SETTINGS } from './types'; const initialState = { audioDisabled: false }; export default (state = initialState, action) => { switch (action.type) { case SET_APP_SETTINGS: { const { data } = action; return { ...data }; } case SET_AUDIO_OFF: { return { ...state, audioDisabled: true }; } case SET_AUDIO_ON: { return { ...state, audioDisabled: false }; } case SET_ELECTRON_SETTINGS: { const { keyPath, value, options } = action; settings.set(keyPath, value, options); return { ...state }; } default: { return state; } } };
import settings from 'electron-settings'; import { SET_APP_SETTINGS, SET_AUDIO_OFF, SET_AUDIO_ON, SET_ELECTRON_SETTINGS } from './types'; const initialState = { audioDisabled: true }; export default (state = initialState, action) => { switch (action.type) { case SET_APP_SETTINGS: { const { data } = action; return { ...data }; } case SET_AUDIO_OFF: { return { ...state, audioDisabled: true }; } case SET_AUDIO_ON: { return { ...state, audioDisabled: false }; } case SET_ELECTRON_SETTINGS: { const { keyPath, value, options } = action; settings.set(keyPath, value, options); return { ...state }; } default: { return state; } } };
Update IP address of kafka consumer
#!/usr/bin/env python import threading, logging, time from kafka import KafkaConsumer class Consumer(threading.Thread): daemon = True def run(self): consumer = KafkaConsumer(bootstrap_servers='10.100.198.220:9092', #consumer = KafkaConsumer(bootstrap_servers='10.0.2.15:9092', auto_offset_reset='earliest') consumer.subscribe(['voltha-heartbeat']) for message in consumer: print (message) def main(): threads = [ Consumer() ] for t in threads: t.start() time.sleep(3000) if __name__ == "__main__": logging.basicConfig( format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s', level=logging.INFO ) main()
#!/usr/bin/env python import threading, logging, time from kafka import KafkaConsumer class Consumer(threading.Thread): daemon = True def run(self): #consumer = KafkaConsumer(bootstrap_servers='10.100.198.220:9092', consumer = KafkaConsumer(bootstrap_servers='10.0.2.15:9092', auto_offset_reset='earliest') consumer.subscribe(['voltha-heartbeat']) for message in consumer: print (message) def main(): threads = [ Consumer() ] for t in threads: t.start() time.sleep(3000) if __name__ == "__main__": logging.basicConfig( format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s', level=logging.INFO ) main()
Clean up, Clean up, Clean up!
function string_to_color(str,options){this.hash=function(word){var h=0;for(var i=0;i<word.length;i++)h=word.charCodeAt(i)+((h<<5)-h);return h};this.shade=function(color,prc){var num=parseInt(color,16),amt=Math.round(2.55*prc),R=(num>>16)+amt,G=(num>>8&255)+amt,B=(num&255)+amt;return(16777216+(R<255?R<1?0:R:255)*65536+(G<255?G<1?0:G:255)*256+(B<255?B<1?0:B:255)).toString(16).slice(1)};this.int_to_rgba=function(i){var color=(i>>24&255).toString(16)+(i>>16&255).toString(16)+(i>>8&255).toString(16)+(i& 255).toString(16);return color};return this.shade(this.int_to_rgba(this.hash(str)),-10)};
function string_to_color(str,options){this.hash=function(str){var h=0;for(var i=0;i<str.length;i++)h=str.charCodeAt(i)+((h<<5)-h);return h};this.shade=function(color,percent){var num=parseInt(color,16),amt=Math.round(2.55*percent),R=(num>>16)+amt,G=(num>>8&255)+amt,B=(num&255)+amt;return(16777216+(R<255?R<1?0:R:255)*65536+(G<255?G<1?0:G:255)*256+(B<255?B<1?0:B:255)).toString(16).slice(1)};this.int_to_rgba=function(i){var color=(i>>24&255).toString(16)+(i>>16&255).toString(16)+(i>>8&255).toString(16)+ (i&255).toString(16);return color};return this.shade(this.int_to_rgba(this.hash(str)),-10)};
[Android] Fix the context issue to let content create windows Content Layer needs getSystemService to get window manager. And it should be created from Activity.
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.runtime; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; /** * MixContext provides ApplicationContext for the contextImpl object * created by Context.CreatePackageContext(). * * For cross package usage, the library part need the possibility to * get both the application's context and the library itself's context. * */ public class MixContext extends ContextWrapper { private Context mActivityCtx; public MixContext(Context base, Context activity) { super(base); mActivityCtx = activity; } @Override public Context getApplicationContext() { return mActivityCtx.getApplicationContext(); } @Override public boolean bindService(Intent in, ServiceConnection conn, int flags) { return getApplicationContext().bindService(in, conn, flags); } @Override public void unbindService(ServiceConnection conn) { getApplicationContext().unbindService(conn); } @Override public Object getSystemService(String name) { return mActivityCtx.getSystemService(name); } }
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.xwalk.runtime; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; /** * MixContext provides ApplicationContext for the contextImpl object * created by Context.CreatePackageContext(). * * For cross package usage, the library part need the possibility to * get both the application's context and the library itself's context. * */ public class MixContext extends ContextWrapper { private Context mAppCtx; public MixContext(Context base, Context app) { super(base); mAppCtx = app.getApplicationContext(); } @Override public Context getApplicationContext() { return mAppCtx; } @Override public boolean bindService(Intent in, ServiceConnection conn, int flags) { return mAppCtx.bindService(in, conn, flags); } @Override public void unbindService(ServiceConnection conn) { mAppCtx.unbindService(conn); } }
Move Data Portal / Other to bottom of contact select
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ('Data Portal / Other', 'data@nhm.ac.uk'), ])
#!/usr/bin/env python # encoding: utf-8 # # This file is part of ckanext-nhm # Created by the Natural History Museum in London, UK from collections import OrderedDict # the order here matters as the default option should always be first in the dict so that it is # automatically selected in combo boxes that use this list as a source for options COLLECTION_CONTACTS = OrderedDict([ ('Data Portal / Other', 'data@nhm.ac.uk'), ('Algae, Fungi & Plants', 'm.carine@nhm.ac.uk'), ('Economic & Environmental Earth Sciences', 'g.miller@nhm.ac.uk'), ('Fossil Invertebrates & Plants', 'z.hughes@nhm.ac.uk'), ('Fossil Vertebrates & Anthropology', 'm.richter@nhm.ac.uk'), ('Insects', 'g.broad@nhm.ac.uk'), ('Invertebrates', 'm.lowe@nhm.ac.uk'), ('Library & Archives', 'library@nhm.ac.uk'), ('Mineral & Planetary Sciences', 'm.rumsey@nhm.ac.uk'), ('Vertebrates', 'simon.loader@nhm.ac.uk'), ])
Move top-level imports from v0 to v1.
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from .v1 import Broker, Header, ALL, temp, temp_config from .utils import (lookup_config, list_configs, describe_configs, wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct) from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog # A catalog created from discovered entrypoints and v0 catalogs. catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog()]) # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions ### Legacy imports ### try: from .databroker import DataBroker except ImportError: pass else: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images
# Import intake to run driver discovery first and avoid circular import issues. import intake del intake import warnings import logging logger = logging.getLogger(__name__) from ._core import (Broker, BrokerES, Header, ALL, lookup_config, list_configs, describe_configs, temp_config, wrap_in_doct, DeprecatedDoct, wrap_in_deprecated_doct) from .discovery import MergedCatalog, EntrypointsCatalog, V0Catalog # A catalog created from discovered entrypoints and v0 catalogs. catalog = MergedCatalog([EntrypointsCatalog(), V0Catalog()]) # set version string using versioneer from ._version import get_versions __version__ = get_versions()['version'] del get_versions ### Legacy imports ### try: from .databroker import DataBroker except ImportError: pass else: from .databroker import (DataBroker, DataBroker as db, get_events, get_table, stream, get_fields, restream, process) from .pims_readers import get_images
Use parseInt() instead of valueOf() It's more efficient to just use parseInt() instead of box then unbox the value.
package de.markusfisch.android.shadereditor.opengl; public class InfoLog { private static String message; private static int errorLine; public static String getMessage() { return message; } public static int getErrorLine() { return errorLine; } public static void parse( String infoLog ) { message = null; errorLine = 0; if( infoLog == null ) return; int from; if( (from = infoLog.indexOf( "ERROR: 0:" )) > -1 ) from += 9; else if( (from = infoLog.indexOf( "0:" )) > -1 ) from += 2; if( from > -1 ) { int to; if( (to = infoLog.indexOf( ":", from )) > -1 ) { try { errorLine = Integer.parseInt( infoLog.substring( from, to ).trim() ); } catch( NumberFormatException e ) { // can't do anything about it } catch( NullPointerException e ) { // can't do anything about it } from = ++to; } if( (to = infoLog.indexOf( "\n", from )) < 0 ) to = infoLog.length(); infoLog = infoLog.substring( from, to ).trim(); } message = infoLog; } }
package de.markusfisch.android.shadereditor.opengl; public class InfoLog { private static String message; private static int errorLine; public static String getMessage() { return message; } public static int getErrorLine() { return errorLine; } public static void parse( String infoLog ) { message = null; errorLine = 0; if( infoLog == null ) return; int from; if( (from = infoLog.indexOf( "ERROR: 0:" )) > -1 ) from += 9; else if( (from = infoLog.indexOf( "0:" )) > -1 ) from += 2; if( from > -1 ) { int to; if( (to = infoLog.indexOf( ":", from )) > -1 ) { try { errorLine = Integer.valueOf( infoLog.substring( from, to ).trim() ); } catch( NumberFormatException e ) { // can't do anything about it } catch( NullPointerException e ) { // can't do anything about it } from = ++to; } if( (to = infoLog.indexOf( "\n", from )) < 0 ) to = infoLog.length(); infoLog = infoLog.substring( from, to ).trim(); } message = infoLog; } }
Fix array notation in function
<?php $app = []; $app['config'] = [ 'db' => [ 'dsn' => 'mysql:dbname=foler;host=localhost', 'user' => 'foler', 'password' => '' ], 'url' => $_SERVER['PHP_SELF'], 'debug' => false ]; if($app['config']['debug']): error_reporting(E_ALL); ini_set('display_errors', 1); endif; $app['locale'] = 'en'; /** * Helps us split codes to associative array * * @param type $string * @param type $value * @param array $arr */ function joinStringToArr($string, $value, &$arr = []) { $keys = explode('.', $string); $ref = &$arr; while ($key = array_shift($keys)) { $ref = &$ref[$key]; } $ref = $value; }
<?php $app = []; $app['config'] = [ 'db' => [ 'dsn' => 'mysql:dbname=foler;host=localhost', 'user' => 'foler', 'password' => '' ], 'url' => $_SERVER['PHP_SELF'], 'debug' => false ]; if($app['config']['debug']): error_reporting(E_ALL); ini_set('display_errors', 1); endif; $app['locale'] = 'en'; /** * Helps us split codes to associative array * * @param type $string * @param type $value * @param array $arr */ function joinStringToArr($string, $value, &$arr = array()) { $keys = explode('.', $string); $ref = &$arr; while ($key = array_shift($keys)) { $ref = &$ref[$key]; } $ref = $value; }
Support RSS path without trailing slash
package com.tidyjava.bp.rss; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; @Controller public class RssController { @Autowired private RssFeedGenerator rssFeedGenerator; @RequestMapping(path = "/rss", produces = APPLICATION_XML_VALUE) @ResponseBody public String rss() throws Exception { SyndFeed feed = rssFeedGenerator.generate(); return new SyndFeedOutput().outputString(feed); } }
package com.tidyjava.bp.rss; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; @Controller public class RssController { @Autowired private RssFeedGenerator rssFeedGenerator; @RequestMapping(path = "/rss/", produces = APPLICATION_XML_VALUE) @ResponseBody public String rss() throws Exception { SyndFeed feed = rssFeedGenerator.generate(); return new SyndFeedOutput().outputString(feed); } }
Remove return type since it's missing from the parent
<?php namespace Drupal\wmcontroller; use Drupal\Component\Plugin\Factory\FactoryInterface; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Plugin\DefaultPluginManager; use Drupal\wmcontroller\Annotation\Controller; class ControllerPluginManager extends DefaultPluginManager { public function __construct( \Traversable $namespaces, CacheBackendInterface $cacheBackend, ModuleHandlerInterface $moduleHandler ) { parent::__construct( 'Controller', $namespaces, $moduleHandler, null, Controller::class ); $this->alterInfo('wmcontroller_controller_info'); $this->setCacheBackend($cacheBackend, 'wmcontroller_controller_info'); } protected function getFactory() { if (!$this->factory) { $this->factory = new ControllerPluginFactory($this, $this->pluginInterface); } return $this->factory; } }
<?php namespace Drupal\wmcontroller; use Drupal\Component\Plugin\Factory\FactoryInterface; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Plugin\DefaultPluginManager; use Drupal\wmcontroller\Annotation\Controller; class ControllerPluginManager extends DefaultPluginManager { public function __construct( \Traversable $namespaces, CacheBackendInterface $cacheBackend, ModuleHandlerInterface $moduleHandler ) { parent::__construct( 'Controller', $namespaces, $moduleHandler, null, Controller::class ); $this->alterInfo('wmcontroller_controller_info'); $this->setCacheBackend($cacheBackend, 'wmcontroller_controller_info'); } protected function getFactory(): FactoryInterface { if (!$this->factory) { $this->factory = new ControllerPluginFactory($this, $this->pluginInterface); } return $this->factory; } }
Add fixes for inflector and tests
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; final class StringInflector { public static function nameToCode(string $value): string { return str_replace([' ', '-', '\''], '_', $value); } public static function nameToSlug(string $value): string { return str_replace(['_'], '-', StringInflector::nameToLowercaseCode($value)); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } private function __construct() { } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Formatter; final class StringInflector { public static function nameToCode(string $value): string { return str_replace([' ', '-', '\''], '_', $value); } public static function nameToSlug(string $value): string { return str_replace([' '], '-', strtolower($value)); } public static function nameToLowercaseCode(string $value): string { return strtolower(self::nameToCode($value)); } public static function nameToUppercaseCode(string $value): string { return strtoupper(self::nameToCode($value)); } private function __construct() { } }
Set default variables at start of function
var hslToHex = require('tie-dye/hslToHex'); function hashbow(input, saturation, lightness) { var toColor, sum; saturation = saturation || 100; lightness = lightness || 50; switch (typeof input) { case 'object': toColor = JSON.stringify(input); break; case 'number': sum = input; break; case 'boolean': return hslToHex(input ? 120 : 0, saturation, lightness); break; case 'function': toColor = input.toString(); break; case 'string': default: toColor = input; } if (sum === null) { sum = 0; toColor.split('').forEach(function (letter) { sum += letter.charCodeAt(0); }); } sum = Math.abs(sum * sum); return hslToHex(sum % 360, saturation, lightness); } module.exports = hashbow;
var hslToHex = require('tie-dye/hslToHex'); function hashbow(input, saturation, lightness) { var toColor, sum; var toColor, sum; switch (typeof input) { case 'object': toColor = JSON.stringify(input); break; case 'number': sum = input; break; case 'boolean': return hslToHex(input ? 120 : 0, saturation || 100, lightness || 50); break; case 'function': toColor = input.toString(); break; case 'string': default: toColor = input; } if (sum === null) { sum = 0; toColor.split('').forEach(function (letter) { sum += letter.charCodeAt(0); }); } sum = Math.abs(sum * sum); var color = hslToHex(sum % 360, saturation || 100, lightness || 50); return color; } module.exports = hashbow;
Fix using preload-webpack-plugin, not resource-hints-plugin
const config = require('./config'); const pwaOptions = require('./pwaConfig'); const PUBLIC_PATH = config.PUBLIC_PATH; /** * optional plugins enabled by enabling their recipe. * once enabled they succeed being required and get added to plugin list. * order them in the order they should be added to the plugin lists. */ const optionalPlugins = [ { recipe: 'hints', name: 'preload-webpack-plugin', prodOnly: false, }, { recipe: 'pwa', name: 'favicons-webpack-plugin', prodOnly: false, options: pwaOptions, }, { recipe: 'visualizer', name: 'webpack-visualizer-plugin', prodOnly: false, options: { filename: '../bundle_weight_report.html', }, }, { recipe: 'optimize', name: 'optimize-js-plugin', prodOnly: true, options: { sourceMap: false, }, }, { recipe: 'offline', name: 'offline-plugin', prodOnly: true, options: { relativePaths: false, AppCache: false, ServiceWorker: { events: true, }, publicPath: PUBLIC_PATH, caches: 'all', }, }, ]; module.exports = optionalPlugins;
const config = require('./config'); const pwaOptions = require('./pwaConfig'); const PUBLIC_PATH = config.PUBLIC_PATH; /** * optional plugins enabled by enabling their recipe. * once enabled they succeed being required and get added to plugin list. * order them in the order they should be added to the plugin lists. */ const optionalPlugins = [ { recipe: 'hints', name: 'resource-hints-webpack-plugin', prodOnly: false, }, { recipe: 'pwa', name: 'favicons-webpack-plugin', prodOnly: false, options: pwaOptions, }, { recipe: 'visualizer', name: 'webpack-visualizer-plugin', prodOnly: false, options: { filename: '../bundle_weight_report.html', }, }, { recipe: 'optimize', name: 'optimize-js-plugin', prodOnly: true, options: { sourceMap: false, }, }, { recipe: 'offline', name: 'offline-plugin', prodOnly: true, options: { relativePaths: false, AppCache: false, ServiceWorker: { events: true, }, publicPath: PUBLIC_PATH, caches: 'all', }, }, ]; module.exports = optionalPlugins;
Watch element files in Vulcanize watch task
'use strict'; import cache from 'gulp-cached'; import gulp from 'gulp'; import remember from 'gulp-remember'; import size from 'gulp-size'; import vulcanize from 'gulp-vulcanize'; import {config, browserSync} from './_config.babel.js'; let sourceFiles = `${config.path.source.elements}/elements.html`; sourceFiles = sourceFiles.concat(config.files.source.elements); gulp.task('vulcanize', () => { return gulp.src(`${config.path.source.elements}/elements.html`) .pipe(vulcanize({ stripComments: true, inlineCss: true, inlineScripts: true })) .pipe(gulp.dest(config.path.destination.elements)) .pipe(size({title: 'vulcanize'})); }); gulp.task('vulcanize:watch', ['browser-sync'], () => { let watcher = gulp.watch(sourceFiles, ['vulcanize']); watcher.on('change', (event) => { browserSync.reload(); if (event.type === 'deleted') { // if a file is deleted, forget about it delete cache.caches.vulcanize[event.path]; remember.forget('vulcanize', event.path); } }); });
'use strict'; import gulp from 'gulp'; import size from 'gulp-size'; import vulcanize from 'gulp-vulcanize'; import {config, browserSync} from './_config.babel.js'; let sourceFiles = `${config.path.source.elements}/elements.html`; gulp.task('vulcanize', () => { return gulp.src(sourceFiles) .pipe(vulcanize({ stripComments: true, inlineCss: true, inlineScripts: true })) .pipe(gulp.dest(config.path.destination.elements)) .pipe(size({title: 'vulcanize'})); }); gulp.task('vulcanize:watch', ['browser-sync'], () => { let watcher = gulp.watch(sourceFiles, ['vulcanize']); watcher.on('change', (event) => { browserSync.reload(); if (event.type === 'deleted') { // if a file is deleted, forget about it delete cache.caches.vulcanize[event.path]; remember.forget('vulcanize', event.path); } }); });
Make icon easier to debug
import styled from 'styled-components'; import icons, { map } from './helpers/icons'; const Icon = styled.i.withConfig({ displayName: 'Icon' })` font-family: 'Bandwidth'; font-size: ${({ theme, size }) => `${size}px` || theme.icon.fontSize}; color: inherit; font-style: normal; display: inline-block; &::before { content: "${({ name, iconsHelper }) => iconsHelper(name) || iconsHelper('help_2')}"; display: block; color: inherit; } `; Icon.defaultProps = { theme: { icon: { fontSize: '16px', fg: 'inherit' }, }, name: 'attention', iconsHelper: icons, size: 16, }; Icon.usage = ` # Icon Icons let you easily render some of our icons. Pass in the \`name\` prop to specify which one. \`\`\` <Icon name="checkmark" /> \`\`\` ## Icons The icon definition file is in \`components/helpers/icons.js\` ${Object.keys(map).map((name) => `* ${name}`).join('\n')} `; export default Icon;
import styled from 'styled-components'; import icons, { map } from './helpers/icons'; const Icon = styled.i.withConfig({ displayName: 'Icon' })` font-family: 'Bandwidth'; font-size: ${({ theme, size }) => `${size}px` || theme.icon.fontSize}; color: inherit; font-style: normal; display: inline-block; &::before { content: "${({ name, iconsHelper }) => iconsHelper(name)}"; display: block; color: inherit; } `; Icon.defaultProps = { theme: { icon: { fontSize: '16px', fg: 'inherit' }, }, name: 'attention', iconsHelper: icons, size: 16, }; Icon.usage = ` # Icon Icons let you easily render some of our icons. Pass in the \`name\` prop to specify which one. \`\`\` <Icon name="checkmark" /> \`\`\` ## Icons The icon definition file is in \`components/helpers/icons.js\` ${Object.keys(map).map((name) => `* ${name}`).join('\n')} `; export default Icon;
Use statistics logger in example app
package main import ( "flag" "io/ioutil" "log" "os" "os/signal" "strings" "github.com/localhots/satan" "github.com/localhots/satan/example/daemons" "github.com/localhots/satan/example/kafka" "github.com/localhots/satan/stats" ) func main() { var debug bool var brokers string flag.BoolVar(&debug, "v", false, "Verbose mode") flag.StringVar(&brokers, "brokers", "127.0.0.1:9092", "Kafka broker addresses separated by space") flag.Parse() log.SetOutput(ioutil.Discard) if debug { log.SetOutput(os.Stderr) } kafka.Initialize(strings.Split(brokers, " ")) defer kafka.Shutdown() logger := stats.NewStdoutLogger(0) defer logger.Print() s := satan.Summon() s.SubscribeFunc = kafka.Subscribe s.Statistics = logger s.AddDaemon(&daemons.NumberPrinter{}) s.AddDaemon(&daemons.PriceConsumer{}) s.StartDaemons() defer s.StopDaemons() sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) <-sig }
package main import ( "flag" "io/ioutil" "log" "os" "os/signal" "strings" "github.com/localhots/satan" "github.com/localhots/satan/example/daemons" "github.com/localhots/satan/example/kafka" ) func main() { var debug bool var brokers string flag.BoolVar(&debug, "v", false, "Verbose mode") flag.StringVar(&brokers, "brokers", "127.0.0.1:9092", "Kafka broker addresses separated by space") flag.Parse() log.SetOutput(ioutil.Discard) if debug { log.SetOutput(os.Stderr) } kafka.Initialize(strings.Split(brokers, " ")) defer kafka.Shutdown() s := satan.Summon() s.SubscribeFunc = kafka.Subscribe s.AddDaemon(&daemons.NumberPrinter{}) s.AddDaemon(&daemons.PriceConsumer{}) s.StartDaemons() defer s.StopDaemons() sig := make(chan os.Signal) signal.Notify(sig, os.Interrupt) <-sig }
fix(ipc): Set default activity state better when load activities
import ACTIVITIY_STATUS from './activityStatus' const IPCAdapter = require('electron-ipc-adapter') const ipcRenderer = window.require('electron').ipcRenderer class ClientIPCAdapter extends IPCAdapter { constructor (ipcRenderer) { super(ipcRenderer.send.bind(ipcRenderer), ipcRenderer.on.bind(ipcRenderer)) } getHubs () { return this.ask('getHubs').then((response) => response.hubs) } getActivities (hubUuid) { return Promise.all([ this.ask('getActivities', { hubUuid }), this.ask('getCurrentActivityForHub', { hubUuid }) ]) .then((results) => { const activities = results[0].activities const currentActivityId = results[1].activityId return activities.map((activity) => { if (activity.id !== '-1' && activity.id === currentActivityId) { activity.activityStatus = ACTIVITIY_STATUS.STARTED } else { activity.activityStatus = ACTIVITIY_STATUS.OFF } return activity }) }) } startActivityForHub (activityId, hubUuid) { return this.tell('startActivityForHub', { hubUuid, activityId }) } } const ipcAdapter = new ClientIPCAdapter(ipcRenderer) export default ipcAdapter
import ACTIVITIY_STATUS from './activityStatus' const IPCAdapter = require('electron-ipc-adapter') const ipcRenderer = window.require('electron').ipcRenderer class ClientIPCAdapter extends IPCAdapter { constructor (ipcRenderer) { super(ipcRenderer.send.bind(ipcRenderer), ipcRenderer.on.bind(ipcRenderer)) } getHubs () { return this.ask('getHubs').then((response) => response.hubs) } getActivities (hubUuid) { return Promise.all([ this.ask('getActivities', { hubUuid }), this.ask('getCurrentActivityForHub', { hubUuid }) ]) .then((results) => { const activities = results[0].activities const currentActivityId = results[1].activityId return activities.map((activity) => { if (activity.id === currentActivityId) { activity.activityStatus = ACTIVITIY_STATUS.STARTED } else { activity.activityStatus = ACTIVITIY_STATUS.OFF } return activity }) }) } startActivityForHub (activityId, hubUuid) { return this.tell('startActivityForHub', { hubUuid, activityId }) } } const ipcAdapter = new ClientIPCAdapter(ipcRenderer) export default ipcAdapter
Add helper function createData() which prepare data for the client to send it to server
angular.module('sparrow') .controller('TimedCtrl', function() { //data is the information send when a template is added. this.data= {}; this.userId = 'xyz'; //workout contain template created by user. this.workout = []; //addWorkout() create a template of named workout this.addWorkout = function() { var obj = {}; obj.activity = this.activity; obj.duration = Number(this.minutes || 0) * 60 + Number(this.seconds || 0); obj.sets = ''; obj.reps = ''; this.workout.push(obj); }; //addTemplate add template to the database. this.sendTemplate = function() { this.createData(); console.log('Send present workout to the database via http services',this.data); }; this.createData = function() { this.data.userId = this.userId; this.data.workout = this.workout; this.data.templateName = this.templateName; this.data.timed = true; }; }) .component('timed', { controller: 'TimedCtrl', templateUrl: 'templates/timed.html' });
angular.module('sparrow') .controller('TimedCtrl', function() { //data is the information send when a template is added. this.data= {}; this.userId = 'xyz'; //workout contain template created by user. this.workout = []; //addWorkout() create a template of named workout this.addWorkout = function() { var obj = {}; obj.activity = this.activity; obj.duration = Number(this.minutes || 0) * 60 + Number(this.seconds || 0); obj.sets = ''; obj.reps = ''; this.workout.push(obj); this.createData(); }; //addTemplate add template to the database. this.sendTemplate = function() { console.log('Send present workout to the database via http services',this.data); }; }) .component('timed', { controller: 'TimedCtrl', templateUrl: 'templates/timed.html' });
Fix exception from require('mdns') if Avahi detection fails with an unexpected error It can also fail e.g. with kDNSServiceErr_ServiceNotRunning (at least on Windows).
var dns_sd = require('./dns_sd'); function supportsInterfaceIndexLocalOnly() { try { var sr = new dns_sd.DNSServiceRef() , flags = 0 , iface = dns_sd.kDNSServiceInterfaceIndexLocalOnly , name = null , type = '_http._tcp' , domain = null , host = null , port = 4321 , txtRec = null , cb = null , ctx = null ; dns_sd.DNSServiceRegister( sr, flags, iface, name, type, domain, host, port, txtRec, cb, ctx); } catch (ex) { if (ex.errorCode === dns_sd.kDNSServiceErr_Unsupported) { if (sr && sr.initialized) { dns_sd.DNSServiceRefDeallocate(sr); } return false; } console.warn('Unexpected result while probing for avahi:', ex); } if (sr && sr.initialized) { dns_sd.DNSServiceRefDeallocate(sr); } return true; } module.exports = ! supportsInterfaceIndexLocalOnly();
var dns_sd = require('./dns_sd'); function supportsInterfaceIndexLocalOnly() { try { var sr = new dns_sd.DNSServiceRef() , flags = 0 , iface = dns_sd.kDNSServiceInterfaceIndexLocalOnly , name = null , type = '_http._tcp' , domain = null , host = null , port = 4321 , txtRec = null , cb = null , ctx = null ; dns_sd.DNSServiceRegister( sr, flags, iface, name, type, domain, host, port, txtRec, cb, ctx); } catch (ex) { if (ex.errorCode === dns_sd.kDNSServiceErr_Unsupported) { if (sr && sr.initialized) { dns_sd.DNSServiceRefDeallocate(sr); } return false; } console.warn('Unexpected result while probing for avahi:', ex); } dns_sd.DNSServiceRefDeallocate(sr); return true; } module.exports = ! supportsInterfaceIndexLocalOnly();
Use the mocha runner again.
/* global process */ import {Controller as Main} from './main-controller'; import {getShortcutObject, metaKey} from './_util'; import {shortcuts as aceDefaultShortcuts} from './_aceDefaultShortcuts'; import StartUp from './startup'; import {xhrGet} from './_external-deps/xhr.js'; import KataUrl from './kata-url.js'; const onSave = () => main.onSave(); const shortcuts = aceDefaultShortcuts.concat([ getShortcutObject([metaKey, 'S'], onSave, 'Save+Run') ]); const appDomNode = document.getElementById('tddbin'); var main = new Main(appDomNode, { iframeSrcUrl: `./mocha/spec-runner.html`, shortcuts: shortcuts }); const withSourceCode = (sourceCode) => { main.setEditorContent(sourceCode); setTimeout(onSave, 1000); }; const kataName = 'es5/mocha+assert/assert-api'; export const DEFAULT_KATA_URL = `http://${process.env.KATAS_SERVICE_DOMAIN}/katas/${kataName}.js`; var xhrGetDefaultKata = xhrGet.bind(null, DEFAULT_KATA_URL); const startUp = new StartUp(xhrGet, xhrGetDefaultKata); const queryString = window.location.hash.replace(/^#\?/, ''); var kataUrl = KataUrl.fromQueryString(queryString); startUp.loadSourceCode(kataUrl, withSourceCode);
/* global process */ import {Controller as Main} from './main-controller'; import {getShortcutObject, metaKey} from './_util'; import {shortcuts as aceDefaultShortcuts} from './_aceDefaultShortcuts'; import StartUp from './startup'; import {xhrGet} from './_external-deps/xhr.js'; import KataUrl from './kata-url.js'; const onSave = () => main.onSave(); const shortcuts = aceDefaultShortcuts.concat([ getShortcutObject([metaKey, 'S'], onSave, 'Save+Run') ]); const appDomNode = document.getElementById('tddbin'); var main = new Main(appDomNode, { iframeSrcUrl: `./katas/spec-runner.html`, shortcuts: shortcuts }); const withSourceCode = (sourceCode) => { main.setEditorContent(sourceCode); setTimeout(onSave, 1000); }; const kataName = 'es5/mocha+assert/assert-api'; export const DEFAULT_KATA_URL = `http://${process.env.KATAS_SERVICE_DOMAIN}/katas/${kataName}.js`; var xhrGetDefaultKata = xhrGet.bind(null, DEFAULT_KATA_URL); const startUp = new StartUp(xhrGet, xhrGetDefaultKata); const queryString = window.location.hash.replace(/^#\?/, ''); var kataUrl = KataUrl.fromQueryString(queryString); startUp.loadSourceCode(kataUrl, withSourceCode);
Replace for-in call w/ Object.keys call to determine object length
//Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual. function deepEqual(x, y) { if (isObject(x) && isObject(y) && areSameLength(x, y)) { return Object.keys(x).every((key) => { return y.hasOwnProperty(key) ? deepEqual(x[key], y[key]) : false; }); } return (x === y); }; function isObject(value) { return typeof value === 'object' && value !== null; } function areSameLength(x, y) { return Object.keys(x).length === Object.keys(y).length; } const obj = {here: {is: "an"}, object: 2}; console.log(deepEqual(obj, obj)); console.log(deepEqual(obj, {here: 1, object: 2})); console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
//Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual. function deepEqual(x, y) { if (isObject(x) && isObject(y) && areSameLength(x, y)) { return Object.keys(x).every((key) => { return y.hasOwnProperty(key) ? deepEqual(x[key], y[key]) : false; }); } return (x === y); }; function isObject(value) { return typeof value === 'object' && value !== null; } function areSameLength(x, y) { let lengthX = 0; let lengthY = 0; for (let prop in x) { lengthX++; } for (let prop in y) { lengthY++; } return (lengthX === lengthY); } const obj = {here: {is: "an"}, object: 2}; console.log(deepEqual(obj, obj)); console.log(deepEqual(obj, {here: 1, object: 2})); console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
Refactor get_alpha() to make it faster Computations of alpha using for loop are very slow. I switch to usage of element-wise numpy functions to make get_alpha() function faster.
from wenohj.solver import Solver import numpy as np import matplotlib.pyplot as plt def get_alpha(x, t, u, u_x_plus, u_x_minus): f1 = np.abs(u_x_plus + 1.0) f2 = np.abs(u_x_minus + 1.0) return np.maximum(f1, f2) def flux(x, t, u, u_x): return (u_x + 1)**2 / 2.0 lb = -1.0 rb = 1.0 ncells = 320 T = 3.5 / np.pi**2 s = Solver(lb, rb, ncells, flux, get_alpha, 'periodic', cfl=0.1) x = s.get_x() u0 = -np.cos(np.pi * x) solution = s.solve(u0, T) plt.plot(x, solution) plt.show()
from wenohj.solver import Solver import numpy as np import matplotlib.pyplot as plt def get_alpha(x, t, u, u_x_plus, u_x_minus): max = np.zeros_like(x) for i in range(len(x)): if np.abs(u_x_plus[i] + 1.0) > np.abs(u_x_minus[i] + 1.0): max[i] = np.abs(u_x_plus[i] + 1.0) else: max[i] = np.abs(u_x_minus[i] + 1.0) return max def flux(x, t, u, u_x): return (u_x + 1)**2 / 2.0 lb = -1.0 rb = 1.0 ncells = 320 T = 3.5 / np.pi**2 s = Solver(lb, rb, ncells, flux, get_alpha, 'periodic', cfl=0.1) x = s.get_x() u0 = -np.cos(np.pi * x) solution = s.solve(u0, T) plt.plot(x, solution) plt.show()
Set celery max tasks child to 1
import os import logging from celery import Celery from temp_config.set_environment import DeployEnv runtime_env = DeployEnv() runtime_env.load_deployment_environment() redis_server = os.environ.get('REDIS_HOSTNAME') redis_port = os.environ.get('REDIS_PORT') celery_tasks = [ 'hms_flask.modules.hms_controller', 'pram_flask.tasks' ] redis = 'redis://' + redis_server + ':' + redis_port + '/0' logging.info("Celery connecting to redis server: " + redis) celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks) celery.conf.update( CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', CELERY_IGNORE_RESULT=True, CELERY_TRACK_STARTED=True, worker_max_tasks_per_child = 1, worker_max_memory_per_child = 50000 )
import os import logging from celery import Celery from temp_config.set_environment import DeployEnv runtime_env = DeployEnv() runtime_env.load_deployment_environment() redis_server = os.environ.get('REDIS_HOSTNAME') redis_port = os.environ.get('REDIS_PORT') celery_tasks = [ 'hms_flask.modules.hms_controller', 'pram_flask.tasks' ] redis = 'redis://' + redis_server + ':' + redis_port + '/0' logging.info("Celery connecting to redis server: " + redis) celery = Celery('flask_qed', broker=redis, backend=redis, include=celery_tasks) celery.conf.update( CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', CELERY_IGNORE_RESULT=True, CELERY_TRACK_STARTED=True, worker_max_memory_per_child = 50000 )
Set service objects can be null.
<?php /** * Encapsulation of model manipulation and business rules */ abstract class Jaded_Service { /** * Singleton instances of services */ protected static $aInstances = array(); //////////////////////////////////////////////////////////////////////////////// // PUBLIC STATIC ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** * Returns an instance of the requested service * @param string $sType * @return Jaded_Service * @throws Jaded_Service_Exception if the type requested is an invalid service */ public static function instance($sType) { if (empty(self::$aInstances[$sType])) { if (!is_subclass_of($sType, __CLASS__)) { throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType); } self::set($sType, new $sType()); } return self::$aInstances[$sType]; } /** * Set a service instance * @param string $sType * @param Jaded_Service $oService */ public static function set($sType, $oService) { if ($oService !== null && !($oService instanceof __CLASS__)) { throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType); } self::$aInstances[$sType] = $oService; } }
<?php /** * Encapsulation of model manipulation and business rules */ abstract class Jaded_Service { /** * Singleton instances of services */ protected static $aInstances = array(); //////////////////////////////////////////////////////////////////////////////// // PUBLIC STATIC ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /** * Returns an instance of the requested service * @param string $sType * @return Jaded_Service * @throws Jaded_Service_Exception if the type requested is an invalid service */ public static function instance($sType) { if (empty(self::$aInstances[$sType])) { if (!is_subclass_of($sType, __CLASS__)) { throw new Jaded_Service_Exception("Invalid Service type [{$sType}]", Jaded_Service_Exception::InvalidType); } self::set($sType, new $sType()); } return self::$aInstances[$sType]; } /** * Set a service instance * @param string $sType * @param Jaded_Service $oService */ public static function set($sType, Jaded_Service $oService) { self::$aInstances[$sType] = $oService; } }
Fix companies path in Chamber of Deputies dataset test
import shutil import os from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): self.temp_path = mkdtemp() fixtures = os.path.join('rosie', 'chamber_of_deputies', 'tests', 'fixtures') copies = ( ('companies.xz', Adapter.COMPANIES_DATASET), ('reimbursements.xz', 'reimbursements.xz') ) for source, target in copies: copy2(os.path.join(fixtures, source), os.path.join(self.temp_path, target)) self.subject = Adapter(self.temp_path) def tearDown(self): shutil.rmtree(self.temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, fetch, ceap): self.assertEqual(5, len(self.subject.dataset)) self.assertEqual(1, self.subject.dataset['legal_entity'].isnull().sum())
import os.path from tempfile import mkdtemp from unittest import TestCase from unittest.mock import patch from shutil import copy2 from rosie.chamber_of_deputies import settings from rosie.chamber_of_deputies.adapter import Adapter class TestDataset(TestCase): def setUp(self): temp_path = mkdtemp() copy2('rosie/chamber_of_deputies/tests/fixtures/companies.xz', os.path.join(temp_path, settings.COMPANIES_DATASET)) copy2('rosie/chamber_of_deputies/tests/fixtures/reimbursements.xz', temp_path) self.subject = Adapter(temp_path) @patch('rosie.chamber_of_deputies.adapter.CEAPDataset') @patch('rosie.chamber_of_deputies.adapter.fetch') def test_get_performs_a_left_merge_between_reimbursements_and_companies(self, _ceap_dataset, _fetch): dataset = self.subject.dataset() self.assertEqual(5, len(dataset)) self.assertEqual(1, dataset['legal_entity'].isnull().sum())
duck: Fix so it actually throws the ducked exception Signed-off-by: BJ Hargrave <3d26bb3930946e3370762d769a073cece444c2d8@bjhargrave.com>
package aQute.lib.exceptions; public class Exceptions { private Exceptions() {} public static RuntimeException duck(Throwable t) { Exceptions.<RuntimeException> throwsUnchecked(t); throw new AssertionError("unreachable"); } @SuppressWarnings("unchecked") private static <E extends Throwable> void throwsUnchecked(Throwable throwable) throws E { throw (E) throwable; } public static Runnable wrap(final RunnableWithException run) { return new Runnable() { @Override public void run() { try { run.run(); } catch (Exception e) { throw duck(e); } } }; } public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) { return new org.osgi.util.function.Function<T,R>() { @Override public R apply(T value) { try { return run.apply(value); } catch (Exception e) { throw duck(e); } } }; } }
package aQute.lib.exceptions; public class Exceptions { static RuntimeException singleton = new RuntimeException(); public static RuntimeException duck(Throwable t) { Exceptions.<RuntimeException> asUncheckedException0(t); return singleton; } @SuppressWarnings("unchecked") private static <E extends Throwable> E asUncheckedException0(Throwable throwable) throws E { return (E) throwable; } public static Runnable wrap(final RunnableWithException run) { return new Runnable() { @Override public void run() { try { run.run(); } catch (Exception e) { duck(e); } } }; } public static <T, R> org.osgi.util.function.Function<T,R> wrap(final FunctionWithException<T,R> run) { return new org.osgi.util.function.Function<T,R>() { @Override public R apply(T value) { try { return run.apply(value); } catch (Exception e) { duck(e); return null; // will never happen } } }; } }
Fix and add ddsc-site urls.
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst. from __future__ import print_function, unicode_literals from __future__ import absolute_import, division from rest_framework.reverse import reverse from rest_framework.views import APIView from rest_framework.response import Response class Root(APIView): def get(self, request, format=None): response = { 'datasets': reverse('dataset-list', request=request), 'locations': reverse('location-list', request=request), 'timeseries': reverse('timeseries-list', request=request), 'parameters': reverse('parameter-list', request=request), 'layers': reverse('layer-list', request=request), 'collages': reverse('collage-list', request=request), } user = getattr(request, 'user', None) if user is not None and user.is_superuser: response.update({ 'users': reverse('user-list', request=request), 'groups': reverse('usergroup-list', request=request), 'roles': reverse('role-list', request=request), }) return Response(response)
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst. from __future__ import print_function, unicode_literals from __future__ import absolute_import, division from rest_framework.reverse import reverse from rest_framework.views import APIView from rest_framework.response import Response class Root(APIView): def get(self, request, format=None): response = { 'datasets': reverse('dataset-list', request=request), 'locations': reverse('location-list', request=request), 'timeseries': reverse('timeseries-list', request=request), 'parameters': reverse('parameter-list', request=request), 'layers': reverse('layers-list', request=request), } user = getattr(request, 'user', None) if user is not None and user.is_superuser: response.update({ 'users': reverse('user-list', request=request), 'groups': reverse('usergroup-list', request=request), 'roles': reverse('role-list', request=request), }) return Response(response)
XWIKI-7161: Add support for classifier in Maven/Aether repository handler Set proper dependency id
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.aether.internal; import org.sonatype.aether.graph.Dependency; import org.xwiki.extension.AbstractExtensionDependency; public class AetherExtensionDependency extends AbstractExtensionDependency { private Dependency aetherDependency; public AetherExtensionDependency(Dependency aetherDependency) { super(AetherUtils.createExtensionId(aetherDependency.getArtifact()).getId(), aetherDependency.getArtifact() .getVersion()); } public Dependency getAetherDependency() { return this.aetherDependency; } }
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.repository.aether.internal; import org.sonatype.aether.graph.Dependency; import org.xwiki.extension.AbstractExtensionDependency; public class AetherExtensionDependency extends AbstractExtensionDependency { private Dependency aetherDependency; public AetherExtensionDependency(Dependency aetherDependency) { super(aetherDependency.getArtifact().getGroupId() + ':' + aetherDependency.getArtifact().getArtifactId(), aetherDependency.getArtifact().getVersion()); } public Dependency getAetherDependency() { return this.aetherDependency; } }
Fix Travis tests not failing with AUTOLOAD=0
#!/usr/bin/env php <?php chdir(dirname(__FILE__)); $autoload = (int)$argv[1]; $returnStatus = null; $composerOriginalRaw = file_get_contents('composer.json'); if (!$autoload) { // Modify composer to not autoload WonderPush $composer = json_decode($composerOriginalRaw, true); unset($composer['autoload']); file_put_contents('composer.json', json_encode($composer)); } passthru('composer install', $returnStatus); if (!$autoload) { // Revert rewrite file_put_contents('composer.json', $composerOriginalRaw); } if ($returnStatus !== 0) { exit(1); } $config = $autoload ? 'phpunit.xml' : 'phpunit.no_autoload.xml'; passthru("./vendor/bin/phpunit -c $config", $returnStatus); if (!$autoload) { // Revert autoloader modifications made earlier passthru('composer dump-autoload'); } if ($returnStatus !== 0) { exit(1); }
#!/usr/bin/env php <?php chdir(dirname(__FILE__)); $autoload = (int)$argv[1]; $returnStatus = null; $composerOriginalRaw = file_get_contents('composer.json'); if (!$autoload) { // Modify composer to not autoload WonderPush $composer = json_decode($composerOriginalRaw, true); unset($composer['autoload']); file_put_contents('composer.json', json_encode($composer)); } passthru('composer install', $returnStatus); if (!$autoload) { // Revert rewrite file_put_contents('composer.json', $composerOriginalRaw); } if ($returnStatus !== 0) { exit(1); } $config = $autoload ? 'phpunit.xml' : 'phpunit.no_autoload.xml'; passthru("./vendor/bin/phpunit -c $config", $returnStatus); if (!$autoload) { // Revert autoloader modifications made earlier passthru('composer dump-autoload', $returnStatus); } if ($returnStatus !== 0) { exit(1); }
Add second argument to render() method of markdown parser
"use strict"; var resolveItemText = require('./resolve_item_text') , makeInlineCitation = require('./make_inline_citation') , makeBibliographyEntry = require('./make_bibliography_entry') , formatItems = require('./format_items') , getCSLItems = require('./csl_from_documents') module.exports = function renderTemplate(opts, cslEngine) { var itemsByID = formatItems(opts) , cslItems , parser cslItems = getCSLItems(itemsByID.document) cslEngine.sys.items = cslItems; cslEngine.updateItems(Object.keys(cslItems), true); parser = require('editorsnotes-markup-parser')({ projectBaseURL: opts.projectBaseURL, resolveItemText: resolveItemText.bind(null, itemsByID), makeInlineCitation: makeInlineCitation.bind(null, cslEngine), makeBibliographyEntry: makeBibliographyEntry.bind(null, cslEngine) }); return parser.render(opts.data, {}); }
"use strict"; var resolveItemText = require('./resolve_item_text') , makeInlineCitation = require('./make_inline_citation') , makeBibliographyEntry = require('./make_bibliography_entry') , formatItems = require('./format_items') , getCSLItems = require('./csl_from_documents') module.exports = function renderTemplate(opts, cslEngine) { var itemsByID = formatItems(opts) , cslItems , parser cslItems = getCSLItems(itemsByID.document) cslEngine.sys.items = cslItems; cslEngine.updateItems(Object.keys(cslItems), true); parser = require('editorsnotes-markup-parser')({ projectBaseURL: opts.projectBaseURL, resolveItemText: resolveItemText.bind(null, itemsByID), makeInlineCitation: makeInlineCitation.bind(null, cslEngine), makeBibliographyEntry: makeBibliographyEntry.bind(null, cslEngine) }); return parser.render(opts.data); }
Use super() and self within the Cipher and Caesar classes
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = self._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(self._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): super().__init__("d")
import math import secrets from string import ascii_lowercase class Cipher(object): def __init__(self, key=None): if not key: key = Cipher._random_key() if not key.isalpha() or not key.islower(): raise ValueError("Key must consist only of lowercase letters") self.key = key self._key = [ord(k)-97 for k in key] def encode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, k) for c, k in zip(chars, key)) def decode(self, s): key = self._key * math.ceil(len(s)/len(self._key)) chars = [c for c in s.lower() if c in ascii_lowercase] return "".join(Cipher._shift(c, -k) for c, k in zip(chars, key)) @staticmethod def _shift(char, key): return chr(97 + ((ord(char) - 97 + key) % 26)) @staticmethod def _random_key(length=256): return "".join(secrets.choice(ascii_lowercase) for _ in range(length)) class Caesar(Cipher): def __init__(self): Cipher.__init__(self, "d")
Use insert for now to salt the passwords
var async = require('async') var mongoose = require('mongoose') var schema = require('../server/schema') var jobs = process.argv.slice(2) var fixtureData = readFixtureData() mongoose.connect('mongodb://localhost/meku') async.series([demoUsers, demoAccounts], function(err) { mongoose.disconnect(function() { console.log('> All done: ', err ? err : 'OK') }) }) function readFixtureData() { var env = process.env.NODE_ENV || 'development' return require('./data.' + env) } function demoUsers(callback) { async.forEach(fixtureData.users, function(u, callback) { new schema.User(u).save(callback) }, callback) } function demoAccounts(callback) { async.each(fixtureData.accounts, function(a, callback) { async.map(a.users, function(username, callback) { schema.User.findOne({ username: username }, null, function(err, user) { if (err) return callback(err) return callback(null, {_id: user._id, name: user.username}) }) }, function(err, users) { if (err) return callback(err) a.users = users new schema.Account(a).save(callback) }) }, callback) }
var async = require('async') var mongoose = require('mongoose') var schema = require('../server/schema') var jobs = process.argv.slice(2) var fixtureData = readFixtureData() mongoose.connect('mongodb://localhost/meku') async.series([demoUsers, demoAccounts], function(err) { mongoose.disconnect(function() { console.log('> All done: ', err ? err : 'OK') }) }) function readFixtureData() { var env = process.env.NODE_ENV || 'development' return require('./data.' + env) } function demoUsers(callback) { async.forEach(fixtureData.users, function(u, callback) { schema.User.update({username: u.username}, u, {upsert: true}, callback) }, callback) } function demoAccounts(callback) { async.each(fixtureData.accounts, function(a, callback) { async.map(a.users, function(username, callback) { schema.User.findOne({ username: username }, null, function(err, user) { if (err) return callback(err) return callback(null, {_id: user._id, name: user.username}) }) }, function(err, users) { if (err) return callback(err) a.users = users new schema.Account(a).save(callback) }) }, callback) }