text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Load dist css file in example
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import 'eagle.js/dist/eagle.css' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import Router from 'vue-router' import App from './App' import Home from './Home' import Eagle from 'eagle.js' import slideshows from './slideshows/slideshows.js' /* eslint-disable no-new */ Vue.use(Eagle) Vue.use(Router) var routes = [] slideshows.list.forEach(function (slideshow) { routes.push({ path: '/' + slideshow.infos.path, component: slideshow }) }) routes.push({ path: '*', component: Home }) routes.push({ path: '/', name: 'Home', component: Home }) console.log(routes) var router = new Router({ routes // hashbang: true // mode: 'history' }) new Vue({ el: '#app', router, template: '<App/>', components: { App } })
Add godoc string and debug flag parsing
// This is gotify, a lightweight Spotify player written in Go package main import ( "flag" "fmt" "github.com/adrien-f/gotify/config" sp "github.com/op/go-libspotify" ) func Ascii() { fmt.Println(" _ _ __") fmt.Println(" __ _ ___ | |_(_)/ _|_ _") fmt.Println(" / _` |/ _ \\| __| | |_| | | |") fmt.Println("| (_| | (_) | |_| | _| |_| |") fmt.Println(" \\__, |\\___/ \\__|_|_| \\__, |") fmt.Println(" |___/ |___/") fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId()) } var ( configuration *config.Configuration debug = flag.Bool("debug", false, "debug output") ) func main() { flag.Parse() Ascii() configuration = config.LoadConfig() }
package main import ( "fmt" "github.com/adrien-f/gotify/config" sp "github.com/op/go-libspotify" ) func Ascii() { fmt.Println(" _ _ __") fmt.Println(" __ _ ___ | |_(_)/ _|_ _") fmt.Println(" / _` |/ _ \\| __| | |_| | | |") fmt.Println("| (_| | (_) | |_| | _| |_| |") fmt.Println(" \\__, |\\___/ \\__|_|_| \\__, |") fmt.Println(" |___/ |___/") fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId()) } var ( configuration *config.Configuration ) func main() { Ascii() configuration = config.LoadConfig() }
FIX: Remove access key fields that are not required
<?php class AccessKeysSiteConfig extends DataObjectDecorator { function extraStatics() { return array( 'db' => array( 'SkipToMainContentAccessKey' => 'VarChar(1)' ) ); } public function updateCMSFields(FieldSet &$fields) { $tf2 = new TextField('SkipToMainContentAccessKey'); $tf2->setMaxLength(1); $fields->addFieldToTab('Root.Accessibility', $tf2); $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); } } ?>
<?php class AccessKeysSiteConfig extends DataObjectDecorator { function extraStatics() { return array( 'db' => array( 'SearchAccessKey' => 'VarChar(1)', 'SkipToMainContentAccessKey' => 'VarChar(1)', 'AccessibilityHelpAccessKey' => 'VarChar(1)' ) ); } public function updateCMSFields(FieldSet &$fields) { $tf1 = new TextField('SearchAccessKey'); $tf1->setMaxLength(1); $fields->addFieldToTab('Root.Accessibility', $tf1); $fields->renameField("SearchAccessKey", _t('AccessKey.SEARCH_ACCESS_KEY')); $tf2 = new TextField('SkipToMainContentAccessKey'); $tf2->setMaxLength(1); $fields->addFieldToTab('Root.Accessibility', $tf2); $fields->renameField("SkipToMainContentAccessKey", _t('AccessKey.SKIP_TO_MAIN_CONTENT_ACCESS_KEY')); $tf3 = new TextField('AccessibilityHelpAccessKey'); $tf3->setMaxLength(1); $fields->addFieldToTab('Root.Accessibility', $tf3); $fields->renameField("AccessibilityHelpAccessKey", _t('AccessKey.ACCESSIBILITY_HELP_ACCESS_KEY')); } } ?>
Disable OAuth header parsing for now.
<?php namespace Northstar\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, // @TODO: Enable this once we've updated PHP version. // \Northstar\Http\Middleware\ParseOAuthHeader::class, ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => \Northstar\Http\Middleware\Authenticate::class, 'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class, 'scope' => \Northstar\Http\Middleware\RequireScope::class, // @TODO: Remove this old alias for the scope middleware. 'key' => \Northstar\Http\Middleware\RequireScope::class, ]; }
<?php namespace Northstar\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's global HTTP middleware stack. * * @var array */ protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Northstar\Http\Middleware\ParseOAuthHeader::class, ]; /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => \Northstar\Http\Middleware\Authenticate::class, 'guest' => \Northstar\Http\Middleware\RedirectIfAuthenticated::class, 'scope' => \Northstar\Http\Middleware\RequireScope::class, // @TODO: Remove this old alias for the scope middleware. 'key' => \Northstar\Http\Middleware\RequireScope::class, ]; }
III-2779: Fix exception about enums that can't be serialized, ensure native sapiVersion is serialized instead
<?php namespace CultuurNet\UDB3\SavedSearches\Command; use CultuurNet\UDB3\ValueObject\SapiVersion; use ValueObjects\StringLiteral\StringLiteral; abstract class SavedSearchCommand { /** * @var string */ protected $sapiVersion; /** * @var StringLiteral */ protected $userId; /** * @param SapiVersion $sapiVersion * @param StringLiteral $userId */ public function __construct( SapiVersion $sapiVersion, StringLiteral $userId ) { $this->sapiVersion = $sapiVersion->toNative(); $this->userId = $userId; } /** * @return SapiVersion */ public function getSapiVersion(): SapiVersion { return SapiVersion::fromNative($this->sapiVersion); } /** * @return StringLiteral */ public function getUserId() { return $this->userId; } }
<?php namespace CultuurNet\UDB3\SavedSearches\Command; use CultuurNet\UDB3\ValueObject\SapiVersion; use ValueObjects\StringLiteral\StringLiteral; abstract class SavedSearchCommand { /** * @var SapiVersion */ protected $sapiVersion; /** * @var StringLiteral */ protected $userId; /** * @param SapiVersion $sapiVersion * @param StringLiteral $userId */ public function __construct( SapiVersion $sapiVersion, StringLiteral $userId ) { $this->sapiVersion = $sapiVersion; $this->userId = $userId; } /** * @return SapiVersion */ public function getSapiVersion(): SapiVersion { return $this->sapiVersion; } /** * @return StringLiteral */ public function getUserId() { return $this->userId; } }
Install argparse when installing on Python 2.6
#/usr/bin/env python import os from setuptools import setup, find_packages from salad import VERSION ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) requirements = ["argparse", "nose", "splinter", "zope.testbrowser", "lettuce>=0.2.10.1"] try: import argparse except ImportError: requirements.append('argparse') setup( name="salad", description="A nice mix of great BDD ingredients", author="Steven Skoczen", author_email="steven.skoczen@wk.com", url="https://github.com/wieden-kennedy/salad", version=VERSION, download_url = ['https://github.com/skoczen/lettuce/tarball/fork', ], install_requires=requirements, dependency_links = ['https://github.com/skoczen/lettuce/tarball/fork#egg=lettuce-0.2.10.1', ], packages=find_packages(), zip_safe=False, include_package_data=True, classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], entry_points={ 'console_scripts': ['salad = salad.cli:main'], }, )
#/usr/bin/env python import os from setuptools import setup, find_packages from salad import VERSION ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) setup( name="salad", description="A nice mix of great BDD ingredients", author="Steven Skoczen", author_email="steven.skoczen@wk.com", url="https://github.com/wieden-kennedy/salad", version=VERSION, download_url = ['https://github.com/skoczen/lettuce/tarball/fork', ], install_requires=["nose", "splinter", "zope.testbrowser", "lettuce>=0.2.10.1"], dependency_links = ['https://github.com/skoczen/lettuce/tarball/fork#egg=lettuce-0.2.10.1', ], packages=find_packages(), zip_safe=False, include_package_data=True, classifiers=[ "Programming Language :: Python", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "Topic :: Internet :: WWW/HTTP", "Topic :: Software Development :: Libraries :: Python Modules", ], entry_points={ 'console_scripts': ['salad = salad.cli:main'], }, )
Change unit object format (server side)
var units = { datacenter: { unitStats: { name: 'SysAdmin', attack: 0, security: 25, power: 500, price: 2000 } }, personal_computer: { unitStats: { name: 'Zombie computer', attack: 10, security: 0, power: 10, price: 300 } }, cave: { unitStats: { name: 'Hacker', attack: 25, security: 0, power: 0, price: 2000 } } }; module.exports = units;
var units = { datacenter: { unitName: 'adminsys', unitStats: { attack: 10, security: 50, power: 5 } }, personal_computer: { unitName: 'zombie_computer', unitStats: { attack: 50, security: 0, power: 2 } }, cave: { unitName: 'hackers', unitStats: { attack: 100, security: 30, power: 4 } } }; module.exports = units;
Use named functions for better readability
angular .module('ngSharepoint') .provider('$sp', $spProvider); function $spProvider() { var siteUrl = ''; var connMode = 'JSOM'; var token = false; var autoload = true; var provider = { setSiteUrl: setSiteUrl, setConnectionMode: setConnectionMode, setAccessToken: setAccessToken, setAutoload: setAutoload, $get: $sp }; return provider; function setSiteUrl(newUrl) { siteUrl = newUrl; } function setConnectionMode(newConnMode) { //Only JSOM Supported for now if (newConnMode === 'JSOM' || newConnMode === 'REST') { connMode = newConnMode; } } function setAccessToken(newToken) { token = newToken; } function setAutoload(newAutoload) { autoload = newAutoload; } function $sp() { var service = { getSiteUrl: getSiteUrl, getConnectionMode: getConnectionMode, getAccessToken: getAccessToken, getContext: getContext, getAutoload: getAutoload }; return service; function getContext() { return new SP.ClientContext(); } function getSiteUrl() { return siteUrl; } function getConnectionMode() { return connMode; } function getAccessToken() { return token; } function getAutoload() { return autoload; } } }
angular .module('ngSharepoint') .provider('$sp', function() { var siteUrl = ''; var connMode = 'JSOM'; //possible values: JSOM, REST var token = false; var autoload = true; return { setSiteUrl: function (newUrl) { siteUrl = newUrl; }, setConnectionMode: function(newConnMode) { //Only JSOM Supported for now if (newConnMode === 'JSOM' || newConnMode === 'REST') { connMode = newConnMode; } }, setAccessToken: function(newToken) { token = newToken; }, setAutoload: function(newAutoload) { autoload = newAutoload; }, $get: function() { return ({ getSiteUrl: function() { return siteUrl; }, getConnectionMode: function() { return connMode; }, getAccessToken: function(token) { return token; }, getContext: function() { return new SP.ClientContext(siteUrl); }, getAutoload: function() { return autoload; } }); } }; });
ROO-1875: Improve file system management messages by using "Updated" instead of "Managed" verb
package org.springframework.roo.process.manager.internal; import java.io.File; import java.util.logging.Logger; import org.springframework.roo.file.undo.FilenameResolver; import org.springframework.roo.support.logging.HandlerUtils; import org.springframework.roo.support.util.Assert; public class ManagedMessageRenderer { private static final Logger logger = HandlerUtils.getLogger(ManagedMessageRenderer.class); private FilenameResolver filenameResolver; private File file; private String descriptionOfChange = null; private boolean createOperation; public void setDescriptionOfChange(String message) { this.descriptionOfChange = message; } public ManagedMessageRenderer(FilenameResolver filenameResolver, File file, boolean createOperation) { Assert.notNull(filenameResolver, "Filename resolver required"); Assert.notNull(file, "File to manage required"); this.filenameResolver = filenameResolver; this.file = file; this.createOperation = createOperation; } void logManagedMessage() { StringBuilder message = new StringBuilder(); if (createOperation) { message.append("Created "); } else { message.append("Updated "); } message.append(filenameResolver.getMeaningfulName(file)); if (descriptionOfChange != null && descriptionOfChange.length() > 0) { message.append(" ["); message.append(descriptionOfChange); message.append("]"); } logger.fine(message.toString()); } }
package org.springframework.roo.process.manager.internal; import java.io.File; import java.util.logging.Logger; import org.springframework.roo.file.undo.FilenameResolver; import org.springframework.roo.support.logging.HandlerUtils; import org.springframework.roo.support.util.Assert; public class ManagedMessageRenderer { private static final Logger logger = HandlerUtils.getLogger(ManagedMessageRenderer.class); private FilenameResolver filenameResolver; private File file; private String descriptionOfChange = null; private boolean createOperation; public void setDescriptionOfChange(String message) { this.descriptionOfChange = message; } public ManagedMessageRenderer(FilenameResolver filenameResolver, File file, boolean createOperation) { Assert.notNull(filenameResolver, "Filename resolver required"); Assert.notNull(file, "File to manage required"); this.filenameResolver = filenameResolver; this.file = file; this.createOperation = createOperation; } void logManagedMessage() { StringBuilder message = new StringBuilder(); if (createOperation) { message.append("Created "); } else { message.append("Managed "); } message.append(filenameResolver.getMeaningfulName(file)); if (descriptionOfChange != null && descriptionOfChange.length() > 0) { message.append(" ["); message.append(descriptionOfChange); message.append("]"); } logger.fine(message.toString()); } }
Change button link to point to Donorbox page
import React from 'react'; // import PropTypes from 'prop-types'; import Section from 'shared/components/section/section'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './donate.css'; const Donate = (props) => { const { ...otherProps } = props; return ( <Section title="Donate" headingLines={false} {...otherProps} className={styles.donateSection} headingTheme="white" > <div className={styles.donate} > <p> Our mission and veteran programs are all maintained through the efforts of our all volunteer staff. Your thoughtful contribution to our fund allows us to expand our reach and help more veterans attend developer conferences. </p> <p>Thank you for helping us to get veterans coding!</p> <LinkButton text="Donate Now" link="https://donorbox.org/operationcode" /> </div> </Section> ); }; Donate.propTypes = {}; export default Donate;
import React from 'react'; // import PropTypes from 'prop-types'; import Section from 'shared/components/section/section'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './donate.css'; const Donate = (props) => { const { ...otherProps } = props; return ( <Section title="Donate" headingLines={false} {...otherProps} className={styles.donateSection} headingTheme="white" > <div className={styles.donate} > <p> Our mission and veteran programs are all maintained through the efforts of our all volunteer staff. Your thoughtful contribution to our fund allows us to expand our reach and help more veterans attend developer conferences. </p> <p>Thank you for helping us to get veterans coding!</p> <LinkButton text="Donate Now" link="#" /> </div> </Section> ); }; Donate.propTypes = {}; export default Donate;
event-protocol: Make binary command executable and add hashbang I might have missed something, but I couldn't work out to run it (from another directory) anymore since it moved into the bin directory in 3dbafa2e4a327a4251038a97063b7de5e0da3f88
#!/usr/bin/env node const readline = require('readline') const validateEvent = require('../lib/validateEvent') const RED = '\033[0;31m' const NC = '\033[0m' const lines = readline.createInterface({ input: process.stdin }) let error = false lines.on('line', line => { if(error) return let event try { event = JSON.parse(line) validateEvent(event) console.log(line) } catch(err) { if(event) { console.error(RED + '--- Failed to validate event ---' + NC) console.error(RED + JSON.stringify(event, null, 2) + NC) console.error(RED + '--- Validation error ---' + NC) } console.error(RED + err.message + NC) error = true lines.close() } }) lines.on('close', () => process.exit(error ? 1 : 0))
const readline = require('readline') const validateEvent = require('../lib/validateEvent') const RED = '\033[0;31m' const NC = '\033[0m' const lines = readline.createInterface({ input: process.stdin }) let error = false lines.on('line', line => { if(error) return let event try { event = JSON.parse(line) validateEvent(event) console.log(line) } catch(err) { if(event) { console.error(RED + '--- Failed to validate event ---' + NC) console.error(RED + JSON.stringify(event, null, 2) + NC) console.error(RED + '--- Validation error ---' + NC) } console.error(RED + err.message + NC) error = true lines.close() } }) lines.on('close', () => process.exit(error ? 1 : 0))
Change Entity Revision name separator from . to __
"use strict"; const Table = require('./table'); class Revision extends Table { constructor(engine, relationship, name='revision', alias=null) { super(engine, relationship.name + '__' + name, alias); this.id = name; this.relationship = relationship; return this; } schema() { let schema = super.schema(); schema.columns.push({ name: 'entityId', dataType: 'INTEGER', // NOTE: Ideally, this field should be notNull. Unfortunately, we need // to procure the revisionId *before* we know the entityId (when saving // a new entity). Therefore, we must allow for null values. notNull: false, }, { name: 'date', dataType: 'INTEGER', notNull: true, }); schema.keys.push('entityId'); return schema; } } module.exports = Revision;
"use strict"; const Table = require('./table'); class Revision extends Table { constructor(engine, relationship, name='revision', alias=null) { super(engine, relationship.name + '.' + name, alias); this.id = name; this.relationship = relationship; return this; } schema() { let schema = super.schema(); schema.columns.push({ name: 'entityId', dataType: 'INTEGER', // NOTE: Ideally, this field should be notNull. Unfortunately, we need // to procure the revisionId *before* we know the entityId (when saving // a new entity). Therefore, we must allow for null values. notNull: false, }, { name: 'date', dataType: 'INTEGER', notNull: true, }); schema.keys.push('entityId'); return schema; } } module.exports = Revision;
Correct a client test description even-numbered -> odd-numbered
package client import ( "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/spec" "golang.org/x/net/http2" ) func StreamIdentifiers() *spec.ClientTestGroup { tg := NewTestGroup("5.1.1", "Stream Identifiers") // An endpoint that receives an unexpected stream identifier // MUST respond with a connection error (Section 5.4.1) of // type PROTOCOL_ERROR. tg.AddTestCase(&spec.ClientTestCase{ Desc: "Sends odd-numbered stream identifier", Requirement: "The endpoint MUST respond with a connection error of type PROTOCOL_ERROR.", Run: func(c *config.Config, conn *spec.Conn) error { err := conn.Handshake() if err != nil { return err } headers := spec.CommonRespHeaders(c) hp := http2.HeadersFrameParam{ StreamID: 101, EndStream: true, EndHeaders: true, BlockFragment: conn.EncodeHeaders(headers), } conn.WriteHeaders(hp) return spec.VerifyConnectionError(conn, http2.ErrCodeProtocol) }, }) return tg }
package client import ( "github.com/summerwind/h2spec/config" "github.com/summerwind/h2spec/spec" "golang.org/x/net/http2" ) func StreamIdentifiers() *spec.ClientTestGroup { tg := NewTestGroup("5.1.1", "Stream Identifiers") // An endpoint that receives an unexpected stream identifier // MUST respond with a connection error (Section 5.4.1) of // type PROTOCOL_ERROR. tg.AddTestCase(&spec.ClientTestCase{ Desc: "Sends even-numbered stream identifier", Requirement: "The endpoint MUST respond with a connection error of type PROTOCOL_ERROR.", Run: func(c *config.Config, conn *spec.Conn) error { err := conn.Handshake() if err != nil { return err } headers := spec.CommonRespHeaders(c) hp := http2.HeadersFrameParam{ StreamID: 101, EndStream: true, EndHeaders: true, BlockFragment: conn.EncodeHeaders(headers), } conn.WriteHeaders(hp) return spec.VerifyConnectionError(conn, http2.ErrCodeProtocol) }, }) return tg }
Check expected type after JSON decode instead of checking what is not expected. This will also allow "true" and "false" as filenames instead of only "null".
<?php /** * ownCloud - ajax frontend * * @author Robin Appelman * @copyright 2010 Robin Appelman icewind1991@gmail.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // only need filesystem apps $RUNTIME_APPTYPES=array('filesystem'); // Init owncloud // Check if we are a user OCP\User::checkLoggedIn(); $files = $_GET["files"]; $dir = $_GET["dir"]; $files_list = json_decode($files); // in case we get only a single file if (!is_array($files_list)) { $files_list = array($files); } OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);
<?php /** * ownCloud - ajax frontend * * @author Robin Appelman * @copyright 2010 Robin Appelman icewind1991@gmail.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE * License as published by the Free Software Foundation; either * version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details. * * You should have received a copy of the GNU Affero General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ // only need filesystem apps $RUNTIME_APPTYPES=array('filesystem'); // Init owncloud // Check if we are a user OCP\User::checkLoggedIn(); $files = $_GET["files"]; $dir = $_GET["dir"]; $files_list = json_decode($files); // in case we get only a single file if ($files_list === NULL ) { $files_list = array($files); } OC_Files::get($dir, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD' ? true : false);
Introduce ember-infinity as a service
export function initialize(application) { const inject = (property, what) => { application.inject('controller', property, what); application.inject('component', property, what); application.inject('route', property, what); }; inject('config', 'service:config'); inject('session', 'service:session'); inject('authManager', 'service:auth-manager'); inject('store', 'service:store'); inject('metrics', 'service:metrics'); inject('loader', 'service:loader'); inject('l10n', 'service:l10n'); inject('device', 'service:device'); inject('notify', 'service:notify'); inject('confirm', 'service:confirm'); inject('sanitizer', 'service:sanitizer'); inject('settings', 'service:settings'); inject('fastboot', 'service:fastboot'); inject('routing', 'service:-routing'); inject('cookies', 'service:cookies'); inject('infinity', 'service:infinity'); application.inject('component', 'router', 'service:router'); } export default { name: 'blanket', initialize };
export function initialize(application) { const inject = (property, what) => { application.inject('controller', property, what); application.inject('component', property, what); application.inject('route', property, what); }; inject('config', 'service:config'); inject('session', 'service:session'); inject('authManager', 'service:auth-manager'); inject('store', 'service:store'); inject('metrics', 'service:metrics'); inject('loader', 'service:loader'); inject('l10n', 'service:l10n'); inject('device', 'service:device'); inject('notify', 'service:notify'); inject('confirm', 'service:confirm'); inject('sanitizer', 'service:sanitizer'); inject('settings', 'service:settings'); inject('fastboot', 'service:fastboot'); inject('routing', 'service:-routing'); inject('cookies', 'service:cookies'); application.inject('component', 'router', 'service:router'); } export default { name: 'blanket', initialize };
Switch experiment to performing 1000 parallel requests
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 1000, timeout: 0 }); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
const io = require('socket.io'), winston = require('winston'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, {'timestamp': true}); const PORT = 3031; winston.info('Rupture real-time service starting'); winston.info('Listening on port ' + PORT); var socket = io.listen(PORT); socket.on('connection', function(client) { winston.info('New connection from client ' + client.id); client.on('get-work', function() { winston.info('get-work from client ' + client.id); client.emit('do-work', { url: 'https://facebook.com/?breach-test', amount: 3, timeout: 0 }); }); client.on('disconnect', function() { winston.info('Client ' + client.id + ' disconnected'); }); });
Handle error testcases in mock-server tests.
""" Tests for the mock-server itself. """ from utils import APIPath def test_testcase_difference(root_path): """Ensure that different testcases output different data.""" recipes = set() testcase_paths = ( APIPath(path, 'http://example.com') for path in root_path.path.iterdir() if path.is_dir() ) for testcase_path in testcase_paths: recipe_path = testcase_path.add('api', 'v1', 'recipe') try: recipe_data = recipe_path.read() signed_recipe_data = recipe_path.add('signed').read() except FileNotFoundError: # Some error testcases are purposefully missing files, # so we just skip checking those. continue assert recipe_data not in recipes recipes.add(recipe_data) # This asserts both that testcases have differing signed data # and that a single testcase does not have the same data for # signed and unsigned endpoints. assert signed_recipe_data not in recipes recipes.add(signed_recipe_data)
""" Tests for the mock-server itself. """ from utils import APIPath def test_testcase_difference(root_path): """Ensure that different testcases output different data.""" recipes = set() testcase_paths = ( APIPath(path, 'http://example.com') for path in root_path.path.iterdir() if path.is_dir() ) for testcase_path in testcase_paths: recipe_path = testcase_path.add('api', 'v1', 'recipe') recipe_data = recipe_path.read() assert recipe_data not in recipes recipes.add(recipe_data) # This asserts both that testcases have differing signed data # and that a single testcase does not have the same data for # signed and unsigned endpoints. signed_recipe_data = recipe_path.add('signed').read() assert signed_recipe_data not in recipes recipes.add(signed_recipe_data)
Add wrapper for async receive event handler
import asyncio import inspect import sys from rollbar.contrib.asgi import ASGIApp def run(coro): if sys.version_info >= (3, 7): return asyncio.run(coro) assert inspect.iscoroutine(coro) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() asyncio.set_event_loop(None) def async_receive(message): async def receive(): return message assert message["type"] == "http.request" return receive @ASGIApp class FailingTestASGIApp: def __call__(self, scope, receive, send): run(self._asgi_app(scope, receive, send)) async def app(self, scope, receive, send): raise RuntimeError("Invoked only for testing")
import asyncio import inspect import sys from rollbar.contrib.asgi import ASGIApp def run(coro): if sys.version_info >= (3, 7): return asyncio.run(coro) assert inspect.iscoroutine(coro) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() asyncio.set_event_loop(None) @ASGIApp class FailingTestASGIApp: def __call__(self, scope, receive, send): run(self._asgi_app(scope, receive, send)) async def app(self, scope, receive, send): raise RuntimeError("Invoked only for testing")
Simplify data object for authentication
package hummingbird import ( "encoding/json" "github.com/parnurzeal/gorequest" ) type API struct { endpoint string token string request *gorequest.SuperAgent } func (api *API) UserAuthenticate(username, email, password string) (errs []error, body string) { data := map[string]string{ "username": username, "email": email, "password": password, } _, body, errs = api.request. Post(api.endpoint + "/v1/users/authenticate"). Send(data). End() if len(errs) == 0 { api.token = body } return } func (api *API) UserInformation(username string) (errs []error, user User) { _, body, errs := api.request. Get(api.endpoint + "/v1/users/" + username). End() if len(errs) != 0 { return } err := json.Unmarshal([]byte(body), &user) if err != nil { errs = append(errs, err) } return } func NewAPI() *API { api := new(API) api.endpoint = "https://hummingbird.me/api" api.request = gorequest.New() return api }
package hummingbird import ( "encoding/json" "github.com/parnurzeal/gorequest" ) type API struct { endpoint string token string request *gorequest.SuperAgent } func (api *API) UserAuthenticate(username, email, password string) (errs []error, body string) { type UserAuthenticateData struct { Username string `json:"username,omitempty"` Email string `json:"email,omitempty"` Password string `json:"password"` } data := UserAuthenticateData{ Username: username, Email: email, Password: password, } _, body, errs = api.request. Post(api.endpoint + "/v1/users/authenticate"). Send(data). End() if len(errs) == 0 { api.token = body } return } func (api *API) UserInformation(username string) (errs []error, user User) { _, body, errs := api.request. Get(api.endpoint + "/v1/users/" + username). End() if len(errs) != 0 { return } err := json.Unmarshal([]byte(body), &user) if err != nil { errs = append(errs, err) } return } func NewAPI() *API { api := new(API) api.endpoint = "https://hummingbird.me/api" api.request = gorequest.New() return api }
Fix Celery configuration for AppConfig in INSTALLED_APPS
# http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import import os from celery import Celery # Attempt to determine the project name from the directory containing this file PROJECT_NAME = os.path.basename(os.path.dirname(__file__)) # Set the default Django settings module for the 'celery' command-line program os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{}.settings'.format( PROJECT_NAME)) from django.conf import settings app = Celery(PROJECT_NAME) # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') # The `app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)` technique # described in # http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html # fails when INSTALLED_APPS includes a "dotted path to the appropriate # AppConfig subclass" as recommended by # https://docs.djangoproject.com/en/1.8/ref/applications/#configuring-applications. # Ask Solem recommends the following workaround; see # https://github.com/celery/celery/issues/2248#issuecomment-97404667 from django.apps import apps app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()]) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
# http://celery.readthedocs.org/en/latest/django/first-steps-with-django.html from __future__ import absolute_import import os from celery import Celery # Attempt to determine the project name from the directory containing this file PROJECT_NAME = os.path.basename(os.path.dirname(__file__)) # Set the default Django settings module for the 'celery' command-line program os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{}.settings'.format( PROJECT_NAME)) from django.conf import settings app = Celery(PROJECT_NAME) # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
feat: Add pagination options to listReferencedFiles
import { cozyFetchJSON } from './fetch' import { encodeQuery } from './utils' import { DOCTYPE_FILES } from './doctypes' function updateRelations (verb) { return function (cozy, doc, ids) { if (!doc) throw new Error('missing doc argument') if (!Array.isArray(ids)) ids = [ids] const refs = ids.map((id) => ({type: DOCTYPE_FILES, id})) return cozyFetchJSON(cozy, verb, makeReferencesPath(doc), {data: refs}) } } export const addReferencedFiles = updateRelations('POST') export const removeReferencedFiles = updateRelations('DELETE') export function listReferencedFiles (cozy, doc, options) { if (!doc) throw new Error('missing doc argument') return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc, options)) .then((files) => files.map((file) => file._id)) } function makeReferencesPath (doc, options) { const type = encodeURIComponent(doc._type) const id = encodeURIComponent(doc._id) let q = encodeQuery(options) if (q !== '') { q = '?' + q } return `/data/${type}/${id}/relationships/references${q}` }
import {cozyFetchJSON} from './fetch' import { DOCTYPE_FILES } from './doctypes' function updateRelations (verb) { return function (cozy, doc, ids) { if (!doc) throw new Error('missing doc argument') if (!Array.isArray(ids)) ids = [ids] const refs = ids.map((id) => ({type: DOCTYPE_FILES, id})) return cozyFetchJSON(cozy, verb, makeReferencesPath(doc), {data: refs}) } } export const addReferencedFiles = updateRelations('POST') export const removeReferencedFiles = updateRelations('DELETE') export function listReferencedFiles (cozy, doc) { if (!doc) throw new Error('missing doc argument') return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc)) .then((files) => files.map((file) => file._id)) } function makeReferencesPath (doc) { const type = encodeURIComponent(doc._type) const id = encodeURIComponent(doc._id) return `/data/${type}/${id}/relationships/references` }
Use FAIL rate-limit handler for tests Should avoid possible Thread.sleep() for tests execution.
package org.kohsuke.github; import org.junit.Assert; import org.junit.Before; import org.kohsuke.randname.RandomNameGenerator; import java.io.File; /** * @author Kohsuke Kawaguchi */ public abstract class AbstractGitHubApiTestBase extends Assert { protected GitHub gitHub; @Before public void setUp() throws Exception { File f = new File(System.getProperty("user.home"), ".github.kohsuke2"); if (f.exists()) { // use the non-standard credential preferentially, so that developers of this library do not have // to clutter their event stream. gitHub = GitHubBuilder.fromPropertyFile(f.getPath()).withRateLimitHandler(RateLimitHandler.FAIL).build(); } else { gitHub = GitHubBuilder.fromCredentials().withRateLimitHandler(RateLimitHandler.FAIL).build(); } } protected static final RandomNameGenerator rnd = new RandomNameGenerator(); }
package org.kohsuke.github; import org.junit.Assert; import org.junit.Before; import org.kohsuke.randname.RandomNameGenerator; import java.io.File; /** * @author Kohsuke Kawaguchi */ public abstract class AbstractGitHubApiTestBase extends Assert { protected GitHub gitHub; @Before public void setUp() throws Exception { File f = new File(System.getProperty("user.home"), ".github.kohsuke2"); if (f.exists()) { // use the non-standard credential preferentially, so that developers of this library do not have // to clutter their event stream. gitHub = GitHubBuilder.fromPropertyFile(f.getPath()).build(); } else { gitHub = GitHub.connect(); } } protected static final RandomNameGenerator rnd = new RandomNameGenerator(); }
Add the redacter display name to the redaction text
/* Copyright 2015, 2016 OpenMarket Ltd 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'; var React = require('react'); var MatrixClientPeg = require('../../../MatrixClientPeg'); module.exports = React.createClass({ displayName: 'UnknownBody', render: function() { const ev = this.props.mxEvent; var text = ev.getContent().body; if (ev.isRedacted()) { const room = MatrixClientPeg.get().getRoom(ev.getRoomId()); const because = ev.getUnsigned().redacted_because; const name = room.getMember(because.sender).name || because.sender; text = "This event was redacted by " + name; } return ( <span className="mx_UnknownBody"> {text} </span> ); }, });
/* Copyright 2015, 2016 OpenMarket Ltd 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'; var React = require('react'); module.exports = React.createClass({ displayName: 'UnknownBody', render: function() { var text = this.props.mxEvent.getContent().body; if (this.props.mxEvent.isRedacted()) { text = "This event was redacted"; } return ( <span className="mx_UnknownBody"> {text} </span> ); }, });
Implement /refresh endpoint for indetity provider
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.athenz.instanceproviderservice.instanceconfirmation; import com.google.inject.Inject; import com.yahoo.container.jaxrs.annotation.Component; import com.yahoo.log.LogLevel; import javax.ws.rs.Consumes; import javax.ws.rs.ForbiddenException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.logging.Logger; /** * @author bjorncs */ @Path("/{path: instance|refresh}") public class InstanceConfirmationResource { private static final Logger log = Logger.getLogger(InstanceConfirmationResource.class.getName()); private final InstanceValidator instanceValidator; @Inject public InstanceConfirmationResource(@Component InstanceValidator instanceValidator) { this.instanceValidator = instanceValidator; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public InstanceConfirmation confirmInstance(InstanceConfirmation instanceConfirmation) { if (!instanceValidator.isValidInstance(instanceConfirmation)) { log.log(LogLevel.ERROR, "Invalid instance: " + instanceConfirmation); throw new ForbiddenException("Instance is invalid"); } return instanceConfirmation; } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.athenz.instanceproviderservice.instanceconfirmation; import com.google.inject.Inject; import com.yahoo.container.jaxrs.annotation.Component; import com.yahoo.log.LogLevel; import javax.ws.rs.Consumes; import javax.ws.rs.ForbiddenException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.logging.Logger; /** * @author bjorncs */ @Path("/instance") public class InstanceConfirmationResource { private static final Logger log = Logger.getLogger(InstanceConfirmationResource.class.getName()); private final InstanceValidator instanceValidator; @Inject public InstanceConfirmationResource(@Component InstanceValidator instanceValidator) { this.instanceValidator = instanceValidator; } @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public InstanceConfirmation confirmInstance(InstanceConfirmation instanceConfirmation) { if (!instanceValidator.isValidInstance(instanceConfirmation)) { log.log(LogLevel.ERROR, "Invalid instance: " + instanceConfirmation); throw new ForbiddenException("Instance is invalid"); } return instanceConfirmation; } }
routes/flights/base: Reset "page" to 1 after leaving the route
import Ember from 'ember'; export default Ember.Route.extend({ ajax: Ember.inject.service(), queryParams: { page: { refreshModel: true }, column: { refreshModel: true }, order: { refreshModel: true }, }, model(params) { return this.get('ajax').request(this.getURL(params), { data: { page: params.page, column: params.column, order: params.order, }, }); }, getURL(/* params */) { throw new Error('Not implemented: `getURL`'); }, resetController(controller, isExiting) { this._super(...arguments); if (isExiting) { controller.set('page', 1); } }, actions: { loading(transition) { let controller = this.controllerFor('flights'); controller.set('loading', true); transition.promise.finally(() => { controller.set('loading', false); }); }, }, });
import Ember from 'ember'; export default Ember.Route.extend({ ajax: Ember.inject.service(), queryParams: { page: { refreshModel: true }, column: { refreshModel: true }, order: { refreshModel: true }, }, model(params) { return this.get('ajax').request(this.getURL(params), { data: { page: params.page, column: params.column, order: params.order, }, }); }, getURL(/* params */) { throw new Error('Not implemented: `getURL`'); }, actions: { loading(transition) { let controller = this.controllerFor('flights'); controller.set('loading', true); transition.promise.finally(() => { controller.set('loading', false); }); }, }, });
Remove explicit requirement of JsonApiService JsonApiService is implicitly import before it is a service
/** * Module dependencies */ var util = require( 'util' ), actionUtil = require( './_util/actionUtil' ), pluralize = require('pluralize'); /** * Create Record * * post /:modelIdentity * * An API call to create and return a single model instance from the data adapter * using the specified criteria. * */ module.exports = function createRecord(req, res) { var Model = actionUtil.parseModel(req); var data = actionUtil.parseValues(req, Model); // Create new instance of model using data from params Model.create(data) .exec( (err, newInstance) => { if (err) return res.negotiate(err) var Q = Model.findOne(newInstance.id); Q.exec( (err, newRecord) => { var type = pluralize(req.options.model || req.options.controller); res.status(201); return res.json(JsonApiService.serialize(type, newRecord)); }); }); };
/** * Module dependencies */ var util = require( 'util' ), actionUtil = require( './_util/actionUtil' ), pluralize = require('pluralize'); var JsonApiService = require('../services/JsonApiService'); /** * Create Record * * post /:modelIdentity * * An API call to create and return a single model instance from the data adapter * using the specified criteria. * */ module.exports = function createRecord(req, res) { var Model = actionUtil.parseModel(req); var data = actionUtil.parseValues(req, Model); // Create new instance of model using data from params Model.create(data) .exec( (err, newInstance) => { if (err) return res.negotiate(err) var Q = Model.findOne(newInstance.id); Q.exec( (err, newRecord) => { var type = pluralize(req.options.model || req.options.controller); res.status(201); return res.json(JsonApiService.serialize(type, newRecord)); }); }); };
Update error text to be more descriptive
package org.javarosa.xpath.expr; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.DataInstance; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.parser.XPathSyntaxException; public class XPathCountFunc extends XPathFuncExpr { public static final String NAME = "count"; private static final int EXPECTED_ARG_COUNT = 1; public XPathCountFunc() { name = NAME; expectedArgCount = EXPECTED_ARG_COUNT; } public XPathCountFunc(XPathExpression[] args) throws XPathSyntaxException { super(NAME, args, EXPECTED_ARG_COUNT, true); } @Override public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) { if (evaluatedArgs[0] instanceof XPathNodeset) { return new Double(((XPathNodeset)evaluatedArgs[0]).size()); } else { throw new XPathTypeMismatchException("uses an invalid reference inside a count function"); } } }
package org.javarosa.xpath.expr; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.DataInstance; import org.javarosa.xpath.XPathNodeset; import org.javarosa.xpath.XPathTypeMismatchException; import org.javarosa.xpath.parser.XPathSyntaxException; public class XPathCountFunc extends XPathFuncExpr { public static final String NAME = "count"; private static final int EXPECTED_ARG_COUNT = 1; public XPathCountFunc() { name = NAME; expectedArgCount = EXPECTED_ARG_COUNT; } public XPathCountFunc(XPathExpression[] args) throws XPathSyntaxException { super(NAME, args, EXPECTED_ARG_COUNT, true); } @Override public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) { if (evaluatedArgs[0] instanceof XPathNodeset) { return new Double(((XPathNodeset)evaluatedArgs[0]).size()); } else { throw new XPathTypeMismatchException("not a nodeset"); } } }
TEST added core-js to loading libraries for test suite
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'node_modules/core-js/client/core.js', { pattern: 'test/**/*.js', watched: false } ], exclude: [], preprocessors: { 'test/**/*.js': ['webpack'] }, webpack: { module: { loaders: [ { test: /\.js$/, loader: 'babel' }, { test: /\.html$/, loader: 'html' } ] }, devtool: "#inline-source-map" }, webpackMiddleware: { noInfo: true }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ { pattern: 'test/**/*.js', watched: false } ], exclude: [], preprocessors: { 'test/**/*.js': ['webpack'] }, webpack: { module: { loaders: [ { test: /\.js$/, loader: 'babel' }, { test: /\.html$/, loader: 'html' } ] }, devtool: "#inline-source-map" }, webpackMiddleware: { noInfo: true }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
Use List instead of ArrayList as type
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.List; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final List<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(List<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } }
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.btc.model; import java.util.ArrayList; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InputsAndChangeOutput { public final ArrayList<RawTransactionInput> rawTransactionInputs; // Is set to 0L in case we don't have an output public final long changeOutputValue; @Nullable public final String changeOutputAddress; public InputsAndChangeOutput(ArrayList<RawTransactionInput> rawTransactionInputs, long changeOutputValue, @Nullable String changeOutputAddress) { checkArgument(!rawTransactionInputs.isEmpty(), "rawInputs.isEmpty()"); this.rawTransactionInputs = rawTransactionInputs; this.changeOutputValue = changeOutputValue; this.changeOutputAddress = changeOutputAddress; } }
Include the position into the graph
from networkx import Graph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = Graph() buses = [] for bus_name, bus in buses_df.iterrows(): pos = (bus.x, bus.y) buses.append((bus_name, {'pos': pos})) # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
from networkx import OrderedGraph def translate_df_to_graph(buses_df, lines_df, transformers_df=None): graph = OrderedGraph() buses = buses_df.index # add nodes graph.add_nodes_from(buses) # add branches branches = [] for line_name, line in lines_df.iterrows(): branches.append( ( line.bus0, line.bus1, {"branch_name": line_name, "length": line.length}, ) ) if transformers_df is not None: for trafo_name, trafo in transformers_df.iterrows(): branches.append( ( trafo.bus0, trafo.bus1, {"branch_name": trafo_name, "length": 0}, ) ) graph.add_edges_from(branches) return graph
Use a dictionary for metrid ids. There are few unique ones (less than 1k), but many instances.
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.metricsproxy.metric.model; import com.yahoo.yolean.concurrent.CopyOnWriteHashMap; import java.util.Map; import java.util.Objects; /** * @author gjoranv */ public class MetricId { private static final Map<String, MetricId> dictionary = new CopyOnWriteHashMap<>(); public static final MetricId empty = toMetricId(""); public final String id; private MetricId(String id) { this.id = id; } public static MetricId toMetricId(String id) { return dictionary.computeIfAbsent(id, key -> new MetricId(key)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricId metricId = (MetricId) o; return Objects.equals(id, metricId.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return id; } }
// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package ai.vespa.metricsproxy.metric.model; import java.util.Objects; /** * @author gjoranv */ public class MetricId { public static final MetricId empty = toMetricId(""); public final String id; private MetricId(String id) { this.id = id; } public static MetricId toMetricId(String id) { return new MetricId(id); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MetricId metricId = (MetricId) o; return Objects.equals(id, metricId.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return id; } }
Use periods on senteces in docs
var ContactView = require('../view/Contact'); /** * Creates a new Contact. * @constructor * @arg {Object} options - Object hash used to populate instance. * @arg {string} options.firstName - First name of the contact. * @arg {string} options.firstName - Last name of the contact. * @arg {string} options.tel - Telephone number of the contact. */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact. */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
var ContactView = require('../view/Contact'); /** * Creates a new Contact * @constructor * @arg {Object} options - Object hash used to populate instance * @arg {string} options.firstName - First name of the contact * @arg {string} options.firstName - Last name of the contact * @arg {string} options.tel - name of the contact */ var Contact = function(options) { if (typeof options !== 'object') { throw console.error('`options` is not properly defined'); } this.init(options); }; Contact.prototype = { firstName: '', lastName: '', tel: '', /** * @description Creates a new instance of Contact */ init: function(options) { var opts = Object.keys(options); opts.forEach(function(currentValue){ this[currentValue] = options[currentValue]; }, this); console.log(this); this.save(); }, save: function() { var key = localStorage.length; var contact = { firstName: this.firstName, lastName: this.lastName, tel: this.tel }; localStorage.setItem(key, JSON.stringify(contact)); var contactView = new ContactView(key, contact); } }; Contact.remove = function(id) { localStorage.removeItem(id); }; module.exports = Contact;
Fix incorrect namespace for test class
<?php namespace Moxio\CodeSniffer\MoxioSniffs\Sniffs\Tests\PHP; use Moxio\CodeSniffer\MoxioSniffs\Sniffs\PHP\DisallowUniqidWithoutMoreEntropySniff; use Moxio\CodeSniffer\MoxioSniffs\Sniffs\Tests\AbstractSniffTest; class DisallowUniqidWithoutMoreEntropySniffTest extends AbstractSniffTest { protected function getSniffClass() { return DisallowUniqidWithoutMoreEntropySniff::class; } public function testSniff() { $file = __DIR__ . '/DisallowUniqidWithoutMoreEntropySniffTest.inc'; $this->assertFileHasErrorsOnLines($file, [ 2, 3, 5, ]); } }
<?php namespace Moxio\Sniffs\Tests\PHP; use Moxio\CodeSniffer\MoxioSniffs\Sniffs\PHP\DisallowUniqidWithoutMoreEntropySniff; use Moxio\CodeSniffer\MoxioSniffs\Sniffs\Tests\AbstractSniffTest; class DisallowUniqidWithoutMoreEntropySniffTest extends AbstractSniffTest { protected function getSniffClass() { return DisallowUniqidWithoutMoreEntropySniff::class; } public function testSniff() { $file = __DIR__ . '/DisallowUniqidWithoutMoreEntropySniffTest.inc'; $this->assertFileHasErrorsOnLines($file, [ 2, 3, 5, ]); } }
Change client constants sandbox URL to https
<?php /** * CheckoutApi_Client_Constant * A final class that manage constant value for all CheckoutApi_Client_Client instance * @package CheckoutApi_Client * @category Api * @author Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com> * @copyright 2014 Integration team (http://www.checkout.com) */ final class CheckoutApi_Client_Constant { const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/'; const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/'; const APIGW3_URI_PREFIX_SANDBOX= 'https://sandbox.checkout.com/api2/'; const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/'; const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_'; const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_'; const CHARGE_TYPE = 'card'; const LOCALPAYMENT_CHARGE_TYPE = 'localPayment'; const TOKEN_CARD_TYPE = 'cardToken'; const TOKEN_SESSION_TYPE = 'sessionToken'; const AUTOCAPUTURE_CAPTURE = 'y'; const AUTOCAPUTURE_AUTH = 'n'; const VERSION = 'v2'; const STATUS_CAPTURE = 'Captured'; const STATUS_REFUND = 'Refunded'; const LIB_VERSION = 'v1.2.5'; }
<?php /** * CheckoutApi_Client_Constant * A final class that manage constant value for all CheckoutApi_Client_Client instance * @package CheckoutApi_Client * @category Api * @author Dhiraj Gangoosirdar <dhiraj.gangoosirdar@checkout.com> * @copyright 2014 Integration team (http://www.checkout.com) */ final class CheckoutApi_Client_Constant { const APIGW3_URI_PREFIX_PREPOD = 'http://preprod.checkout.com/api2/'; const APIGW3_URI_PREFIX_DEV= 'http://dev.checkout.com/api2/'; const APIGW3_URI_PREFIX_SANDBOX= 'http://sandbox.checkout.com/api2/'; const APIGW3_URI_PREFIX_LIVE = 'https://api2.checkout.com/'; const ADAPTER_CLASS_GROUP = 'CheckoutApi_Client_Adapter_'; const PARSER_CLASS_GROUP = 'CheckoutApi_Parser_'; const CHARGE_TYPE = 'card'; const LOCALPAYMENT_CHARGE_TYPE = 'localPayment'; const TOKEN_CARD_TYPE = 'cardToken'; const TOKEN_SESSION_TYPE = 'sessionToken'; const AUTOCAPUTURE_CAPTURE = 'y'; const AUTOCAPUTURE_AUTH = 'n'; const VERSION = 'v2'; const STATUS_CAPTURE = 'Captured'; const STATUS_REFUND = 'Refunded'; const LIB_VERSION = 'v1.2.5'; }
Add `request` and `response` to context. Add `request` and `response` to context in the service. Closes #106.
var find = require('reactor/find'), serializer = require('./serializer'), url = require('url'); function say () { var all = [].slice.call(arguments), filtered = all.filter(function (argument) { return argument !== say }); console.log.apply(console, filtered); if (filtered.length != all.length) process.exit(1); } exports.create = function (base, context) { var reactor = require('reactor').createReactor(); find(base, 'stencil').forEach(function (route) { reactor.get(route.route, function (params, request, response, next) { var pathInfo = params.pathInfo ? '/' + params.pathInfo : ''; context.generate(route.script, { request: request, response: response, pathInfo: pathInfo }, function (error, stencil) { if (error) { next(error); } else { response.setHeader("Content-Type", "text/html; charset=utf8"); response.end(serializer(stencil.document.documentElement)); } }); }); }); return function (req, res, next){ if (!reactor.react(req.method, url.parse(req.url).pathname, req, res, next)) next(); } }
var find = require('reactor/find'), serializer = require('./serializer'), url = require('url'); function say () { var all = [].slice.call(arguments), filtered = all.filter(function (argument) { return argument !== say }); console.log.apply(console, filtered); if (filtered.length != all.length) process.exit(1); } exports.create = function (base, context) { var reactor = require('reactor').createReactor(); find(base, 'stencil').forEach(function (route) { reactor.get(route.route, function (params, request, response, next) { var pathInfo = params.pathInfo ? '/' + params.pathInfo : ''; context.generate(route.script, { pathInfo: pathInfo }, function (error, stencil) { if (error) { next(error); } else { response.setHeader("Content-Type", "text/html; charset=utf8"); response.end(serializer(stencil.document.documentElement)); } }); }); }); return function (req, res, next){ if (!reactor.react(req.method, url.parse(req.url).pathname, req, res, next)) next(); } }
Add git command to appAction category
'use strict'; var path = require('path'); var taskOpts = require('./lib/tasks.js'); module.exports = function(kbox) { var events = kbox.core.events; var engine = kbox.engine; kbox.ifApp(function(app) { // Grab the clients var Git = require('./lib/git.js'); var git = new Git(kbox, app); // Events // Install the util container for our things events.on('post-install', function(app, done) { var opts = { name: 'git', srcRoot: path.resolve(__dirname) }; engine.build(opts, done); }); // Tasks // git wrapper: kbox git COMMAND kbox.tasks.add(function(task) { task.path = [app.name, 'git']; task.category = 'appAction'; task.description = 'Run git commands.'; task.kind = 'delegate'; task.options.push(taskOpts.gitUsername); task.options.push(taskOpts.gitEmail); task.func = function(done) { // We need to use this faux bin until the resolution of // https://github.com/syncthing/syncthing/issues/1056 git.cmd(this.payload, this.options, done); }; }); }); };
'use strict'; var path = require('path'); var taskOpts = require('./lib/tasks.js'); module.exports = function(kbox) { var events = kbox.core.events; var engine = kbox.engine; kbox.ifApp(function(app) { // Grab the clients var Git = require('./lib/git.js'); var git = new Git(kbox, app); // Events // Install the util container for our things events.on('post-install', function(app, done) { var opts = { name: 'git', srcRoot: path.resolve(__dirname) }; engine.build(opts, done); }); // Tasks // git wrapper: kbox git COMMAND kbox.tasks.add(function(task) { task.path = [app.name, 'git']; task.description = 'Run git commands.'; task.kind = 'delegate'; task.options.push(taskOpts.gitUsername); task.options.push(taskOpts.gitEmail); task.func = function(done) { // We need to use this faux bin until the resolution of // https://github.com/syncthing/syncthing/issues/1056 git.cmd(this.payload, this.options, done); }; }); }); };
Update class integration test to use new syntax and output assertion
from unittest.mock import patch import io from thinglang import run def test_class_integration(): with patch('sys.stdin', io.StringIO('yotam\n19\n5')): assert run(""" thing Person has text name has number age setup with name self.name = name does say_hello with repeat_count number i = 0 repeat while i < repeat_count Output.write("Hello number", i, "from", self.name, "who's", self.age, "years old and is always excited to get some coding done.") i = i + 1 thing Program setup Person person = create Person(Input.get_line("What is your name?")) number age = Input.get_line("What is your age?") as number if age person.age = age person.say_hello(Input.get_line("How excited are you?") as number) """).output == "What is your name?\nWhat is your age?\nHow excited are you?\n" +\ "\n".join("Hello number {} from yotam who's 19 years old and is always excited to get some coding done.".format(i) for i in range(5))
from thinglang import run def test_class_integration(): assert run(""" thing Person has text name has number age created with name self.name = name self.age = 0 does grow_up self.age = self.age + 1 does say_hello with excitement_level Output.write("Hello from", self.name, ", who's ", self.age, "and is always up for a fun game of tag.") thing Program setup text name = "yotam" text wants_to_grow_up = true #text name = Input.get_line("What is your name?") #text wants_to_grow_up = Input.get_line("Do you want to grow up?") Person person = create Person(name) if wants_to_grow_up person.grow_up() person.say_hello() """).output == """dog is dog"""
Modify subscription handler interface name
#!/usr/bin/env python2.5 ## ## @file contextOrientationTCs.py ## ## Copyright (C) 2008 Nokia. All rights reserved. ## ## ## ## ## Requires python2.5-gobject and python2.5-dbus ## ## Implements also some testing API: ## ## contextSrcPath="." sessionConfigPath="tests/python-test-library/stubs" ctxBusName = "org.freedesktop.ContextKit" ctxMgrPath = "/org/freedesktop/ContextKit/Manager" ctxMgrIfce = "org.freedesktop.ContextKit.Manager" ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber" mceBusName = "com.nokia.mce" mceRqstPath = "/com/nokia/mce/request" mceRqstIfce = "com.nokia.mce.request" scriberBusName = "org.freedesktop.context.testing.subHandler" scriberHandlerPath = "/org/freedesktop/context/testing/subHandler/request" scriberHandlerIfce = "org.freedesktop.context.testing.subHandler.request" scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0" scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1" scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2" properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp']
#!/usr/bin/env python2.5 ## ## @file contextOrientationTCs.py ## ## Copyright (C) 2008 Nokia. All rights reserved. ## ## ## ## ## Requires python2.5-gobject and python2.5-dbus ## ## Implements also some testing API: ## ## contextSrcPath="." sessionConfigPath="tests/python-test-library/stubs" ctxBusName = "org.freedesktop.ContextKit" ctxMgrPath = "/org/freedesktop/ContextKit/Manager" ctxMgrIfce = "org.freedesktop.ContextKit.Manager" ctxScriberIfce = "org.freedesktop.ContextKit.Subscriber" mceBusName = "com.nokia.mce" mceRqstPath = "/com/nokia/mce/request" mceRqstIfce = "com.nokia.mce.request" testBusName = "org.freedesktop.context.testing" testRqstPath = "/org/freedesktop/context/testing/request" testRqstIfce = "org.freedesktop.context.testing.request" scriberOnePath = "/org/freedesktop/ContextKit/Subscribers/0" scriberTwoPath = "/org/freedesktop/ContextKit/Subscribers/1" scriberThirdPath = "/org/freedesktop/ContextKit/Subscribers/2" properties = ['Context.Device.Orientation.facingUp','Context.Device.Orientation.edgeUp']
Add fail option to testing harness
package net.teamio.blockunit; /** * Created by oliver on 2017-07-03. */ public class TestingHarness { public void assertEquals(int a, int b) { if (a != b) { throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b); } } public void assertEquals(boolean a, boolean b) { if (a != b) { throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b); } } public void assertNull(Object o) { if (o != null) { throw new TestAssertionException("AssertNull: passed object is not null"); } } public void assertNotNull(Object o) { if (o == null) { throw new TestAssertionException("AssertNotNull: passed object is null"); } } public void assertTrue(boolean b) { if (!b) { throw new TestAssertionException("AssertTrue: passed value is false"); } } public void assertFalse(boolean b) { if (b) { throw new TestAssertionException("AssertFalse: passed value is true"); } } public void fail() { throw new TestAssertionException("Test failed"); } public void fail(String message) { throw new TestAssertionException("Test failed: %s", message); } }
package net.teamio.blockunit; /** * Created by oliver on 2017-07-03. */ public class TestingHarness { public void assertEquals(int a, int b) { if (a != b) { throw new TestAssertionException("AssertEquals: %d is not equal to %d", a, b); } } public void assertEquals(boolean a, boolean b) { if (a != b) { throw new TestAssertionException("AssertEquals: %s is not equal to %s", a, b); } } public void assertNull(Object o) { if (o != null) { throw new TestAssertionException("AssertNull: passed object is not null"); } } public void assertNotNull(Object o) { if (o == null) { throw new TestAssertionException("AssertNotNull: passed object is null"); } } public void assertTrue(boolean b) { if (!b) { throw new TestAssertionException("AssertTrue: passed value is false"); } } public void assertFalse(boolean b) { if (b) { throw new TestAssertionException("AssertFalse: passed value is true"); } } }
Check for the existance of the settings file and report if its not there
""" MCServer Tools config loader """ import json import os.path from mcserver import MCServerError class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ try: with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) except: raise MCServerError('Could not open settings file: {}'.format(self.settings_file)) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings
""" MCServer Tools config loader """ import json import os.path class CoreConfig(object): """ MCServer Tools configuration """ SETTINGS_FILE = 'mcserver.settings' def __init__(self, path): """ Load configuration from the given file path """ self.settings_file = os.path.join(path, self.SETTINGS_FILE) self._settings = {} self._load_settings() def _load_settings(self): """ Load the settings from disk """ with open(self.settings_file, 'r') as fh: self._settings = json.load(fh) def get(self, property, default = None): """ Try to get the property value. If the property was not found then return the given default. """ if property not in self._settings: return default return self._settings[property] def has(self, property): """ Check if the config has the given property. """ return property in self._settings
Add linux in build options
module.exports = function (grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['win', 'osx', 'linux'], buildDir: './build', version: '0.12.1' }, src: [ 'index.html', 'package.json', './components/**/*', './css/**/*', './images/**/*', './js/**/*', './node_module/**/*' ] } }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('build', ['nodewebkit']); };
module.exports = function (grunt) { grunt.initConfig({ nodewebkit: { options: { platforms: ['win', 'osx'], buildDir: './build', version: '0.12.1' }, src: [ 'index.html', 'package.json', './components/**/*', './css/**/*', './images/**/*', './js/**/*', './node_module/**/*' ] } }); grunt.loadNpmTasks('grunt-node-webkit-builder'); grunt.registerTask('build', ['nodewebkit']); };
Add comment for users delete route
import koaRouter from 'koa-router' import {create, remove} from './collection' const router = koaRouter() router.post('/', function* () { let login = this.request.body.login , password = this.request.body.password try { yield create(login, password) this.status = 201 this.type = 'json' this.body = {message: 'User was successfully created'} } catch(err) { this.throw(500, err) } }) /** * @api {delete} /v1/users Exclude a user * @apiGroup Users * @apiHeader {String} Basic Authorization * @apiSuccessExample {json} Success * HTTP/1.1 200 User was successfully deleted * @apiErrorExample {json} Error * HTTP/1.1 422 Precondition Failed */ router.delete('/', function* () { let name = this.user.name , password = this.user.password try { yield remove(name, password) this.status = 200 this.type = 'json' this.body = {message: 'User was successfully deleted'} } catch(err) { this.throw(422, err) } }) export default router
import koaRouter from 'koa-router' import {create, remove} from './collection' const router = koaRouter() router.post('/', function* () { let login = this.request.body.login , password = this.request.body.password try { yield create(login, password) this.status = 201 this.type = 'json' this.body = {message: 'User was successfully created'} } catch(err) { this.throw(500, err) } }) router.delete('/', function* () { let name = this.user.name , password = this.user.password try { yield remove(name, password) this.status = 200 this.type = 'json' this.body = {message: 'User was successfully deleted'} } catch(err) { this.throw(500, err) } }) export default router
Add in largest scale with high pb cutoff
import sys ''' Cleans an MS with a single channel given a mask and a model ''' vis = sys.argv[4] model = sys.argv[5] mask = sys.argv[6] out_root = vis[:-3] clean(vis=vis, imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40, 80], threshold='2.2mJy/beam', imagermode='mosaic', gain=0.5, imsize=[4096, 4096], weighting='natural', robust=0.0, niter=50000, pbcor=True, minpb=0.7, interpolation='linear', usescratch=True, phasecenter='J2000 01h33m50.904 +30d39m35.79', veltype='radio', outframe='LSRK', modelimage=model, mask=mask)
import sys ''' Cleans an MS with a single channel given a mask and a model ''' vis = sys.argv[4] model = sys.argv[5] mask = sys.argv[6] out_root = vis[:-3] clean(vis=vis, imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40], threshold='2.2mJy/beam', imagermode='mosaic', gain=0.5, imsize=[4096, 4096], weighting='natural', robust=0.0, niter=50000, pbcor=True, minpb=0.7, interpolation='linear', usescratch=True, phasecenter='J2000 01h33m50.904 +30d39m35.79', veltype='radio', outframe='LSRK', modelimage=model, mask=mask)
Change array to object for data
/** * BaseCache it's a simple static cache * * @namespace Barba.BaseCache * @type {Object} */ var BaseCache = { /** * The array that keeps everything. * * @memberOf Barba.BaseCache * @type {Array} */ data: {}, /** * Helper to extend the object * * @memberOf Barba.BaseCache * @private * @param {Object} newObject * @return {Object} newInheritObject */ extend: function(obj) { return Utils.extend(this, obj); }, /** * Set a key, value data, mainly Barba is going to save Ajax * promise object. * * @memberOf Barba.BaseCache * @param {String} key * @param {*} value */ set: function(key, val) { this.data[key] = val; }, /** * Retrieve the data by the key * * @memberOf Barba.BaseCache * @param {String} key * @return {*} */ get: function(key) { return this.data[key]; }, /** * Reset all the cache stored * * @memberOf Barba.BaseCache */ reset: function() { this.data = {}; } }; module.exports = BaseCache;
/** * BaseCache it's a simple static cache * * @namespace Barba.BaseCache * @type {Object} */ var BaseCache = { /** * The array that keeps everything. * * @memberOf Barba.BaseCache * @type {Array} */ data: [], /** * Helper to extend the object * * @memberOf Barba.BaseCache * @private * @param {Object} newObject * @return {Object} newInheritObject */ extend: function(obj) { return Utils.extend(this, obj); }, /** * Set a key, value data, mainly Barba is going to save Ajax * promise object. * * @memberOf Barba.BaseCache * @param {String} key * @param {*} value */ set: function(key, val) { this.data[key] = val; }, /** * Retrieve the data by the key * * @memberOf Barba.BaseCache * @param {String} key * @return {*} */ get: function(key) { return this.data[key]; }, /** * Reset all the cache stored * * @memberOf Barba.BaseCache */ reset: function() { this.data = []; } }; module.exports = BaseCache;
Add gevent 1.0 as a dependency
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='ouimeaux', version=version, description="Python API to Belkin WeMo devices", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ian McCracken', author_email='ian.mccracken@gmail.com', url='', license='BSD', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, dependency_links = [ 'https://github.com/downloads/SiteSupport/gevent/gevent-1.0rc2.tar.gz#egg=gevent-1.0.rc2' ], install_requires=[ 'gevent >= 1.0rc2', ], entry_points=""" # -*- Entry points: -*- """, )
from setuptools import setup, find_packages import sys, os version = '0.1' setup(name='ouimeaux', version=version, description="Python API to Belkin WeMo devices", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', author='Ian McCracken', author_email='ian.mccracken@gmail.com', url='', license='BSD', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
Update test_amp_is_canonical() with new naming.
<?php /** * Tests for amp.php. * * @package AMP */ /** * Tests for amp.php. */ class Test_AMP extends WP_UnitTestCase { /** * Tear down and clean up. */ public function tearDown() { parent::tearDown(); remove_theme_support( 'amp' ); } /** * Test amp_is_canonical(). * * @covers amp_is_canonical() */ public function test_amp_is_canonical() { remove_theme_support( 'amp' ); $this->assertFalse( amp_is_canonical() ); add_theme_support( 'amp' ); $this->assertTrue( amp_is_canonical() ); remove_theme_support( 'amp' ); add_theme_support( 'amp', array( 'template_dir' => 'amp-templates', ) ); $this->assertFalse( amp_is_canonical() ); remove_theme_support( 'amp' ); add_theme_support( 'amp', array( 'custom_prop' => 'something', ) ); $this->assertTrue( amp_is_canonical() ); } }
<?php /** * Tests for amp.php. * * @package AMP */ /** * Tests for amp.php. */ class Test_AMP extends WP_UnitTestCase { /** * Tear down and clean up. */ public function tearDown() { parent::tearDown(); remove_theme_support( 'amp' ); } /** * Test amp_is_canonical(). * * @covers amp_is_canonical() */ public function test_amp_is_canonical() { remove_theme_support( 'amp' ); $this->assertFalse( amp_is_canonical() ); add_theme_support( 'amp' ); $this->assertTrue( amp_is_canonical() ); remove_theme_support( 'amp' ); add_theme_support( 'amp', array( 'template_path' => get_template_directory() . 'amp-templates/', ) ); $this->assertFalse( amp_is_canonical() ); remove_theme_support( 'amp' ); add_theme_support( 'amp', array( 'custom_prop' => 'something', ) ); $this->assertTrue( amp_is_canonical() ); } }
Fix NPE for command with no arguments [jes: fixed whitespace and commit message] Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>
package com.github.maven_nar; import java.util.ArrayList; import java.util.List; public class ProcessLibraryCommand { /** * The executable to run * * @parameter default-value="" */ private String executable; /** * The library type that this command is valid for * * @parameter default-value="" */ private String libraryType; /** * Any additional arguments to pass into the executable * * @parameter default-value="" */ private List<String> arguments; public List<String> getCommandList() { List<String> command = new ArrayList<String>(); command.add(executable); if (arguments != null) { command.addAll(arguments); } return command; } public String getExecutable() { return executable; } public void setExecutable(String executable) { this.executable = executable; } public List<String> getArguments() { return arguments; } public void setArguments(List<String> arguments) { this.arguments = arguments; } public String getType() { // TODO Auto-generated method stub return libraryType; } }
package com.github.maven_nar; import java.util.ArrayList; import java.util.List; public class ProcessLibraryCommand { /** * The executable to run * * @parameter default-value="" */ private String executable; /** * The library type that this command is valid for * * @parameter default-value="" */ private String libraryType; /** * Any additional arguments to pass into the executable * * @parameter default-value="" */ private List<String> arguments; public List<String> getCommandList() { List<String> command = new ArrayList<String>(); command.add(executable); command.addAll(arguments); return command; } public String getExecutable() { return executable; } public void setExecutable(String executable) { this.executable = executable; } public List<String> getArguments() { return arguments; } public void setArguments(List<String> arguments) { this.arguments = arguments; } public String getType() { // TODO Auto-generated method stub return libraryType; } }
Disable ExampleDecoder testing on go < 1.8 ... because it fails as the error message returned by stdlib changed with go1.8.
// The original error message returned by stdlib changed with go1.8. // We only test the latest release. // //+build go1.8 forcego1.8 package jsonptrerror_test import ( "fmt" "strings" "github.com/dolmen-go/jsonptrerror" ) func ExampleDecoder() { decoder := jsonptrerror.NewDecoder(strings.NewReader( `{"key": "x", "value": 5}`, )) var out struct { Key string `json:"key"` Value bool `json:"value"` } err := decoder.Decode(&out) fmt.Println(err) if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok { fmt.Println("Original error:", err.UnmarshalTypeError.Error()) fmt.Println("Error location:", err.Pointer) } // Output: // /value: cannot unmarshal number into Go value of type bool // Original error: json: cannot unmarshal number into Go struct field .value of type bool // Error location: /value }
package jsonptrerror_test import ( "fmt" "strings" "github.com/dolmen-go/jsonptrerror" ) func ExampleDecoder() { decoder := jsonptrerror.NewDecoder(strings.NewReader( `{"key": "x", "value": 5}`, )) var out struct { Key string `json:"key"` Value bool `json:"value"` } err := decoder.Decode(&out) fmt.Println(err) if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok { fmt.Println("Original error:", err.UnmarshalTypeError.Error()) fmt.Println("Error location:", err.Pointer) } // Output: // /value: cannot unmarshal number into Go value of type bool // Original error: json: cannot unmarshal number into Go struct field .value of type bool // Error location: /value }
Simplify the use of `phutil_get_library_root` Summary: Currently, in order to retrieve the library root of the current phutil module, the following code is required: ```lang=php $library = phutil_get_current_library_name(); $root = phutil_get_library_root($library); ``` This can be simplified by allowing the use of `phutil_get_library_root()` (without any arguments) to mean "get the library root for the current module". Test Plan: N/A Reviewers: #blessed_reviewers, epriestley Reviewed By: #blessed_reviewers, epriestley Subscribers: Korvin, epriestley Differential Revision: https://secure.phabricator.com/D11326
<?php function phutil_get_library_root($library = null) { if (!$library) { $library = phutil_get_current_library_name(); } $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
<?php function phutil_get_library_root($library) { $bootloader = PhutilBootloader::getInstance(); return $bootloader->getLibraryRoot($library); } function phutil_get_library_root_for_path($path) { foreach (Filesystem::walkToRoot($path) as $dir) { if (Filesystem::pathExists($dir.'/__phutil_library_init__.php')) { return $dir; } } return null; } function phutil_get_library_name_for_root($path) { $path = rtrim(Filesystem::resolvePath($path), '/'); $bootloader = PhutilBootloader::getInstance(); $libraries = $bootloader->getAllLibraries(); foreach ($libraries as $library) { $root = $bootloader->getLibraryRoot($library); if (rtrim(Filesystem::resolvePath($root), '/') == $path) { return $library; } } return null; } function phutil_get_current_library_name() { $caller = head(debug_backtrace(false)); $root = phutil_get_library_root_for_path($caller['file']); return phutil_get_library_name_for_root($root); } /** * Warns about use of deprecated behavior. */ function phutil_deprecated($what, $why) { PhutilErrorHandler::dispatchErrorMessage( PhutilErrorHandler::DEPRECATED, $what, array( 'why' => $why, )); }
Disable Express' view components (we use our own)
/** server The backbone of the server module. In development, this runs proxied through BrowserSync server. @param {Object} options Options passed on to "globals" @param {Function} next Called when server successfully initialized **/ var reorg = require("reorg"); module.exports = reorg(function(options, next) { // Globals require("./globals")(options); var server = global.shipp.framework({ strict: true }), middleware = require("./middleware"), Utils = require("./utils"); // Remove views functionality (we handle this in our compilers) server.disable("view cache"); server.disable("view engine"); server.disable("views"); // Remove powered-by header for security server.disable("x-powered-by"); [ // User-defined middleware middleware("beforeAll"), // Common middleware: logging, favicons, cookie parsing, sessions and body parsing require("./common")(), // User-defined middleware middleware("beforeRoutes"), // Static and compiled routes require("./routes")(), // Data-server require("./data-server")(), // User-defined middleware middleware("afterRoutes") ].forEach(function(library) { Utils.useMiddleware(server, library); }); // Error handling: please see errors middleware for explanation of structure require("./errors")(server, middleware("errorHandler")); // Find open port and set up graceful shutdown require("./lifecycle")(server, next); }, "object", ["function", function() {}]);
/** server The backbone of the server module. In development, this runs proxied through BrowserSync server. @param {Object} options Options passed on to "globals" @param {Function} next Called when server successfully initialized **/ var reorg = require("reorg"); module.exports = reorg(function(options, next) { // Globals require("./globals")(options); var server = global.shipp.framework({ strict: true }), middleware = require("./middleware"), Utils = require("./utils"); // Remove powered-by header for security server.disable("x-powered-by"); [ // User-defined middleware middleware("beforeAll"), // Common middleware: logging, favicons, cookie parsing, sessions and body parsing require("./common")(), // User-defined middleware middleware("beforeRoutes"), // Static and compiled routes require("./routes")(), // Data-server require("./data-server")(), // User-defined middleware middleware("afterRoutes") ].forEach(function(library) { Utils.useMiddleware(server, library); }); // Error handling: please see errors middleware for explanation of structure require("./errors")(server, middleware("errorHandler")); // Find open port and set up graceful shutdown require("./lifecycle")(server, next); }, "object", ["function", function() {}]);
Fix defaults for Session config
<?php return [ /** * The driver to use to store the session (defaults to `file`) */ 'driver' => getenv('SESSION_DRIVER') ?: 'file', /** * The name of the cookie that is set in a visitors browser */ 'cookie' => getenv('SESSION_COOKIE') ?: 'lumberjack_session', /** * How long the session will persist for */ 'lifetime' => getenv('SESSION_LIFETIME') ?: 120, /** * The URL path that will be considered valid for the cookie. Normally this is the * root of the domain but might need to be changed if serving WordPress from a sub-directory. */ 'path' => '/', /** * The domain that the cookie is valid for */ 'domain' => getenv('SESSION_DOMAIN') ?: null, /** * If true, the cookie will only be sent if the connection is done over HTTPS */ 'secure' => getenv('SESSION_SECURE_COOKIE') ?: false, /** * If true, JavaScript will not be able to access the cookie data */ 'http_only' => true, /** * Should the session data be encrypted when stored? */ 'encrypt' => false, /** * When using the `file` driver this is the path to which session data is stored. * If none is specified the default PHP location will be used. */ 'files' => false, ];
<?php return [ /** * The driver to use to store the session (defaults to `file`) */ 'driver' => getenv('SESSION_DRIVER') ?? 'file', /** * The name of the cookie that is set in a visitors browser */ 'cookie' => getenv('SESSION_COOKIE') ?? 'lumberjack_session', /** * How long the session will persist for */ 'lifetime' => getenv('SESSION_LIFETIME') ?? 120, /** * The URL path that will be considered valid for the cookie. Normally this is the * root of the domain but might need to be changed if serving WordPress from a sub-directory. */ 'path' => '/', /** * The domain that the cookie is valid for */ 'domain' => getenv('SESSION_DOMAIN') ?? null, /** * If true, the cookie will only be sent if the connection is done over HTTPS */ 'secure' => getenv('SESSION_SECURE_COOKIE') ?? false, /** * If true, JavaScript will not be able to access the cookie data */ 'http_only' => true, /** * Should the session data be encrypted when stored? */ 'encrypt' => false, /** * When using the `file` driver this is the path to which session data is stored. * If none is specified the default PHP location will be used. */ 'files' => false, ];
Set a default api path
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from rest_framework_bulk.routes import BulkRouter from rest_surveys.views import ( SurveyViewSet, SurveyResponseViewSet, ) # API # With trailing slash appended: router = BulkRouter() router.register(r'surveys', SurveyViewSet, base_name='survey') router.register(r'survey-responses', SurveyResponseViewSet, base_name='survey-response') slashless_router = BulkRouter(trailing_slash=False) slashless_router.registry = router.registry[:] urlpatterns = [ url(r'^{api_path}'.format( api_path=settings.REST_SURVEYS.get('API_PATH', 'api/')), include(router.urls)), url(r'^{api_path}'.format( api_path=settings.REST_SURVEYS.get('API_PATH', 'api/')), include(slashless_router.urls)), ]
from __future__ import unicode_literals from django.conf import settings from django.conf.urls import include, url from rest_framework_bulk.routes import BulkRouter from rest_surveys.views import ( SurveyViewSet, SurveyResponseViewSet, ) # API # With trailing slash appended: router = BulkRouter() router.register(r'surveys', SurveyViewSet, base_name='survey') router.register(r'survey-responses', SurveyResponseViewSet, base_name='survey-response') slashless_router = BulkRouter(trailing_slash=False) slashless_router.registry = router.registry[:] urlpatterns = [ url(r'^{api_path}'.format(api_path=settings.REST_SURVEYS['API_PATH']), include(router.urls)), url(r'^{api_path}'.format(api_path=settings.REST_SURVEYS['API_PATH']), include(slashless_router.urls)), ]
Fix missing public decls that were breaking tests
package com.xtremelabs.robolectric.shadows; import com.xtremelabs.robolectric.util.Implementation; import com.xtremelabs.robolectric.util.Implements; import android.media.AudioManager; @SuppressWarnings({"UnusedDeclaration"}) @Implements(AudioManager.class) public class ShadowAudioManager { private int streamMaxVolume = 15; private int streamVolume = 7; private int flags; @Implementation public int getStreamMaxVolume(int streamType) { return streamMaxVolume; } @Implementation public int getStreamVolume(int streamType) { return streamVolume; } @Implementation public void setStreamVolume(int streamType, int index, int flags) { this.streamVolume = index; this.flags = flags; } public int getStreamMaxVolume() { return streamMaxVolume; } public void setStreamMaxVolume(int streamMaxVolume) { this.streamMaxVolume = streamMaxVolume; } public int getStreamVolume() { return streamVolume; } public void setStreamVolume(int streamVolume) { this.streamVolume = streamVolume; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } }
package com.xtremelabs.robolectric.shadows; import com.xtremelabs.robolectric.util.Implementation; import com.xtremelabs.robolectric.util.Implements; import android.media.AudioManager; @SuppressWarnings({"UnusedDeclaration"}) @Implements(AudioManager.class) public class ShadowAudioManager { private int streamMaxVolume = 15; private int streamVolume = 7; private int flags; @Implementation public int getStreamMaxVolume(int streamType) { return streamMaxVolume; } @Implementation int getStreamVolume(int streamType) { return streamVolume; } @Implementation void setStreamVolume(int streamType, int index, int flags) { this.streamVolume = index; this.flags = flags; } public int getStreamMaxVolume() { return streamMaxVolume; } public void setStreamMaxVolume(int streamMaxVolume) { this.streamMaxVolume = streamMaxVolume; } public int getStreamVolume() { return streamVolume; } public void setStreamVolume(int streamVolume) { this.streamVolume = streamVolume; } public int getFlags() { return flags; } public void setFlags(int flags) { this.flags = flags; } }
Store both username and displayName in server session
var passport = require('passport'), GitHubStrategy = require('passport-github').Strategy, config = require('./config'); passport.serializeUser(function(user, done) { var sessionUser = {username: user.username, displayName: user.displayName, avatar: user._json.avatar_url, github_id: user.id} done(null, sessionUser); }); passport.deserializeUser(function(sessionUser, done) { done(null, sessionUser); }); passport.use(new GitHubStrategy({ clientID: config.github_clientID, clientSecret: config.github_clientSecret, callbackURL: config.github_callback }, function(accessToken, refreshToken, profile, done) { // create persistent store user if not found in db return done(null, profile); }) ); module.exports = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/login') };
var passport = require('passport'), GitHubStrategy = require('passport-github').Strategy, config = require('./config'); passport.serializeUser(function(user, done) { var sessionUser = {name: user.displayName, avatar: user._json.avatar_url, github_id: user.id} done(null, sessionUser); }); passport.deserializeUser(function(sessionUser, done) { done(null, sessionUser); }); passport.use(new GitHubStrategy({ clientID: config.github_clientID, clientSecret: config.github_clientSecret, callbackURL: config.github_callback }, function(accessToken, refreshToken, profile, done) { // create persistent store user if not found in db return done(null, profile); }) ); module.exports = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/login') };
Update plugin to work with the new build-wepack hook signature.
import path from 'path'; export default () => () => (webpackConfig = {}) => { // Register extensions webpackConfig.resolve.extensions.push('.ts', '.tsx'); const jsLoader = webpackConfig.module.loaders.find(loader => loader.id === 'babel'); // Make sure ts and tsx files are processed by babel after being the typescript compiler is done const babelLoader = { ...jsLoader, id: 'babel-ts', test: /\.tsx?$/ }; // (Webpack calls loaders in reverse order, so we add babel before typescript) webpackConfig.module.loaders.push(babelLoader); // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. const tsLoader = { test: /\.tsx?$/, loader: 'ts-loader', }; webpackConfig.module.loaders.push(tsLoader); // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. const tsPreLoader = { test: /\.js$/, loader: 'source-map-loader', }; webpackConfig.module.preLoaders.push(tsPreLoader); const modulesPath = path.join(__dirname, '../../node_modules'); webpackConfig.resolveLoader.root.push(modulesPath); return webpackConfig; };
import path from 'path'; export default ({ previousValue: prevWebpackConfig }) => () => () => { const webpackConfig = { ...prevWebpackConfig }; // Register extensions webpackConfig.resolve.extensions.push('.ts', '.tsx'); // Make sure ts and tsx files are processed by babel after being the typescript compiler is done const babelLoader = { test: /\.tsx?$/, loader: 'babel-loader', }; // (Webpack calls loaders in reverse order, so we add babel before typescript) webpackConfig.module.loaders.push(babelLoader); // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. const tsLoader = { test: /\.tsx?$/, loader: 'ts-loader', }; webpackConfig.module.loaders.push(tsLoader); // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. const tsPreLoader = { test: /\.js$/, loader: 'source-map-loader', }; webpackConfig.module.preLoaders.push(tsPreLoader); const modulesPath = path.join(__dirname, '../../node_modules'); webpackConfig.resolveLoader.root.push(modulesPath); return webpackConfig; };
Add comment for test account
import config from 'config'; import { Router } from 'express'; const router = Router(); router.post('/student', (req, res) => { if (req.body.username === 'test' && req.body.password === 'test') { console.log('student logged in, account:', req.body.username); res.cookie(config.cookie_path.name, req.body.username, { signed: true, }); // 用户信息最好用json-server查询 res.send({ userId: 'test', phoneNumber: '15800001111', type: 'student', name: '小明', email: 'xiaoming@163.com', campus: 'xianlin', orders: [1, 2, 3], }); } else { console.error("测试账号:test,测试密码:test"); res.send({ error: '用户名和密码不匹配', }); } }); router.post('/knight', (req, res) => { console.log('knight login', req.body.username, req.body.password); }); export default router;
import config from 'config'; import { Router } from 'express'; const router = Router(); router.post('/student', (req, res) => { if (req.body.username === 'test' && req.body.password === 'test') { console.log('student logged in, account:', req.body.username); res.cookie(config.cookie_path.name, req.body.username, { signed: true, }); // 用户信息最好用json-server查询 res.send({ userId: 'test', phoneNumber: '15800001111', type: 'student', name: '小明', email: 'xiaoming@163.com', campus: 'xianlin', orders: [1, 2, 3], }); } else { res.send({ error: '用户名和密码不匹配', }); } }); router.post('/knight', (req, res) => { console.log('knight login', req.body.username, req.body.password); }); export default router;
Use correct comparison operator for TEXTAREA in isEditorBlur
export default class FocusHandler { inputFocused = false; editorMouseDown = false; onEditorMouseDown = ():void => { this.editorFocused = true; } onInputMouseDown = ():void => { this.inputFocused = true; } isEditorBlur = (event): void => { if ( (event.target.tagName === 'INPUT' || event.target.tagName === 'LABEL' || event.target.tagName === 'TEXTAREA') && !this.editorFocused ) { this.inputFocused = false; return true; } else if ( (event.target.tagName !== 'INPUT' || event.target.tagName !== 'LABEL' || event.target.tagName !== 'TEXTAREA') && !this.inputFocused ) { this.editorFocused = false; return true; } return false; }; isEditorFocused = ():void => { if (!this.inputFocused) { return true; } this.inputFocused = false; return false; } isToolbarFocused = ():void => { if (!this.editorFocused) { return true; } this.editorFocused = false; return false; } isInputFocused = ():void => this.inputFocused; }
export default class FocusHandler { inputFocused = false; editorMouseDown = false; onEditorMouseDown = ():void => { this.editorFocused = true; } onInputMouseDown = ():void => { this.inputFocused = true; } isEditorBlur = (event): void => { if ( (event.target.tagName === 'INPUT' || event.target.tagName === 'LABEL' || event.target.tagName === 'TEXTAREA') && !this.editorFocused ) { this.inputFocused = false; return true; } else if ( (event.target.tagName !== 'INPUT' || event.target.tagName !== 'LABEL' || event.target.tagName === 'TEXTAREA') && !this.inputFocused ) { this.editorFocused = false; return true; } return false; }; isEditorFocused = ():void => { if (!this.inputFocused) { return true; } this.inputFocused = false; return false; } isToolbarFocused = ():void => { if (!this.editorFocused) { return true; } this.editorFocused = false; return false; } isInputFocused = ():void => this.inputFocused; }
blueprints/route-test: Use `options.entity-name` for test description
'use strict'; const path = require('path'); const stringUtil = require('ember-cli-string-utils'); const useTestFrameworkDetector = require('../test-framework-detector'); module.exports = useTestFrameworkDetector({ description: 'Generates a route unit test.', availableOptions: [ { name: 'reset-namespace', type: Boolean } ], fileMapTokens: function() { return { __test__: function (options) { let moduleName = options.locals.moduleName; if (options.pod) { moduleName = 'route'; } return `${moduleName}-test`; }, __path__: function(options) { if (options.pod) { return path.join(options.podPath, options.locals.moduleName); } return 'routes'; } }; }, locals: function(options) { let moduleName = options.entity.name; if (options.resetNamespace) { moduleName = moduleName.split('/').pop(); } return { friendlyTestDescription: ['Unit', 'Route', options.entity.name].join(' | '), moduleName: stringUtil.dasherize(moduleName) }; }, });
'use strict'; const testInfo = require('ember-cli-test-info'); const path = require('path'); const stringUtil = require('ember-cli-string-utils'); const useTestFrameworkDetector = require('../test-framework-detector'); module.exports = useTestFrameworkDetector({ description: 'Generates a route unit test.', availableOptions: [ { name: 'reset-namespace', type: Boolean } ], fileMapTokens: function() { return { __test__: function (options) { let moduleName = options.locals.moduleName; if (options.pod) { moduleName = 'route'; } return `${moduleName}-test`; }, __path__: function(options) { if (options.pod) { return path.join(options.podPath, options.locals.moduleName); } return 'routes'; } }; }, locals: function(options) { let moduleName = options.entity.name; if (options.resetNamespace) { moduleName = moduleName.split('/').pop(); } return { friendlyTestDescription: testInfo.description(options.entity.name, 'Unit', 'Route'), moduleName: stringUtil.dasherize(moduleName) }; }, });
Add authenticate.py to installed scripts
from setuptools import setup setup( name='bwapi', version='3.2.0', description='A software development kit for the Brandwatch API', url='https://github.com/BrandwatchLtd/api_sdk', author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden', author_email='amyb@brandwatch.com, paul@brandwatch.com, jess@brandwatch.com', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7' ], py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'], scripts=['authenticate.py'], install_requires=['requests'], tests_require=['responses'] )
from setuptools import setup setup( name='bwapi', version='3.2.0', description='A software development kit for the Brandwatch API', url='https://github.com/BrandwatchLtd/api_sdk', author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden', author_email='amyb@brandwatch.com, paul@brandwatch.com, jess@brandwatch.com', license='License :: OSI Approved :: MIT License', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7' ], py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'], install_requires=['requests'], tests_require=['responses'] )
Fix des alertes sur des attributs inexistants
<?php namespace ETNA\FeatureContext; trait setUpScenarioDirectories { /** @Var string */ private $requests_path; /** @Var string */ private $results_path; /** * @BeforeScenario */ public function setUpScenarioDirectories($event) { if ($event instanceof \Behat\Behat\Event\ScenarioEvent) { $this->results_path = realpath(dirname($event->getScenario()->getFile())) . '/results/'; $this->requests_path = realpath(dirname($event->getScenario()->getFile())) . '/requests/'; } else { $this->results_path = realpath(dirname($event->getOutline()->getFile())) . '/results/'; $this->requests_path = realpath(dirname($event->getOutline()->getFile())) . '/requests/'; } } }
<?php namespace ETNA\FeatureContext; trait setUpScenarioDirectories { /** * @BeforeScenario */ public function setUpScenarioDirectories($event) { if ($event instanceof \Behat\Behat\Event\ScenarioEvent) { $this->results_path = realpath(dirname($event->getScenario()->getFile())) . '/results/'; $this->requests_path = realpath(dirname($event->getScenario()->getFile())) . '/requests/'; } else { $this->results_path = realpath(dirname($event->getOutline()->getFile())) . '/results/'; $this->requests_path = realpath(dirname($event->getOutline()->getFile())) . '/requests/'; } } }
Add dummy @TransactionAttribute on read method.
package jannotate.beans; import jannotate.domain.Annotation; import java.util.List; import javax.annotation.Resource; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Transient; import javax.ejb.*; @Stateless public class AnnotationEjb { @PersistenceContext EntityManager em; @TransactionAttribute() public List<Annotation> getAnnotations() { return (List<Annotation>) em.createQuery( "SELECT a FROM Annotation a order by a.api, a.name").getResultList(); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public String addEntry(Annotation instance) { System.out.println("AnnotationEjb.addEntry():" + instance); em.persist(instance); return "index"; } }
package jannotate.beans; import jannotate.domain.Annotation; import java.util.List; import javax.annotation.Resource; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Transient; import javax.ejb.*; @Stateless public class AnnotationEjb { @PersistenceContext EntityManager em; public List<Annotation> getAnnotations() { return (List<Annotation>) em.createQuery( "SELECT a FROM Annotation a order by a.api, a.name").getResultList(); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public String addEntry(Annotation instance) { System.out.println("AnnotationEjb.addEntry():" + instance); em.persist(instance); return "index"; } }
Correct local references when loading uncompiled source
/** * @fileoverview Bootstrapper for local development. * * This script can be used during development instead of the compiled firebase-simple-login.js. * It pulls in the raw source files, so no compilation step is required (though if you * change any dependencies, e.g. by adding goog.require statements, you'll need to * run compile-js.sh to rebuild deps.js) * * This script pulls in google closure's base.js and our dependencies file * automatically. All other required scripts will be pulled in based on goog.require * statements. */ // Figure out the base path of firebase-simple-login-local.js. var basePath = null; var scripts = document.getElementsByTagName('script'); for (var i = scripts.length - 1; i >= 0; i--) { var src = scripts[i].src; var l = src.indexOf('firebase-simple-login-local.js'); if (l != -1) { basePath = src.substr(0, l); break; } } if (basePath === null) throw "Couldn't determine location of firebase-simple-login-local.js. WHAT DID YOU DO!?!?!"; document.write('<script type="text/javascript" src="' + basePath + '../../lib/closure/library/closure/goog/base.js"></script>'); document.write('<script type="text/javascript" src="' + basePath + '../deps.js"></script>'); document.write('<script type="text/javascript" src="' + basePath + 'firebase-simple-login-require.js"></script>');
/** * @fileoverview Bootstrapper for local development. * * This script can be used during development instead of the compiled firebase-simple-login.js. * It pulls in the raw source files, so no compilation step is required (though if you * change any dependencies, e.g. by adding goog.require statements, you'll need to * run compile-js.sh to rebuild deps.js) * * This script pulls in google closure's base.js and our dependencies file * automatically. All other required scripts will be pulled in based on goog.require * statements. */ // Figure out the base path of firebase-simple-login-local.js. var basePath = null; var scripts = document.getElementsByTagName('script'); for (var i = scripts.length - 1; i >= 0; i--) { var src = scripts[i].src; var l = src.indexOf('firebase-simple-login-local.js'); if (l != -1) { basePath = src.substr(0, l); break; } } if (basePath === null) throw "Couldn't determine location of firebase-simple-login-local.js. WHAT DID YOU DO!?!?!"; document.write('<script type="text/javascript" src="' + basePath + '../../build/closure/library/closure/goog/base.js"></script>'); document.write('<script type="text/javascript" src="' + basePath + '../deps.js"></script>'); document.write('<script type="text/javascript" src="' + basePath + 'firebase-simple-login-require.js"></script>');
Print stack only when env DEBUG is set
var Q = require('q'); var _ = require('lodash'); var http = require('http'); var send = require('send'); var path = require('path'); var Gaze = require('gaze').Gaze; function watch(dir) { var d = Q.defer(); dir = path.resolve(dir); var gaze = new Gaze("**/*.md", { cwd: dir }); gaze.once("all", function(e, filepath) { gaze.close(); d.resolve(filepath); }); gaze.once("error", function(err) { gaze.close(); d.reject(err); }); return d.promise; } function logError(err) { var message = err.message || err; if (process.env.DEBUG != null) message = err.stack || message; console.log(message); return Q.reject(err); }; // Exports module.exports = { watch: watch, logError: logError };
var Q = require('q'); var _ = require('lodash'); var http = require('http'); var send = require('send'); var path = require('path'); var Gaze = require('gaze').Gaze; function watch(dir) { var d = Q.defer(); dir = path.resolve(dir); var gaze = new Gaze("**/*.md", { cwd: dir }); gaze.once("all", function(e, filepath) { gaze.close(); d.resolve(filepath); }); gaze.once("error", function(err) { gaze.close(); d.reject(err); }); return d.promise; } function logError(err) { console.log(err.stack || err.message || err); return Q.reject(err); }; // Exports module.exports = { watch: watch, logError: logError };
Make ports a slice for consistency with policy violations Signed-off-by: Kevin Kirsche <18695bc9b6a48cd25cda049e45c04495c905a059@gmail.com>
package nessusProcessor // PolicyViolationMatchCriteria holds what criteria should be checked when checking for a // policy violation. type PolicyViolationMatchCriteria struct { ExternallyAccessible bool IgnoreViolationWithCriteriaMatch bool PreviousViolationCheck bool CountIf string DescriptionRegexp []string NotDescriptionRegexp []string PluginID int Ports []int OrganizationIDs []int RegionIDs []int } // FalsePositiveMatchCriteria holds what criteria should be checked when // checking for a false positive. type FalsePositiveMatchCriteria struct { PluginID int Ports []int Protocol string DescriptionRegexp []string CheckIfIsNotDefined bool SQLSolarisCheck bool }
package nessusProcessor // PolicyViolationMatchCriteria holds what criteria should be checked when checking for a // policy violation. type PolicyViolationMatchCriteria struct { ExternallyAccessible bool IgnoreViolationWithCriteriaMatch bool PreviousViolationCheck bool CountIf string DescriptionRegexp []string NotDescriptionRegexp []string PluginID int Ports []int OrganizationIDs []int RegionIDs []int } // FalsePositiveMatchCriteria holds what criteria should be checked when // checking for a false positive. type FalsePositiveMatchCriteria struct { PluginID int Port int Protocol string DescriptionRegexp []string CheckIfIsNotDefined bool SQLSolarisCheck bool }
Add password confirmation to user seeds.
var db = require('../models/db'); db.User .build({ username: 'johndoe', email: 'johndoe@tessel.io', name: 'John Doe', password: 'password', passwordConfirmation: 'password' }) .confirmPassword() .digest() .genApiKey() .save() .success(function(user){ console.log('user =>' + user.username + ' stored'); }) .error(function(err){ console.log('error ====>', err); }) db.User .build({ username: 'janedoe', email: 'janedoe@tessel.io', name: 'Jane Doe', password: 'password', passwordConfirmation: 'password' }) .confirmPassword() .digest() .genApiKey() .save() .success(function(user){ console.log('user =>' + user.username + ' stored'); }) .error(function(err){ console.log('error ====>', err); })
var db = require('../models/db'); db.User .build({ username: 'johndoe', email: 'johndoe@tessel.io', name: 'John Doe', password: 'password', }) .digest() .genApiKey() .save() .success(function(user){ console.log('user =>' + user.username + ' stored'); }) .error(function(err){ console.log('error ====>', err); }) db.User .build({ username: 'janedoe', email: 'janedoe@tessel.io', name: 'Jane Doe', password: 'password', }) .digest() .genApiKey() .save() .success(function(user){ console.log('user =>' + user.username + ' stored'); }) .error(function(err){ console.log('error ====>', err); })
Fix word count if the altered string ends up empty
function runLogEditorWordCount(){ var common = LogEditorCommon.getInstance(), previewDiv = $("div.mdd_editor_wrap textarea"); common.toolbar.append("<li id='geoachingUtilsWordCount'>Hallo<li/>"); previewDiv.on("input", function(e){ var currentText = $(e.currentTarget).val(), currentWordCount = countWords(currentText); $("#geoachingUtilsWordCount").text(currentWordCount); }); // from http://stackoverflow.com/a/18679657/527718, but slightly improved function countWords(s){ s = s.replace(/\n /, "\n"); // exclude newline with a start spacing s = s.replace(/\n/g, " ") // replace newline with space s = s.replace(/(^\s*)|(\s*$)/gi, ""); //exclude start and end white-space s = s.replace(/[ ]{2,}/gi, " "); //2 or more space to 1 if(s===""){ return 0; } else { return s.split(" ").length; } } }
function runLogEditorWordCount(){ var common = LogEditorCommon.getInstance(), previewDiv = $("div.mdd_editor_wrap textarea"); common.toolbar.append("<li id='geoachingUtilsWordCount'>Hallo<li/>"); previewDiv.on("input", function(e){ var currentText = $(e.currentTarget).val(), currentWordCount = countWords(currentText); $("#geoachingUtilsWordCount").text(currentWordCount); }); // from http://stackoverflow.com/a/18679657/527718, but slightly improved function countWords(s){ s = s.replace(/\n /, "\n"); // exclude newline with a start spacing s = s.replace(/\n/g, " ") // replace newline with space s = s.replace(/(^\s*)|(\s*$)/gi, "");//exclude start and end white-space s = s.replace(/[ ]{2,}/gi, " ");//2 or more space to 1 return s.split(' ').length; } }
Set 'darkest' as default tint
import React, { PureComponent } from 'react'; import Box from '../box'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { COLORS, TINTS } from '../../constants'; import theme from './theme.css'; const factory = (baseType, type, defaultElement) => { class Text extends PureComponent { render() { const { children, className, color, element, tint, ...others } = this.props; const classNames = cx(theme[baseType], theme[type], theme[color], theme[tint], className); const Element = element || defaultElement; return ( <Box className={classNames} data-teamleader-ui={baseType} element={Element} {...others}> {children} </Box> ); } } Text.propTypes = { children: PropTypes.node, className: PropTypes.string, color: PropTypes.oneOf(COLORS), element: PropTypes.node, tint: PropTypes.oneOf(TINTS), }; Text.defaultProps = { element: null, tint: 'darkest', }; return Text; }; export { factory as textFactory };
import React, { PureComponent } from 'react'; import Box from '../box'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { COLORS, TINTS } from '../../constants'; import theme from './theme.css'; const factory = (baseType, type, defaultElement) => { class Text extends PureComponent { render() { const { children, className, color, element, tint, ...others } = this.props; const classNames = cx(theme[baseType], theme[type], theme[color], theme[tint], className); const Element = element || defaultElement; return ( <Box className={classNames} data-teamleader-ui={baseType} element={Element} {...others}> {children} </Box> ); } } Text.propTypes = { children: PropTypes.node, className: PropTypes.string, color: PropTypes.oneOf(COLORS), element: PropTypes.node, tint: PropTypes.oneOf(TINTS), }; Text.defaultProps = { element: null, }; return Text; }; export { factory as textFactory };
Use a recurrence's label as it's unique id.
<?php namespace Plummer\Calendar; class Calendar { protected $events; protected $recurrenceTypes; protected function __construct(\Iterator $events, $recurrenceTypes) { $this->events = $events; $this->addRecurrenceTypes($recurrenceTypes); } public static function make(\Iterator $events, $recurrenceTypes = []) { return new static($events, $recurrenceTypes); } public function addEvents(array $events) { foreach($events as $event) { $this->addEvent($event); } } public function addEvent(Event $event) { $event->setCalendar($this); $this->events[] = $event; } public function addRecurrenceTypes(array $recurrenceTypes) { foreach($recurrenceTypes as $recurrenceType) { $this->addRecurrenceType($recurrenceType); } } public function addRecurrenceType(RecurrenceInterface $recurrenceType) { $this->recurrenceTypes[$recurrenceType->getLabel()] = $recurrenceType; } }
<?php namespace Plummer\Calendar; class Calendar { protected $events; protected $recurrenceTypes; protected function __construct(\Iterator $events, $recurrenceTypes) { $this->events = $events; $this->addRecurrenceTypes($recurrenceTypes); } public static function make(\Iterator $events, $recurrenceTypes = []) { return new static($events, $recurrenceTypes); } public function addEvents(array $events) { foreach($events as $event) { $this->addEvent($event); } } public function addEvent(Event $event) { $event->setCalendar($this); $this->events[] = $event; } public function addRecurrenceTypes(array $recurrenceTypes) { foreach($recurrenceTypes as $recurrenceType) { $this->addRecurrenceType($recurrenceType); } } public function addRecurrenceType(RecurrenceInterface $recurrenceType) { $this->recurrenceTypes[] = $recurrenceType; } }
Tweak wording in doc comments
<?php namespace Neos\Flow\Http; use Neos\Flow\Annotations as Flow; use Neos\Flow\Core\Bootstrap; use Psr\Http\Message\ServerRequestInterface; /** * Central authority to get hold of the active HTTP request. * When no active HTTP request can be determined (for example in CLI context) an exception will be thrown * * Note: Usually this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances * * @Flow\Scope("singleton") */ final class ActiveHttpRequestProvider { /** * @Flow\Inject * @var Bootstrap */ protected $bootstrap; /** * Returns the currently active HTTP request, if available. * If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown * * @return ServerRequestInterface * @throws Exception */ public function getActiveHttpRequest(): ServerRequestInterface { $requestHandler = $this->bootstrap->getActiveRequestHandler(); if (!$requestHandler instanceof HttpRequestHandlerInterface) { throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131); } return $requestHandler->getHttpRequest(); } }
<?php namespace Neos\Flow\Http; use Neos\Flow\Annotations as Flow; use Neos\Flow\Core\Bootstrap; use Psr\Http\Message\ServerRequestInterface; /** * Central authority to get hold of the active HTTP request. * When no active HTTP request can be determined (for example in CLI context) an exception will be thrown * * Note: Naturally this class is not being used directly. But it is configured as factory for Psr\Http\Message\ServerRequestInterface instances * * @Flow\Scope("singleton") */ final class ActiveHttpRequestProvider { /** * @Flow\Inject * @var Bootstrap */ protected $bootstrap; /** * Returns the currently active HTTP request, if available. * If the HTTP request can't be determined (for example in CLI context) a \Neos\Flow\Http\Exception is thrown * * @return ServerRequestInterface * @throws Exception */ public function getActiveHttpRequest(): ServerRequestInterface { $requestHandler = $this->bootstrap->getActiveRequestHandler(); if (!$requestHandler instanceof HttpRequestHandlerInterface) { throw new Exception(sprintf('The active HTTP request can\'t be determined because the request handler is not an instance of %s but a %s. Use a ServerRequestFactory to create a HTTP requests in CLI context', HttpRequestHandlerInterface::class, get_class($requestHandler)), 1600869131); } return $requestHandler->getHttpRequest(); } }
Update control statement negation example
<?php // basic if - else if ($expr1) { // if body } elseif ($expr2) { // elseif body } else { // else body; } // if with a negation if (!$expr1) { // if body } // if with an operand if ($expr1 && $expr2) { // if body } else { // else body; } // if with long expression if ($expr1 && $expr2 && $expr3 && $expr4 &&) { // if body } // switch statement switch ($expr) { case 0: echo 'First case, with a break'; break; case 1: echo 'Second case, which falls through'; // no break case 2: case 3: case 4: echo 'Third case, return instead of break'; return; default: echo 'Default case'; break; } // for loop for ($i = 0; $i < 10; $i++) { // for body } // foreach loop foreach ($iterable as $key => $value) { // foreach body } // try - catch try { // try body } catch (FirstExceptionType $e) { // catch body } catch (OtherExceptionType $e) { // catch body }
<?php // basic if - else if ($expr1) { // if body } elseif ($expr2) { // elseif body } else { // else body; } // if with a negation if (! $expr1) { // if body } // if with an operand if ($expr1 && $expr2) { // if body } else { // else body; } // if with long expression if ($expr1 && $expr2 && $expr3 && $expr4 &&) { // if body } // switch statement switch ($expr) { case 0: echo 'First case, with a break'; break; case 1: echo 'Second case, which falls through'; // no break case 2: case 3: case 4: echo 'Third case, return instead of break'; return; default: echo 'Default case'; break; } // for loop for ($i = 0; $i < 10; $i++) { // for body } // foreach loop foreach ($iterable as $key => $value) { // foreach body } // try - catch try { // try body } catch (FirstExceptionType $e) { // catch body } catch (OtherExceptionType $e) { // catch body }
Make token creation a little easier to read
var assert = require('assert'); var connect = require('connect'); var csrf = require('csrf-lite'); var extend = require('obj-extend'); module.exports = function (options) { options = extend({ tokenKey: 'csrfToken', dataKey: 'body' }, options); return function connectCsrf (req, res, next) { // Grab the token off the request object or create one var token = req[options.tokenKey]; if (token === undefined) { token = csrf(); req[options.tokenKey] = token; } // Create a helper function to print a csrf form input req.csrfInput = res.locals.csrfInput = function () { return csrf.html(token); }; // CSRF validation // https://github.com/senchalabs/connect/blob/2.12.0/lib/middleware/csrf.js#L76 if (!req.method.match(/^(GET|HEAD|OPTIONS)$/)) { var data = req[options.dataKey] || {}; var valid = csrf.validate(data, token); if (!valid) { return next(connect.utils.error(403)); } } next(); }; };
var assert = require('assert'); var connect = require('connect'); var csrf = require('csrf-lite'); var extend = require('obj-extend'); module.exports = function (options) { options = extend({ tokenKey: 'csrfToken', dataKey: 'body' }, options); return function connectCsrf (req, res, next) { // Grab the token off the request object or create one var token = req[options.tokenKey] = req[options.tokenKey] || csrf(); // Create a helper function to print a csrf form input req.csrfInput = res.locals.csrfInput = function () { return csrf.html(token); }; // CSRF validation // https://github.com/senchalabs/connect/blob/2.12.0/lib/middleware/csrf.js#L76 if (!req.method.match(/^(GET|HEAD|OPTIONS)$/)) { var data = req[options.dataKey] || {}; var valid = csrf.validate(data, token); if (!valid) { return next(connect.utils.error(403)); } } next(); }; };
Fix header of Python file Now correctly points to the Python interpretor
#!/usr/bin/env python import socket, fcntl, sys #Lock to only allow one instance of this program to run pid_file = '/tmp/send.pid' fp = open(pid_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: print 'An instance of this program is already running' sys.exit(0) import Adafruit_CharLCD as LCD lcd = LCD.Adafruit_CharLCDPlate() lcd.set_color(0,0,0) listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) number_packets_received = 0 def print_lcd(): lcd.clear() lcd.message('# of packets\nreceived: ' + str(number_packets_received)) if __name__ == '__main__': while True: print_lcd() print listener.recvfrom(7777) number_packets_received += 1
#!/usr/bin/env/python import socket, fcntl, sys #Lock to only allow one instance of this program to run pid_file = '/tmp/send.pid' fp = open(pid_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: print 'An instance of this program is already running' sys.exit(0) import Adafruit_CharLCD as LCD lcd = LCD.Adafruit_CharLCDPlate() lcd.set_color(0,0,0) listener = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP) number_packets_received = 0 def print_lcd(): lcd.clear() lcd.message('# of packets\nreceived: ' + str(number_packets_received)) if __name__ == '__main__': while True: print_lcd() print listener.recvfrom(7777), '\n', type(listener) number_packets_received += 1
Update unit test to test for latest updates in the basic class template class.
<?php /* * This file is part of the Onema ClassyFile Package. * For the full copyright and license information, * please view the LICENSE file that was distributed * with this source code. */ namespace Onema\Test; use Onema\ClassyFile\Template\BasicClassTemplate; /** * BasicClassTemplateTest - Description. * * @author Juan Manuel Torres <kinojman@gmail.com> * @copyright (c) 2015, Onema * @group template */ class BasicClassTemplateTest extends \PHPUnit_Framework_TestCase { public function testDefaultTest () { $date = new \DateTime(); $templateClass = new BasicClassTemplate(); $template = $templateClass->getTemplate('foo', 'bar', 'blah', 'lala'); $this->assertRegExp(sprintf('/%s/', $date->format('Y')), $template); $this->assertRegExp(sprintf('/%s/', 'Juan Manuel Torres'), $template); } public function testCustomTest () { $expectedTemplate = sprintf('<?php%s%s%s%s%s%s%s%s%s%s', PHP_EOL, 'foo', PHP_EOL, 'bar', PHP_EOL, PHP_EOL, 'blah', PHP_EOL, 'lala', PHP_EOL); $templateClass = new BasicClassTemplate(''); $template = $templateClass->getTemplate('foo', 'bar', 'blah', 'lala'); $this->assertEquals($expectedTemplate, $template); } }
<?php /* * This file is part of the Onema ClassyFile Package. * For the full copyright and license information, * please view the LICENSE file that was distributed * with this source code. */ namespace Onema\Test; use Onema\ClassyFile\Template\BasicClassTemplate; /** * BasicClassTemplateTest - Description. * * @author Juan Manuel Torres <kinojman@gmail.com> * @copyright (c) 2015, Onema * @group template */ class BasicClassTemplateTest extends \PHPUnit_Framework_TestCase { public function testDefaultTest () { $date = new \DateTime(); $templateClass = new BasicClassTemplate(); $template = $templateClass->getTemplate('foo', 'bar', 'blah', 'lala'); $this->assertRegExp(sprintf('/%s/', $date->format('Y')), $template); $this->assertRegExp(sprintf('/%s/', 'Juan Manuel Torres'), $template); } public function testCustomTest () { $expectedTemplate = sprintf('<?php%s%s%s%s%s%s%s%s%s', '', 'foo', PHP_EOL, 'bar', PHP_EOL, 'blah', PHP_EOL, 'lala', PHP_EOL); $templateClass = new BasicClassTemplate(''); $template = $templateClass->getTemplate('foo', 'bar', 'blah', 'lala'); $this->assertEquals($expectedTemplate, $template); } }
Correct version for deploy to GAE
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test application started.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 8080 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":8080", nil) } */
//Command to run test version: //goapp serve app.yaml //Command to deploy/update application: //goapp deploy -application golangnode0 -version 0 package main import ( "fmt" "net/http" ) func helloWorld(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello World!") } func startPage(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, test application started.\n - /helloworld - show title page\n - /showinfo - show information about this thing") } func showInfo(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Inforamtion page for test project.\nLanguage - Go\nPlatform - Google Application Engine") } func init() { http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) //Wrong code for App Enine - server cant understand what it need to show //http.ListenAndServe(":80", nil) } /* func main() { fmt.Println("Hello, test server started on 80 port.\n - /helloworld - show title page\n - /showinfo - show information about this thing") http.HandleFunc("/", startPage) http.HandleFunc("/helloworld", helloWorld) http.HandleFunc("/showinfo", showInfo) http.ListenAndServe(":8080", nil) } */
Use snake case for API's URL: generic_records instead of genericRecord and species_observation instead of speciesObservation.
from __future__ import absolute_import, unicode_literals, print_function, division from django.conf.urls import url from rest_framework import routers from main.api import views as main_views router = routers.DefaultRouter() router.register(r'projects?', main_views.ProjectViewSet, 'project') router.register(r'sites?', main_views.SiteViewSet, 'site') router.register(r'datasets?', main_views.DatasetViewSet, 'dataset') router.register(r'generic_records?', main_views.GenericRecordViewSet, 'genericRecord') router.register(r'observations?', main_views.ObservationViewSet, 'observation') router.register(r'species_observations?', main_views.SpeciesObservationViewSet, 'speciesObservation') url_patterns = [ url(r'dataset/(?P<pk>\d+)/data?', main_views.DatasetDataView.as_view(), name='dataset-data') ] urls = router.urls + url_patterns
from __future__ import absolute_import, unicode_literals, print_function, division from django.conf.urls import url from rest_framework import routers from main.api import views as main_views router = routers.DefaultRouter() router.register(r'projects?', main_views.ProjectViewSet, 'project') router.register(r'sites?', main_views.SiteViewSet, 'site') router.register(r'datasets?', main_views.DatasetViewSet, 'dataset') router.register(r'genericRecords?', main_views.GenericRecordViewSet, 'genericRecord') router.register(r'observations?', main_views.ObservationViewSet, 'observation') router.register(r'speciesObservations?', main_views.SpeciesObservationViewSet, 'speciesObservation') url_patterns = [ url(r'dataset/(?P<pk>\d+)/data?', main_views.DatasetDataView.as_view(), name='dataset-data') ] urls = router.urls + url_patterns
Fix a couple of bugs. git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@45 369101cc-9a96-11dd-8e58-870c635edf7a
package com.thaiopensource.relaxng; import org.xml.sax.Locator; import com.thaiopensource.datatype.Datatype; class ValuePattern extends SimplePattern { String str; Datatype dt; ValuePattern(Datatype dt, String str, Locator locator) { super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator); this.dt = dt; this.str = str; } boolean matches(Atom a) { return a.matchesDatatypeValue(dt, str); } boolean samePattern(Pattern other) { if (getClass() != other.getClass()) return false; if (!(other instanceof ValuePattern)) return false; return (dt.equals(((ValuePattern)other).dt) && str.equals(((ValuePattern)other).str)); } void accept(PatternVisitor visitor) { visitor.visitValue(dt, str); } }
package com.thaiopensource.relaxng; import org.xml.sax.Locator; import com.thaiopensource.datatype.Datatype; class ValuePattern extends SimplePattern { String str; Datatype dt; ValuePattern(Datatype dt, String str, Locator locator) { super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator); this.str = str; } boolean matches(Atom a) { return a.matchesDatatypeValue(dt, str); } boolean samePattern(Pattern other) { if (getClass() != other.getClass()) return false; return (dt.equals(((ValuePattern)other).dt) && str.equals(((ValuePattern)other).str)); } void accept(PatternVisitor visitor) { visitor.visitValue(dt, str); } }
Remove JUnit 4 rule ExpectedException.none() (deprecated in version 4.13)
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import static org.junit.Assert.assertThrows; import org.junit.Test; public class TestRuleExpectedException { @Test public void throwsNullPointerException() { assertThrows(NullPointerException.class, () -> { throw new NullPointerException(); }); } }
/* * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.github.bonigarcia; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class TestRuleExpectedException { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void throwsNothing() { } @Test public void throwsNullPointerException() { thrown.expect(NullPointerException.class); throw new NullPointerException(); } }
Add Type field to RecordMatchContext
/* Copyright 2016 The MITRE Corporation. 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 models import "gopkg.in/mgo.v2/bson" const ( Deduplication = "deduplication" Query = "query" ) type RecordMatchContext struct { ID bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"` Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"` // human-friendly name assoc. w/ this record matching context Name string `bson:"name,omitempty" json:"name,omitempty"` // descriptive remarks assoc. w/ this interface to the record match system Description string `bson:"description,omitempty" json:"description,omitempty"` // distinguishes bewteen different context types (e.g., benchmark, challenge) Type string `bson:"type,omitempty" json:"type,omitempty"` }
/* Copyright 2016 The MITRE Corporation. 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 models import "gopkg.in/mgo.v2/bson" const ( Deduplication = "deduplication" Query = "query" ) type RecordMatchContext struct { ID bson.ObjectId `bson:"_id,omitempty" json:"id,omitempty"` Meta *Meta `bson:"meta,omitempty" json:"meta,omitempty"` // human-friendly name assoc. w/ this record matching context Name string `bson:"name,omitempty" json:"name,omitempty"` // descriptive remarks assoc. w/ this interface to the record match system Description string `bson:"description,omitempty" json:"description,omitempty"` }
Change let to var in sms route
"use strict"; const express = require('express'); const twilio = require('twilio'); const bodyParser = require('body-parser'); const app = express(); // Run server to listen on port 8000. const server = app.listen(8000, () => { console.log('listening on *:8000'); }); const io = require('socket.io')(server); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('static')); app.get('/', (req, res) => { res.sendFile(__dirname + '/views/index.html'); }); app.post('/sms', (req, res) => { var twiml = twilio.TwimlResponse(); var addOns = JSON.parse(req.body.AddOns); var sentimentStatus = addOns.results.ibm_watson_sentiment.status; console.log(req.body.From); if (sentimentStatus === 'successful') { var sentiment = addOns.results.ibm_watson_sentiment.result.docSentiment.type; io.emit('sms', { sentiment: sentiment, number: req.body.From }); console.log(sentiment); } else { console.log('Sentiment failed'); } twiml.message('Thanks for playing. Join us tonight at Bash for more fun & games'); res.send(twiml.toString()); });
"use strict"; const express = require('express'); const twilio = require('twilio'); const bodyParser = require('body-parser'); const app = express(); // Run server to listen on port 8000. const server = app.listen(8000, () => { console.log('listening on *:8000'); }); const io = require('socket.io')(server); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('static')); app.get('/', (req, res) => { res.sendFile(__dirname + '/views/index.html'); }); app.post('/sms', (req, res) => { let twiml = twilio.TwimlResponse(); let addOns = JSON.parse(req.body.AddOns); let sentimentStatus = addOns.results.ibm_watson_sentiment.status; console.log(req.body.From); if (sentimentStatus === 'successful') { let sentiment = addOns.results.ibm_watson_sentiment.result.docSentiment.type; io.emit('sms', { sentiment: sentiment, number: req.body.From }); console.log(sentiment); } else { console.log('Sentiment failed'); } twiml.message('Thanks for playing. Join us tonight at Bash for more fun & games'); res.send(twiml.toString()); });
Use relative URL for redirect in NewTerminalHandler
"""Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web import terminado from ..base.handlers import IPythonHandler class TerminalHandler(IPythonHandler): """Render the terminal interface.""" @web.authenticated def get(self, term_name): self.write(self.render_template('terminal.html', ws_path="terminals/websocket/%s" % term_name)) class NewTerminalHandler(IPythonHandler): """Redirect to a new terminal.""" @web.authenticated def get(self): name, _ = self.application.terminal_manager.new_named_terminal() self.redirect(name, permanent=False) class TermSocket(terminado.TermSocket, IPythonHandler): def get(self, *args, **kwargs): if not self.get_current_user(): raise web.HTTPError(403) return super(TermSocket, self).get(*args, **kwargs)
"""Tornado handlers for the terminal emulator.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from tornado import web import terminado from ..base.handlers import IPythonHandler class TerminalHandler(IPythonHandler): """Render the terminal interface.""" @web.authenticated def get(self, term_name): self.write(self.render_template('terminal.html', ws_path="terminals/websocket/%s" % term_name)) class NewTerminalHandler(IPythonHandler): """Redirect to a new terminal.""" @web.authenticated def get(self): name, _ = self.application.terminal_manager.new_named_terminal() self.redirect("/terminals/%s" % name, permanent=False) class TermSocket(terminado.TermSocket, IPythonHandler): def get(self, *args, **kwargs): if not self.get_current_user(): raise web.HTTPError(403) return super(TermSocket, self).get(*args, **kwargs)
Save and restore workbench state. git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@4697 28e8926c-6b08-0410-baaa-805c5e19b8d6
package org.objectweb.proactive.ic2d; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public void initialize(IWorkbenchConfigurer configurer) { // To restore window preferences //super.initialize(configurer); configurer.setSaveAndRestore(true); // Sets the look of the tabs like Eclipse 3.x PlatformUI.getPreferenceStore().setValue( IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false); } public String getInitialWindowPerspectiveId() { return "org.objectweb.proactive.ic2d.monitoring.perspectives.MonitoringPerspective";//MonitoringPerspective.ID /*DefaultPerspective.ID*/; } }
package org.objectweb.proactive.ic2d; import org.eclipse.ui.IWorkbenchPreferenceConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.application.IWorkbenchConfigurer; import org.eclipse.ui.application.IWorkbenchWindowConfigurer; import org.eclipse.ui.application.WorkbenchAdvisor; import org.eclipse.ui.application.WorkbenchWindowAdvisor; public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor { public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) { return new ApplicationWorkbenchWindowAdvisor(configurer); } public void initialize(IWorkbenchConfigurer configurer) { /*// To restore window preferences super.initialize(configurer); configurer.setSaveAndRestore(true); */ // Sets the look of the tabs like Eclipse 3.x PlatformUI.getPreferenceStore().setValue( IWorkbenchPreferenceConstants.SHOW_TRADITIONAL_STYLE_TABS, false); } public String getInitialWindowPerspectiveId() { return "org.objectweb.proactive.ic2d.monitoring.perspectives.MonitoringPerspective";//MonitoringPerspective.ID /*DefaultPerspective.ID*/; } }
Add additional assertion that the file we uploaded is correct We should pull back down the S3 bucket file and be sure it's the same, proving we used the boto3 API correctly. We should probably, at some point, also upload a _real_ zip file and not just a plaintext file.
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile')) # fetch the contents back out, be sure we truly uploaded the dummyfile retrieved_bucket = conn.Object( mock_bucket, conf.s3_package_name() ).get()['Body'] found_contents = str(retrieved_bucket.read()).rstrip() assert found_contents == 'dummy data'
import boto3 from os import path from lambda_uploader import uploader, config from moto import mock_s3 EX_CONFIG = path.normpath(path.join(path.dirname(__file__), '../test/configs')) @mock_s3 def test_s3_upload(): mock_bucket = 'mybucket' conn = boto3.resource('s3') conn.create_bucket(Bucket=mock_bucket) conf = config.Config(path.dirname(__file__), config_file=path.join(EX_CONFIG, 'lambda.json')) conf.set_s3(mock_bucket) upldr = uploader.PackageUploader(conf, None) upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
Change Django field filter kwarg from name to field_name for Django 2 support
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(field_name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(field_name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(field_name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
import django_filters from django_filters.filters import Lookup from apps.events.models import Event class ListFilter(django_filters.Filter): # https://github.com/carltongibson/django-filter/issues/137#issuecomment-37820702 def filter(self, qs, value): value_list = value.split(u',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class EventDateFilter(django_filters.FilterSet): event_start__gte = django_filters.DateTimeFilter(name='event_start', lookup_expr='gte') event_start__lte = django_filters.DateTimeFilter(name='event_start', lookup_expr='lte') event_end__gte = django_filters.DateTimeFilter(name='event_end', lookup_expr='gte') event_end__lte = django_filters.DateTimeFilter(name='event_end', lookup_expr='lte') attendance_event__isnull = django_filters.BooleanFilter(name='attendance_event', lookup_expr='isnull') event_type = ListFilter() class Meta: model = Event fields = ('event_start', 'event_end', 'event_type')
Add 3.7 to the trove classifiers
import setuptools from flatdict import __version__ setuptools.setup( name='flatdict', version=__version__, description=('Python module for interacting with nested dicts as a ' 'single level dict with delimited keys.'), long_description=open('README.rst').read(), author='Gavin M. Roy', author_email='gavinmroy@gmail.com', url='https://github.com/gmr/flatdict', package_data={'': ['LICENSE', 'README.rst']}, py_modules=['flatdict'], license='BSD', classifiers=[ 'Topic :: Software Development :: Libraries', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], zip_safe=True)
import setuptools from flatdict import __version__ setuptools.setup( name='flatdict', version=__version__, description=('Python module for interacting with nested dicts as a ' 'single level dict with delimited keys.'), long_description=open('README.rst').read(), author='Gavin M. Roy', author_email='gavinmroy@gmail.com', url='https://github.com/gmr/flatdict', package_data={'': ['LICENSE', 'README.rst']}, py_modules=['flatdict'], license='BSD', classifiers=[ 'Topic :: Software Development :: Libraries', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ], zip_safe=True)
[BLD] Resolve RuntimeError: Invalid DISPLAY variable - tst
# -*- coding: utf-8 -*- """ Created on Mon Dec 30 02:37:25 2013 @author: Jan """ import unittest import pandas as pd from opengrid.library import plotting class PlotStyleTest(unittest.TestCase): def test_default(self): plt = plotting.plot_style() class CarpetTest(unittest.TestCase): def test_default(self): import numpy as np index = pd.date_range('2015-1-1', '2015-12-31', freq='h') ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') assert plotting.carpet(ser) is not None def test_empty(self): assert plotting.carpet(pd.Series(index=list('abc'))) is None if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- """ Created on Mon Dec 30 02:37:25 2013 @author: Jan """ import unittest class PlotStyleTest(unittest.TestCase): def test_default(self): from opengrid.library.plotting import plot_style plt = plot_style() class CarpetTest(unittest.TestCase): def test_default(self): import numpy as np import pandas as pd from opengrid.library import plotting index = pd.date_range('2015-1-1', '2015-12-31', freq='h') ser = pd.Series(np.random.normal(size=len(index)), index=index, name='abc') plotting.carpet(ser) if __name__ == '__main__': unittest.main()
Add get_project_author ability in project track repository
<?php /** * @license MIT * Full license text in LICENSE file */ namespace Eadrax\Core\Usecase\Project\Track; interface Repository { public function is_user_tracking_project($fan, $project); public function remove_project($fan, $project); public function if_fan_of($fan, $idol); public function remove_idol($fan, $idol); /** * @return Array of Data\Project */ public function get_projects_by_author($author); /** * @param Array $projects Contains Data\project */ public function add_projects($fan, $projects); public function number_of_projects_by($author); public function number_of_projects_tracked_by($fan, $author); public function remove_projects_by_author($fan, $author); public function add_project($fan, $project); public function get_project_author($project); }
<?php /** * @license MIT * Full license text in LICENSE file */ namespace Eadrax\Core\Usecase\Project\Track; interface Repository { public function is_user_tracking_project($fan, $project); public function remove_project($fan, $project); public function if_fan_of($fan, $idol); public function remove_idol($fan, $idol); /** * @return Array of Data\Project */ public function get_projects_by_author($author); /** * @param Array $projects Contains Data\project */ public function add_projects($fan, $projects); public function number_of_projects_by($author); public function number_of_projects_tracked_by($fan, $author); public function remove_projects_by_author($fan, $author); public function add_project($fan, $project); }
Set production databse to test database
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
# -*- coding: utf-8 -*- import os HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key') SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SERVER_NAME = os.environ.get('HOST_NAME', 'localhost:5000') class ProdConfig(Config): ENV = 'prod' DEBUG = False class DevConfig(Config): ENV = 'dev' DEBUG = True LOAD_FAKE_DATA = True class TestConfig(Config): SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL', 'postgresql://localhost/') TESTING = True DEBUG = True # For: `nose.proxy.AssertionError: Popped wrong request context.` # http://stackoverflow.com/a/28139033/399726 # https://github.com/jarus/flask-testing/issues/21 PRESERVE_CONTEXT_ON_EXCEPTION = False
Change user select to use public class fields
import React from 'react'; class UserSelect extends React.Component { defaultValue = 'unassigned'; state = { selectedUserId: this.defaultValue } handleUserChange = (evt) => { let prevUserId; const selectedUserId = evt.target.value; if (this.state.selectedUserId !== this.defaultValue) { prevUserId = this.state.selectedUserId; } this.setState({ selectedUserId }); this.props.onUserChange(Number(selectedUserId), Number(prevUserId)); } render() { return ( <select onChange={this.handleUserChange} value={this.state.selectedUserId}> <option value={this.defaultValue}>Select User</option> {this.props.users.map((user) => <option key={user.id} value={user.id}>{user.name}</option>)} </select> ); } } UserSelect.propTypes = { users: React.PropTypes.array, onUserChange: React.PropTypes.func.isRequired }; export default UserSelect;
import React from 'react'; class UserSelect extends React.Component { constructor(props) { super(props); this.defaultValue = 'unassigned'; this.state = { selectedUserId: this.defaultValue }; this.handleUserChange = this.handleUserChange.bind(this); } handleUserChange(evt) { let prevUserId; const selectedUserId = evt.target.value; if (this.state.selectedUserId !== this.defaultValue) { prevUserId = this.state.selectedUserId; } this.setState({ selectedUserId }); this.props.onUserChange(Number(selectedUserId), Number(prevUserId)); } render() { return ( <select onChange={this.handleUserChange} value={this.state.selectedUserId}> <option value={this.defaultValue}>Select User</option> {this.props.users.map((user) => <option key={user.id} value={user.id}>{user.name}</option>)} </select> ); } } UserSelect.propTypes = { users: React.PropTypes.array, onUserChange: React.PropTypes.func.isRequired }; export default UserSelect;
Add creation of a file to write to
var fs = require('fs'); var clicolour = require('cli-color'); var mkdirp = require('mkdirp'); var error = require('../../error/bsod.js'); var xml = require('xml'); var exec = require('child_process').exec; exports.buildLang = function buildLang(x, y, z) { console.log(clicolour.cyanBright("webOS ") + clicolour.yellowBright("oobe ") + "Createing xml..."); // Create xml to write to exec("echo > ../../../config/config.xml", function (error, stdout, stderr) { console.log(stdout); }); if(z !== undefined){ var langObj = [ { config: [ {language: x} , {region: y} , {allowSend: true} ] } ]; } else { var langObj = [ { config: [ {language: x} , {region: y} , {allowSend: false} ] } ]; } fs.writeFile("../../../config/config.xml", xml(langObj, true), function(err) { if(err) { return console.log(err); } console.log(clicolour.cyanBright("webOS ") + clicolour.yellowBright("oobe ") + "XML created!"); }); console.log(xml(langObj, true)); };
var fs = require('fs'); var clicolour = require('cli-color'); var mkdirp = require('mkdirp'); var error = require('../../error/bsod.js'); var xml = require('xml'); exports.buildLang = function buildLang(x, y, z) { console.log(clicolour.cyanBright("webOS ") + clicolour.yellowBright("oobe ") + "Createing xml..."); if(z !== undefined){ var langObj = [ { config: [ {language: x} , {region: y} , {allowSend: true} ] } ]; } else { var langObj = [ { config: [ {language: x} , {region: y} , {allowSend: false} ] } ]; } fs.writeFile("../../../config/config.xml", xml(langObj, true), function(err) { if(err) { return console.log(err); } console.log(clicolour.cyanBright("webOS ") + clicolour.yellowBright("oobe ") + "XML created!"); }); console.log(xml(langObj, true)); };
Remove deprication tag as it leads to compile errors
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.dns; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * A managed DNS service. * * @author mpolden */ public interface NameService { /** * Create a new CNAME record * * @param alias The alias to create * @param canonicalName The canonical name which the alias should point to. This must be a FQDN. */ RecordId createCname(RecordName alias, RecordData canonicalName); /** Find record by type and name - will throw exception if more tha one record matches */ Optional<Record> findRecord(Record.Type type, RecordName name); /** Find record by type and name - may return multiple records */ default List<Record> findRecords(Record.Type type, RecordName name) { List<Record> result = new ArrayList<>(); findRecord(type, name).ifPresent(result::add); return result; } /** Find record by type and data */ List<Record> findRecord(Record.Type type, RecordData data); /** Update existing record */ void updateRecord(RecordId id, RecordData newData); /** Remove record by ID */ void removeRecord(RecordId id); }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.api.integration.dns; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * A managed DNS service. * * @author mpolden */ public interface NameService { /** * Create a new CNAME record * * @param alias The alias to create * @param canonicalName The canonical name which the alias should point to. This must be a FQDN. */ RecordId createCname(RecordName alias, RecordData canonicalName); /** Find record by type and name */ @Deprecated Optional<Record> findRecord(Record.Type type, RecordName name); /** Find record by type and name - may return multiple records */ default List<Record> findRecords(Record.Type type, RecordName name) { List<Record> result = new ArrayList<>(); findRecord(type, name).ifPresent(result::add); return result; } /** Find record by type and data */ List<Record> findRecord(Record.Type type, RecordData data); /** Update existing record */ void updateRecord(RecordId id, RecordData newData); /** Remove record by ID */ void removeRecord(RecordId id); }
Fix passing argument to callback to be status code not a boolean
module.exports = function( options, callback ) { var option, spider, startTime = new Date(), duration = require( "duration" ), spawn = require( "child_process" ).spawn, args = [ "test", __dirname + "/lib/tests.js" ]; for ( option in options ) { if ( options.hasOwnProperty( option ) ) { args.push( "--" + option + "=" + options[ option ] ); } } spider = spawn( __dirname + "/node_modules/casperjs/bin/casperjs", args, { stdio: "pipe" } ); spider.stdout.on( "data", function( data ) { process.stdout.write( data ); }); spider.stderr.on( "data", function( data ) { process.stderr.write( data ); }); spider.on( "close", function( code ) { process.stdout.write( "Spider completed in ~" + new duration( startTime ).milliseconds + "ms \n" ); if ( callback ) { callback( code ); } }); };
module.exports = function( options, callback ) { var option, spider, startTime = new Date(), duration = require( "duration" ), spawn = require( "child_process" ).spawn, args = [ "test", __dirname + "/lib/tests.js" ]; for ( option in options ) { if ( options.hasOwnProperty( option ) ) { args.push( "--" + option + "=" + options[ option ] ); } } spider = spawn( __dirname + "/node_modules/casperjs/bin/casperjs", args, { stdio: "pipe" } ); spider.stdout.on( "data", function( data ) { process.stdout.write( data ); }); spider.stderr.on( "data", function( data ) { process.stderr.write( data ); }); spider.on( "close", function( code ) { process.stdout.write( "Spider completed in ~" + new duration( startTime ).milliseconds + "ms \n" ); if ( callback ) { callback( !!code ); } }); };
Enforce 20s timeout for all unit tests.
/** * Allow the test suite to run with other libs or jQuery's. */ jQuery.noConflict(); /** * QUnit hooks */ (function() { // jQuery-specific QUnit.reset var reset = QUnit.reset, ajaxSettings = jQuery.ajaxSettings; QUnit.reset = function() { reset.apply(this, arguments); jQuery.event.global = {}; jQuery.ajaxSettings = jQuery.extend({}, ajaxSettings); }; })(); /** * QUnit configuration */ // Max time for stop() and asyncTest() until it aborts test // and start()'s the next test. QUnit.config.testTimeout = 20 * 1000; // 20 seconds /** * Load the TestSwarm listener if swarmURL is in the address. */ (function() { var url = window.location.search; url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + "swarmURL=".length ) ); if ( !url || url.indexOf("http") !== 0 ) { return; } // (Temporarily) Disable Ajax tests to reduce network strain // isLocal = QUnit.isLocal = true; document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); })();
jQuery.noConflict(); // Allow the test to run with other libs or jQuery's. // jQuery-specific QUnit.reset (function() { var reset = QUnit.reset, ajaxSettings = jQuery.ajaxSettings; QUnit.reset = function() { reset.apply(this, arguments); jQuery.event.global = {}; jQuery.ajaxSettings = jQuery.extend({}, ajaxSettings); }; })(); // load testswarm agent (function() { var url = window.location.search; url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) ); if ( !url || url.indexOf("http") !== 0 ) { return; } // (Temporarily) Disable Ajax tests to reduce network strain // isLocal = QUnit.isLocal = true; document.write("<scr" + "ipt src='http://swarm.jquery.org/js/inject.js?" + (new Date).getTime() + "'></scr" + "ipt>"); })();
Update: Add process title & improve callback invocation
#!/usr/bin/env node 'use strict'; var Liftoff = require('liftoff'); var Hacker = new Liftoff({ localDeps: ['hacker'], configName: 'hackerfile', processTitle: 'hacker', cwdOpt: 'cwd', requireOpt: 'require' }).on('require', function (name, module) { if (name === 'coffee-script') { module.register(); } }).on('requireFail', function (name, err) { console.log('Unable to load:', name, err); }); Hacker.launch(function() { if(this.args.verbose) { console.log('CLI OPTIONS:', this.args); console.log('CWD:', this.cwd); console.log('LOCAL MODULES REQUESTED:', this.localRequires); console.log('EXTENSIONS RECOGNIZED:', this.validExtensions); console.log('SEARCHING FOR:', this.configNameRegex); console.log('FOUND CONFIG AT:', this.configPath); console.log('CONFIG BASE DIR:', this.configBase); console.log('YOUR LOCAL DEPS ARE LOCATED:', this.depMap); console.log('LOCAL PACKAGE.JSON:', this.localPackage); console.log('CLI PACKAGE.JSON', require('../package')); } if(this.configPath) { process.chdir(this.configBase); require(this.configPath); console.log(this); } else { console.log('No Hackfile found.'); } });
#!/usr/bin/env node 'use strict'; var Liftoff = require('liftoff'); var Hacker = new Liftoff({ localDeps: ['hacker'], configName: 'hackerfile', cwdOpt: 'cwd', requireOpt: 'require' }).on('require', function (name, module) { if (name === 'coffee-script') { module.register(); } }).on('requireFail', function (name, err) { console.log('Unable to load:', name, err); }).on('run', function () { if(this.args.verbose) { console.log('CLI OPTIONS:', this.args); console.log('CWD:', this.cwd); console.log('LOCAL MODULES REQUESTED:', this.localRequires); console.log('EXTENSIONS RECOGNIZED:', this.validExtensions); console.log('SEARCHING FOR:', this.configNameRegex); console.log('FOUND CONFIG AT:', this.configPath); console.log('CONFIG BASE DIR:', this.configBase); console.log('YOUR LOCAL DEPS ARE LOCATED:', this.depMap); console.log('LOCAL PACKAGE.JSON:', this.localPackage); console.log('CLI PACKAGE.JSON', require('../package')); } if(this.configPath) { process.chdir(this.configBase); require(this.configPath); } else { console.log('No Hackfile found.'); } }); Hacker.launch();
Raise exception instead of returnning it
import requests import os import shutil client_id = '' # Imgur application Client ID, fill this in. directory_name = 'Imgur Albums\\' # Directory for the images to be stored def scrape(album_id): ''' (str) -> list of str Given an Imgur album ID, scrapes all the images within the album into a folder. Returns a list containing all the links that were scraped. ''' # Seperate directory for each album's images to be stored in directory = directory_name+album_id+'\\' if not os.path.exists(directory): os.makedirs(directory) # Creates the full directory for the album imageList = [] print('Loading Album: '+album_id) # Loading the album with Requests link = 'https://api.imgur.com/3/album/' + album_id header = {'Authorization': 'Client-Id '+client_id} album = requests.get(link, headers=header).json() if not album['success']: raise Exception(album['data']['error']) # Scrape image links from the album for image in album['data']['images']: imageList.append(image['link']) # Downloads each image and writes to disk for image in imageList: download = requests.get(image, stream=True) with open(directory+image[image.find('com/')+4:], 'wb') as outFile: shutil.copyfileobj(download.raw, outFile) return imageList
import requests import os import shutil client_id = '' # Imgur application Client ID, fill this in. directory_name = 'Imgur Albums\\' # Directory for the images to be stored def scrape(album_id): ''' (str) -> list of str Given an Imgur album ID, scrapes all the images within the album into a folder. Returns a list containing all the links that were scraped. ''' # Seperate directory for each album's images to be stored in directory = directory_name+album_id+'\\' if not os.path.exists(directory): os.makedirs(directory) # Creates the full directory for the album imageList = [] print('Loading Album: '+album_id) link = 'https://api.imgur.com/3/album/' + album_id header = {'Authorization': 'Client-Id '+client_id} album = requests.get(link, headers=header).json() if not album['success']: return album['data']['error'] # Scrape image links from the album for image in album['data']['images']: imageList.append(image['link']) # Downloads each image and writes to disk for image in imageList: download = requests.get(image, stream=True) with open(directory+image[image.find('com/')+4:], 'wb') as outFile: shutil.copyfileobj(download.raw, outFile) return imageList
fix(sanketa): Fix surrogate pair split :sushi:
/* @flow */ /** * sanketa * * @param {number|string} rawChars - raw chars * @param {Object} [opts] - options * @param {boolean} [opts.r] - reverse flag * @param {number|string} [opts.s] - sepalater * @return {string} */ export default function sanketa(rawChars: (number|string), opts: Object = {}): string { const digits = 3; const separater = opts.s ? opts.s : ','; let chars = rawChars; let snum = 0; chars = typeof chars === 'number' ? chars.toString() : chars; chars = opts.r ? reverse(chars) : chars; chars = Array.from(chars).map((c, key, map) => { if (key < map.length - 1) { if (key % digits === 2) { if (typeof separater === 'object' && separater instanceof Array) { snum = snum < separater.length ? snum + 1 : 1; return c + separater[snum - 1]; } return c + separater; } } return c; }).join(''); return opts.r ? reverse(chars) : chars; } /** * reverse function * * @param {string} chars - chars * @return {string} reversed chars */ function reverse(chars: string): string { return Array.from(chars).reverse().join(''); }
/* @flow */ /** * sanketa * * @param {number|string} rawChars - raw chars * @param {Object} [opts] - options * @param {boolean} [opts.r] - reverse flag * @param {number|string} [opts.s] - sepalater * @return {string} */ export default function sanketa(rawChars: (number|string), opts: Object = {}): string { const digits = 3; const separater = opts.s ? opts.s : ','; let chars = rawChars; let snum = 0; chars = typeof chars === 'number' ? chars.toString() : chars; chars = opts.r ? reverse(chars) : chars; chars = chars.split('').map((c, key, map) => { if (key < map.length - 1) { if (key % digits === 2) { if (typeof separater === 'object' && separater instanceof Array) { snum = snum < separater.length ? snum + 1 : 1; return c + separater[snum - 1]; } return c + separater; } } return c; }).join(''); return opts.r ? reverse(chars) : chars; } /** * reverse function * * @param {string} chars - chars * @return {string} reversed chars */ function reverse(chars: string): string { return chars.split('').reverse().join(''); }
Add simplejson as installation requirement
""" Setup and installation for the package. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="three", version="0.1", author="Zach Williams", author_email="hey@zachwill.com", description="An easy-to-use wrapper for the Open311 API", long_description=open('README.md').read(), packages=[ 'three' ], install_requires=[ 'mock', 'simplejson', 'requests', ], license='MIT', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
""" Setup and installation for the package. """ try: from setuptools import setup except ImportError: from distutils.core import setup setup( name="three", version="0.1", author="Zach Williams", author_email="hey@zachwill.com", description="An easy-to-use wrapper for the Open311 API", long_description=open('README.md').read(), packages=[ 'three' ], install_requires=[ 'mock', 'requests', ], license='MIT', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Return empty menu when no group context available.
<?php namespace Bkstg\CoreBundle\Menu\Builder; use Bkstg\CoreBundle\Context\GroupContextProvider; use Bkstg\CoreBundle\Event\ProductionMenuCollectionEvent; use Knp\Menu\FactoryInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class ProductionMenuBuilder { private $factory; private $dispatcher; private $group_context; /** * @param FactoryInterface $factory * * Add any other dependency you need */ public function __construct( FactoryInterface $factory, EventDispatcherInterface $dispatcher, GroupContextProvider $group_context ) { $this->factory = $factory; $this->dispatcher = $dispatcher; $this->group_context = $group_context; } public function createMenu(array $options) { $menu = $this->factory->createItem('root'); // No group context means return empty menu. if (null === $group = $this->group_context->getContext()) { return $menu; } // Dispatch event to populate the menu. $event = new ProductionMenuCollectionEvent($menu, $group); $this->dispatcher->dispatch(ProductionMenuCollectionEvent::NAME, $event); return $menu; } }
<?php namespace Bkstg\CoreBundle\Menu\Builder; use Bkstg\CoreBundle\Context\GroupContextProvider; use Bkstg\CoreBundle\Event\ProductionMenuCollectionEvent; use Knp\Menu\FactoryInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class ProductionMenuBuilder { private $factory; private $dispatcher; private $group_context; /** * @param FactoryInterface $factory * * Add any other dependency you need */ public function __construct( FactoryInterface $factory, EventDispatcherInterface $dispatcher, GroupContextProvider $group_context ) { $this->factory = $factory; $this->dispatcher = $dispatcher; $this->group_context = $group_context; } public function createMenu(array $options) { $menu = $this->factory->createItem('root'); $production = $this->group_context->getContext(); $event = new ProductionMenuCollectionEvent($menu, $this->group_context->getContext()); $this->dispatcher->dispatch(ProductionMenuCollectionEvent::NAME, $event); return $menu; } }
Fix import when using python3.3
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2013 Rémi Duraffort # This file is part of RandoAmisSecours. # # RandoAmisSecours is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # RandoAmisSecours is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with RandoAmisSecours. If not, see <http://www.gnu.org/licenses/> from django.contrib import admin from RandoAmisSecours.models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
# -*- coding: utf-8 -*- # vim: set ts=4 # Copyright 2013 Rémi Duraffort # This file is part of RandoAmisSecours. # # RandoAmisSecours is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # RandoAmisSecours is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with RandoAmisSecours. If not, see <http://www.gnu.org/licenses/> from django.contrib import admin from models import * admin.site.register(FriendRequest) admin.site.register(Outing) admin.site.register(Profile)
Add window.getselection() mock to commentTree test Jsdom does not support window.getSelection(), which is used by the editor. So in any test fully mounting lego-editor to the dom, this needs to be mocked.
import React from 'react'; import { mount, shallow } from 'enzyme'; import CommentTree from '../CommentTree'; import comments from './fixtures/comments'; import { generateTreeStructure } from '../../../utils'; import { MemoryRouter } from 'react-router-dom'; describe('<CommentTree />', () => { beforeAll(() => { window.getSelection = () => {}; }); const tree = generateTreeStructure(comments); it('should render the top level comments at root level ', () => { const wrapper = shallow(<CommentTree comments={tree} />); const commentElements = wrapper.find('.root'); expect(commentElements.length).toEqual(2); }); it('should nest comments', () => { const wrapper = mount( <MemoryRouter> <CommentTree comments={tree} /> </MemoryRouter> ); const rootElements = wrapper.find('.root'); const rootElement = rootElements.at(1); const childTree = rootElement.find('.child'); expect(childTree.text()).toMatch(comments[2].text); }); });
import React from 'react'; import { mount, shallow } from 'enzyme'; import CommentTree from '../CommentTree'; import comments from './fixtures/comments'; import { generateTreeStructure } from '../../../utils'; import { MemoryRouter } from 'react-router-dom'; describe('<CommentTree />', () => { const tree = generateTreeStructure(comments); it('should render the top level comments at root level ', () => { const wrapper = shallow(<CommentTree comments={tree} />); const commentElements = wrapper.find('.root'); expect(commentElements.length).toEqual(2); }); it('should nest comments', () => { const wrapper = mount( <MemoryRouter> <CommentTree comments={tree} /> </MemoryRouter> ); const rootElements = wrapper.find('.root'); const rootElement = rootElements.at(1); const childTree = rootElement.find('.child'); expect(childTree.text()).toMatch(comments[2].text); }); });
Use actual user avatar in passport mock
var User = require('./models').User; module.exports = { initialize: function(sessionUserObject) { return function(req, res, next) { var passport = this; User.findOne({username: 'Andrew'}, function(err, found){ found = found.toJSON(); found.avatar_url = found.avatar_url; found.github_id = 639382; found.displayName = 'Andrew'; passport._key = 'passport'; passport._userProperty = 'user'; passport.serializeUser = function(user, done) { return done(null, user); }; passport.deserializeUser = function(user, req, done) { return done(null, user); }; req._passport = { instance: passport }; req._passport.session = { user: found }; next(); }); }; } };
var User = require('./models').User; module.exports = { initialize: function(sessionUserObject) { return function(req, res, next) { var passport = this; User.findOne({username: 'Andrew'}, function(err, found){ found = found.toJSON(); found.avatar_url = 'https://avatars.githubusercontent.com/u/639382?v=3'; found.github_id = 639382; found.displayName = 'Andrew'; passport._key = 'passport'; passport._userProperty = 'user'; passport.serializeUser = function(user, done) { return done(null, user); }; passport.deserializeUser = function(user, req, done) { return done(null, user); }; req._passport = { instance: passport }; req._passport.session = { user: found }; next(); }); }; } };