text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix link to Git repository
Package.describe({ name: 'klaussner:svelte', version: '0.0.1', summary: 'Use the magical disappearing UI framework in Meteor', git: 'https://github.com/klaussner/meteor-svelte.git' }); Package.registerBuildPlugin({ name: 'svelte-compiler', use: ['caching-compiler@1.1.9', 'babel-compiler@6.13.0'], sources: [ 'plugin.js' ], npmDependencies: { htmlparser2: '3.9.2', 'source-map': '0.5.6', 'svelte-es5-meteor': '0.0.3' } }); Package.onUse(function (api) { api.use('isobuild:compiler-plugin@1.0.0'); api.imply('modules@0.7.7'); api.imply('ecmascript-runtime@0.3.15'); api.imply('babel-runtime@1.0.1'); api.imply('promise@0.8.8'); });
Package.describe({ name: 'klaussner:svelte', version: '0.0.1', summary: 'Use the magical disappearing UI framework in Meteor', git: 'https://github.com/klaussner/svelte' }); Package.registerBuildPlugin({ name: 'svelte-compiler', use: ['caching-compiler@1.1.9', 'babel-compiler@6.13.0'], sources: [ 'plugin.js' ], npmDependencies: { htmlparser2: '3.9.2', 'source-map': '0.5.6', 'svelte-es5-meteor': '0.0.3' } }); Package.onUse(function (api) { api.use('isobuild:compiler-plugin@1.0.0'); api.imply('modules@0.7.7'); api.imply('ecmascript-runtime@0.3.15'); api.imply('babel-runtime@1.0.1'); api.imply('promise@0.8.8'); });
Remove 'private' and 'public' keywords to make the script works with PHP4.
<? class EpiDBClient { var $server = 'https://egg.science.uva.nl:7443'; var $path_submit = '/submit/'; function __construct() { } function __epidb_encode($data) { $res = array(); foreach ($data as $key=>$val) { $res[] = $key . '=' . urlencode($val); } return implode('&', $res); } function __epidb_call($url, $data) { $param = $this->__epidb_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, count($data)); curl_setopt($ch, CURLOPT_POSTFIELDS, $param); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch); return $res; } function submit($data, $source, $format='json') { $param = array(); $param['data'] = $data; $param['source'] = $source; $param['format'] = $format; $url = $this->server . $this->path_submit; $res = $this->__epidb_call($url, $param); } };
<? class EpiDBClient { private $server = 'https://egg.science.uva.nl:7443'; private $path_submit = '/submit/'; public function __construct() { } private function __epidb_encode($data) { $res = array(); foreach ($data as $key=>$val) { $res[] = $key . '=' . urlencode($val); } return implode('&', $res); } private function __epidb_call($url, $data) { $param = $this->__epidb_encode($data); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, count($data)); curl_setopt($ch, CURLOPT_POSTFIELDS, $param); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($ch); curl_close($ch); return $res; } public function submit($data, $source, $format='json') { $param = array(); $param['data'] = $data; $param['source'] = $source; $param['format'] = $format; $url = $this->server . $this->path_submit; $res = $this->__epidb_call($url, $param); } };
Add route for commenting page test
from flask import Flask, jsonify, render_template, request, current_app, redirect, flash from functools import wraps import json app = Flask(__name__) def jsonp(f): '''Wrap JSONified output for JSONP''' @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + str(f(*args,**kwargs)) + ')' return current_app.response_class(content, mimetype='application/javascript') else: return f(*args, **kwargs) return decorated_function @app.route('/test', methods=['GET']) @jsonp def test(): flash('Previous', category='info') return jsonify({"foo":"bar"}) @app.route('/comment', methods=['GET']) @jsonp def test(): return render_template('dom_edit.html') @app.route('/_add_numbers') @jsonp def add_numbers(): ''' Because numbers must be added server side ''' a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run('0.0.0.0',port=4000)
from flask import Flask, jsonify, render_template, request, current_app, redirect, flash from functools import wraps import json app = Flask(__name__) def jsonp(f): '''Wrap JSONified output for JSONP''' @wraps(f) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + str(f(*args,**kwargs)) + ')' return current_app.response_class(content, mimetype='application/javascript') else: return f(*args, **kwargs) return decorated_function @app.route('/test', methods=['GET']) @jsonp def test(): flash('Previous', category='info') return jsonify({"foo":"bar"}) @app.route('/_add_numbers') @jsonp def add_numbers(): ''' Because numbers must be added server side ''' a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run('0.0.0.0',port=4000)
Add 'add' to projectDeploy provided interface
// Requires var _ = require('underscore'); var DeploymentSolution = require("./solution").DeploymentSolution; // List of all deployment solution var SUPPORTED = []; function setup(options, imports, register) { // Import var logger = imports.logger.namespace("deployment"); var events = imports.events; var workspace = imports.workspace; // Return a specific solution var getSolution = function(solutionId) { return _.find(SOLUTIONS, function(solution) { return solution.id == solutionId; }); }; // Add a solution var addSolution = function(solution) { if (!_.isArray(solution)) solution = [solution]; _.each(solution, function(_sol) { SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol)); }); }; // Add basic solutions addSolution([ require("./ghpages") ]) // Register register(null, { 'projectDeploy': { 'SUPPORTED': SUPPORTED, 'get': getSolution, 'add': addSolution } }); } // Exports module.exports = setup;
// Requires var _ = require('underscore'); var DeploymentSolution = require("./solution").DeploymentSolution; // List of all deployment solution var SUPPORTED = []; function setup(options, imports, register) { // Import var logger = imports.logger.namespace("deployment"); var events = imports.events; var workspace = imports.workspace; // Return a specific solution var getSolution = function(solutionId) { return _.find(SOLUTIONS, function(solution) { return solution.id == solutionId; }); }; // Add a solution var addSolution = function(solution) { if (!_.isArray(solution)) solution = [solution]; _.each(solution, function(_sol) { SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol)); }); } // Add basic solutions addSolution([ require("./ghpages") ]) // Register register(null, { 'projectDeploy': { 'SUPPORTED': SUPPORTED, 'get': getSolution } }); } // Exports module.exports = setup;
Fix webpack critical dependency warning (Closes #20)
(function () { var moment, replacements; if (typeof require === "function") { moment = require('moment'); } else { moment = this.moment; } replacements = { a: 'ddd', A: 'dddd', b: 'MMM', B: 'MMMM', d: 'DD', e: 'D', F: 'YYYY-MM-DD', H: 'HH', I: 'hh', j: 'DDDD', k: 'H', l: 'h', m: 'MM', M: 'mm', p: 'A', S: 'ss', u: 'E', w: 'd', W: 'WW', y: 'YY', Y: 'YYYY', z: 'ZZ', Z: 'z', '%': '%' }; moment.fn.strftime = function (format) { var momentFormat, value; // Convert sequences of letters to bracket-enclosed moment format literals momentFormat = format.replace(/[^%](\w+)/g, function (literal) { return '[' + literal + ']'; }); Object.keys(replacements).forEach(function (key) { value = replacements[key]; momentFormat = momentFormat.replace("%" + key, value); }); return this.format(momentFormat); }; if (typeof module !== "undefined" && module !== null) { module.exports = moment; } else { this.moment = moment; } }).call(this);
(function () { var moment, replacements; if (typeof require !== "undefined" && require !== null) { moment = require('moment'); } else { moment = this.moment; } replacements = { a: 'ddd', A: 'dddd', b: 'MMM', B: 'MMMM', d: 'DD', e: 'D', F: 'YYYY-MM-DD', H: 'HH', I: 'hh', j: 'DDDD', k: 'H', l: 'h', m: 'MM', M: 'mm', p: 'A', S: 'ss', u: 'E', w: 'd', W: 'WW', y: 'YY', Y: 'YYYY', z: 'ZZ', Z: 'z', '%': '%' }; moment.fn.strftime = function (format) { var momentFormat, value; // Convert sequences of letters to bracket-enclosed moment format literals momentFormat = format.replace(/[^%](\w+)/g, function (literal) { return '[' + literal + ']'; }); Object.keys(replacements).forEach(function (key) { value = replacements[key]; momentFormat = momentFormat.replace("%" + key, value); }); return this.format(momentFormat); }; if (typeof module !== "undefined" && module !== null) { module.exports = moment; } else { this.moment = moment; } }).call(this);
: Create documentation of DataSource Settings Task-Url:
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions print AdminControl.getCell() cell = "/Cell:" + AdminControl.getCell() + "/" cellid = AdminConfig.getid( cell ) dbs = AdminConfig.list( 'DataSource', str(cellid) ) for db in dbs.splitlines().split('('): t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Applications import ibmcnx.functions print AdminControl.getCell() cell = "/Cell:" + AdminControl.getCell() + "/" cellid = AdminConfig.getid( cell ) dbs = AdminConfig.list( 'DataSource', str(cellid) ) for db in dbs.splitlines(): t1 = ibmcnx.functions.getDSId( db ) AdminConfig.list( t1 )
Change function name enable to enable_mode
from netmiko.ssh_connection import SSHConnection from netmiko.netmiko_globals import MAX_BUFFER import time class HPProcurveSSH(SSHConnection): def session_preparation(self): ''' Prepare the session after the connection has been established ''' # HP uses - 'Press any key to continue' time.sleep(1) self.remote_conn.send("\n") time.sleep(1) # HP output contains VT100 escape codes self.ansi_escape_codes = True self.disable_paging(command="\nno page\n") self.find_prompt() def enable_mode(self, default_username='manager'): ''' Enter enable mode ''' DEBUG = False output = self.send_command('enable') if 'sername' in output: output += self.send_command(default_username) if 'assword' in output: output += self.send_command(self.secret) if DEBUG: print output self.find_prompt() self.clear_buffer()
from netmiko.ssh_connection import SSHConnection from netmiko.netmiko_globals import MAX_BUFFER import time class HPProcurveSSH(SSHConnection): def session_preparation(self): ''' Prepare the session after the connection has been established ''' # HP uses - 'Press any key to continue' time.sleep(1) self.remote_conn.send("\n") time.sleep(1) # HP output contains VT100 escape codes self.ansi_escape_codes = True self.disable_paging(command="\nno page\n") self.find_prompt() def enable(self, default_username='manager'): ''' Enter enable mode ''' DEBUG = False output = self.send_command('enable') if 'sername' in output: output += self.send_command(default_username) if 'assword' in output: output += self.send_command(self.secret) if DEBUG: print output self.find_prompt() self.clear_buffer()
Fix PointText size test on new Safari...
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ module('TextItem'); test('PointText', function() { var text = new PointText({ fontFamily: 'Helvetica, Arial', fontSize: 14, point: [100, 100], content: 'Hello World!' }); equals(text.fillColor, new Color(0, 0, 0), 'text.fillColor should be black by default'); equals(text.point, new Point(100, 100), 'text.point'); equals(text.bounds.point, new Point(100, 87.4), 'text.bounds.point'); equals(text.bounds.size, new Size(76, 16.8), 'text.bounds.size', { tolerance: 1.0 }); equals(function() { return text.hitTest(text.bounds.center) != null; }, true); });
/* * Paper.js - The Swiss Army Knife of Vector Graphics Scripting. * http://paperjs.org/ * * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey * http://scratchdisk.com/ & http://jonathanpuckey.com/ * * Distributed under the MIT license. See LICENSE file for details. * * All rights reserved. */ module('TextItem'); test('PointText', function() { var text = new PointText({ fontFamily: 'Arial', fontSize: 14, point: [100, 100], content: 'Hello World!' }); equals(text.fillColor, new Color(0, 0, 0), 'text.fillColor should be black by default'); equals(text.point, new Point(100, 100), 'text.point'); equals(text.bounds.point, new Point(100, 87.4), 'text.bounds.point'); equals(text.bounds.size, new Size(77, 16.8), 'text.bounds.size', { tolerance: 1.0 }); equals(function() { return text.hitTest(text.bounds.center) != null; }, true); });
Update links when dtenable set
/* eslint-disable no-console */ // <nowiki> (function() { var updateLinks = function() { $('a').each(function(i, e) { var shorthref = e.getAttribute('href') || ''; if (shorthref.match(/^(|#)$/)) { return; } try { var url = new URL(e.href); if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) { url.searchParams.set('dtenable', '1'); e.href = url.href; } } catch (err) { console.error(e, err); } }); }; if (mw.util.getParamValue('dtenable')) { setTimeout(updateLinks, 1000); } else { var url = new URL(window.location.href); url.searchParams.set('dtenable', '1'); mw.util.addPortletLink( 'p-tb', url.href, 'Enable DiscussionTools', 't-dtenable' ); } } )(); // </nowiki>
/* eslint-disable no-console */ // <nowiki> (function() { var updateLinks = function() { $('a').each(function(i, e) { var shorthref = e.getAttribute('href') || ''; if (shorthref.match(/^(|#)$/)) { return; } try { var url = new URL(e.href); if (url.host.match(/\.(wikipedia|wiktionary|wikiquote|wikisource|wikinews|wikivoyage|wikibooks|wikiversity|wikimedia|mediawiki|wikidata)\.org$/)) { url.searchParams.set('dtenable', '1'); e.href = url.href; } } catch (err) { console.error(e, err); } }); }; setTimeout(updateLinks, 1000); if (mw.util.getParamValue('dtenable') === null) { var url = new URL(window.location.href); url.searchParams.set('dtenable', '1'); mw.util.addPortletLink( 'p-tb', url.href, 'Enable DiscussionTools', 't-dtenable' ); } } )(); // </nowiki>
Change alert message on login
function AuthController($scope, $state, Auth, Flash) { $scope.login = function () { Auth.login($scope.user).then(function (res) { $state.go('home'); }, function (error) { $scope.errorAlert(error); }); }; $scope.register = function () { Auth.register($scope.user).then(function successCallback() { $state.go('home'); $scope.successAlert(); }, function errorCallback(err) { $scope.errorAlert(err); }); }; $scope.successAlert = function (res) { var message = '<strong>Welcome back ' + res.username + '</strong>'; var id = Flash.create('success', message, 5000); } $scope.errorAlert = function (error) { var message = '<strong>Oops!</strong> Something went wrong.'; var id = Flash.create('danger', message, 5000); } } AuthController.$inject = ['$scope', '$state', 'Auth', 'Flash']; angular .module('app') .controller('AuthController', AuthController);
function AuthController($scope, $state, Auth, Flash) { $scope.login = function () { Auth.login($scope.user).then(function () { $state.go('home'); $scope.successAlert(); }, function (error) { $scope.errorAlert(error); }); }; $scope.register = function () { Auth.register($scope.user).then(function successCallback() { $state.go('home'); $scope.successAlert(); }, function errorCallback(err) { $scope.errorAlert(err); }); }; $scope.successAlert = function () { var message = '<strong>Success!</strong>'; var id = Flash.create('success', message, 5000); } $scope.errorAlert = function (error) { var message = '<strong>Oops!</strong> Something went wrong.'; var id = Flash.create('danger', message, 5000); } } AuthController.$inject = ['$scope', '$state', 'Auth', 'Flash']; angular .module('app') .controller('AuthController', AuthController);
Fix twitch api call for boxart
package com.nincraft.ninbot.components.twitch; import com.github.twitch4j.helix.TwitchHelix; import lombok.extern.log4j.Log4j2; import lombok.val; import org.springframework.stereotype.Component; import java.util.Arrays; @Component @Log4j2 public class TwitchAPI { private TwitchHelix twitchHelix; public TwitchAPI(TwitchHelix twitchHelix) { this.twitchHelix = twitchHelix; } String getBoxArtUrl(String gameName) { try { val gameResults = twitchHelix.getGames(null, null, Arrays.asList(gameName)).execute(); if (gameResults.getGames().isEmpty()) { return null; } else { String boxartUrl = gameResults.getGames().get(0).getBoxArtUrl(); return boxartUrl.replace("-{width}x{height}", ""); } } catch (Exception e) { log.error("Failed to get boxart from Twitch API", e); return null; } } }
package com.nincraft.ninbot.components.twitch; import com.github.twitch4j.helix.TwitchHelix; import lombok.extern.log4j.Log4j2; import lombok.val; import org.springframework.stereotype.Component; import java.util.Arrays; @Component @Log4j2 public class TwitchAPI { private TwitchHelix twitchHelix; public TwitchAPI(TwitchHelix twitchHelix) { this.twitchHelix = twitchHelix; } String getBoxArtUrl(String gameName) { try { val gameResults = twitchHelix.getGames(null, Arrays.asList(gameName), null).execute(); if (gameResults.getGames().isEmpty()) { return null; } else { String boxartUrl = gameResults.getGames().get(0).getBoxArtUrl(); return boxartUrl.replace("-{width}x{height}", ""); } } catch (Exception e) { log.error("Failed to get boxart from Twitch API", e); return null; } } }
Enforce camelcase variables with eslint This has been our practice, now it is THE RULE.
module.exports = { root: true, parserOptions: { ecmaVersion: 8, sourceType: 'module' }, extends: 'eslint:recommended', env: { browser: true }, rules: { /* Possible Errors http://eslint.org/docs/rules/#possible-errors */ "comma-dangle": [2, "only-multiline"], /* Stylistic Issues http://eslint.org/docs/rules/#stylistic-issues */ indent: [2, 2], /* two-space indentation */ semi: 2, /* require semi-colons */ camelcase: 2, /* require camelcase variables */ 'no-shadow': [2, { builtinGlobals: true, allow: ['event', 'i', 'name', 'parent', 'resolve', 'self', 'select', 'scrollTo', 'status'] },], /* Prevent shadowing globals like Object*/ } };
module.exports = { root: true, parserOptions: { ecmaVersion: 8, sourceType: 'module' }, extends: 'eslint:recommended', env: { browser: true }, rules: { /* Possible Errors http://eslint.org/docs/rules/#possible-errors */ "comma-dangle": [2, "only-multiline"], /* Stylistic Issues http://eslint.org/docs/rules/#stylistic-issues */ indent: [2, 2], /* two-space indentation */ semi: 2, /* require semi-colons */ 'no-shadow': [2, { builtinGlobals: true, allow: ['event', 'i', 'name', 'parent', 'resolve', 'self', 'select', 'scrollTo', 'status'] },], /* Prevent shadowing globals like Object*/ } };
Update `curio` pin to 0.6.0. Signed-off-by: Laura <07c342be6e560e7f43842e2e21b774e61d85f047@veriny.tf>
from setuptools import setup setup( name='discord-curious', version='0.2.0.post1', packages=['curious', 'curious.core', 'curious.http', 'curious.commands', 'curious.dataclasses', 'curious.voice', 'curious.ext.loapi', 'curious.ext.paginator'], url='https://github.com/SunDwarf/curious', license='MIT', author='Laura Dickinson', author_email='l@veriny.tf', description='A curio library for the Discord API', install_requires=[ "cuiows>=0.1.10", "curio==0.6.0", "h11==0.7.0", "multidict==2.1.4", "pylru==1.0.9", "yarl==0.8.1", ], extras_require={ "voice": ["opuslib==1.1.0", "PyNaCL==1.0.1",] } )
from setuptools import setup setup( name='discord-curious', version='0.2.0.post1', packages=['curious', 'curious.core', 'curious.http', 'curious.commands', 'curious.dataclasses', 'curious.voice', 'curious.ext.loapi', 'curious.ext.paginator'], url='https://github.com/SunDwarf/curious', license='MIT', author='Laura Dickinson', author_email='l@veriny.tf', description='A curio library for the Discord API', install_requires=[ "cuiows>=0.1.10", "curio==0.5.0", "h11==0.7.0", "multidict==2.1.4", "pylru==1.0.9", "yarl==0.8.1", ], extras_require={ "voice": ["opuslib==1.1.0", "PyNaCL==1.0.1",] } )
Add test cases for matching strategies
<?php declare(strict_types=1); namespace Scheb\Tombstone\Analyzer\Matching; use Scheb\Tombstone\Analyzer\Model\TombstoneIndex; use Scheb\Tombstone\Core\Model\Tombstone; use Scheb\Tombstone\Core\Model\Vampire; class PositionStrategy implements MatchingStrategyInterface { public function matchVampireToTombstone(Vampire $vampire, TombstoneIndex $tombstoneIndex): ?Tombstone { if ($matchingTombstone = $tombstoneIndex->getInFileAndLine($vampire->getFile()->getReferencePath(), $vampire->getLine())) { if ($vampire->inscriptionEquals($matchingTombstone)) { return $matchingTombstone; } } return null; } }
<?php declare(strict_types=1); namespace Scheb\Tombstone\Analyzer\Matching; use Scheb\Tombstone\Analyzer\Model\TombstoneIndex; use Scheb\Tombstone\Core\Model\Tombstone; use Scheb\Tombstone\Core\Model\Vampire; class PositionStrategy implements MatchingStrategyInterface { public function matchVampireToTombstone(Vampire $vampire, TombstoneIndex $tombstoneIndex): ?Tombstone { if ($matchingTombstone = $tombstoneIndex->getInFileAndLine($vampire->getFile(), $vampire->getLine())) { if ($vampire->inscriptionEquals($matchingTombstone)) { return $matchingTombstone; } } return null; } }
Introduce a new way to `require` plugins when using RequireJS (dev mode). This is to fix an issue with timing that existed previously.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. window.process = {}; window.process._RJS_baseUrl = function(n) { return ".."; }; window.process._RJS_rootDir = function(n) { if (n == 3) return "."; if (n == 2) return "readium-js"; if (n == 1) return "readium-js/readium-shared-js"; if (n == 0) return "readium-js/readium-shared-js/readium-cfi-js"; }; // Used in readium-build-tools/pluginsConfigMaker // and readium_shared_js/globalsSetup. // Flag as not optimized by r.js window._RJS_isBrowser = true; require.config({ paths: { "version": process._RJS_rootDir(3) + '/dev/version' } });
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // 3. Neither the name of the organization nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. window.process = {}; window.process._RJS_baseUrl = function(n) { return ".."; }; window.process._RJS_rootDir = function(n) { if (n == 3) return "."; if (n == 2) return "readium-js"; if (n == 1) return "readium-js/readium-shared-js"; if (n == 0) return "readium-js/readium-shared-js/readium-cfi-js"; }; window.process._RJS_isBrowser = true; require.config({ paths: { "version": process._RJS_rootDir(3) + '/dev/version' } });
Support floating point ns/op lines
package main import "fmt" import "os" import "bufio" import "strings" import "time" import "strconv" import "flag" func main() { dur := flag.Duration("d", time.Second, "duration unit") flag.Parse() scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // fmt.Println(line) // Println will add back the final '\n' if strings.HasPrefix(line, "Benchmark") { fields := strings.Fields(line) if len(fields) < 4 || fields[3] != "ns/op" { fmt.Println(line) continue } nsPerOp, err := strconv.ParseFloat(fields[2], 64) if err != nil { fmt.Println(line) continue } opsPerDur := int64(float64(dur.Nanoseconds()) / nsPerOp) fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur) continue } fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } }
package main import "fmt" import "os" import "bufio" import "strings" import "time" import "strconv" import "flag" func main() { dur := flag.Duration("d", time.Second, "duration unit") flag.Parse() scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() // fmt.Println(line) // Println will add back the final '\n' if strings.HasPrefix(line, "Benchmark") { fields := strings.Fields(line) if len(fields) < 4 || fields[3] != "ns/op" { fmt.Println(line) continue } nsPerOp, err := strconv.ParseInt(fields[2], 10, 64) if err != nil { fmt.Println(line) continue } opsPerDur := dur.Nanoseconds() / nsPerOp fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur) continue } fmt.Println(line) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } }
Fix bug with colored tiles always showing for guess board
import React, { PropTypes } from 'react'; import colorByCharacter from '~/constants/colorByCharacter'; function WordCard(props) { const {word} = props; function toggleIsRevealed(word) { props.toggleIsRevealed && props.toggleIsRevealed(word); } return ( <div className={`grid__item col-1-5 mv-`} > <div className="ph-"> <div onClick={() => word.isRevealed ? null : toggleIsRevealed(word)} className={`bo--1 bor--5 flex flex--jc--c align-items--center height--80 ${word.isRevealed ? 'opacity--4-10' : 'cursor--pointer'} ${word.isRevealed && colorByCharacter[word.character] ? colorByCharacter[word.character] : 'white'}`} > <div className="grid grid--full col-1-1 pv"> <div className="grid__item col-1-1 text--center font--lg"> {word.text} </div> </div> </div> </div> </div> ); } WordCard.propTypes = { word: PropTypes.object.isRequired, toggleIsRevealed: PropTypes.func.isRequired, }; export default WordCard;
import React, { PropTypes } from 'react'; import colorByCharacter from '~/constants/colorByCharacter'; function WordCard(props) { const {word} = props; function toggleIsRevealed(word) { props.toggleIsRevealed && props.toggleIsRevealed(word); } return ( <div className={`grid__item col-1-5 mv-`} > <div className="ph-"> <div onClick={() => word.isRevealed ? null : toggleIsRevealed(word)} className={`bo--1 bor--5 flex flex--jc--c align-items--center height--80 ${word.isRevealed ? 'opacity--4-10' : 'cursor--pointer'} ${colorByCharacter[word.character] ? colorByCharacter[word.character] : 'white'}`} > <div className="grid grid--full col-1-1 pv"> <div className="grid__item col-1-1 text--center font--lg"> {word.text} </div> </div> </div> </div> </div> ); } WordCard.propTypes = { word: PropTypes.object.isRequired, toggleIsRevealed: PropTypes.func.isRequired, }; export default WordCard;
Remove reference to old broccoli-yuidoc-fork
'use strict'; var YuidocCompiler = require('broccoli-yuidoc'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-yuidoc', postprocessTree: function(type, workingTree) { if (this.app.env !== 'development' || type !== 'all'){ return workingTree; } var codeFolder = this.app.constructor.name === 'EmberAddon' ? 'addon' : 'app'; var yuidocTree = new YuidocCompiler(codeFolder, { srcDir: '/', destDir: '/docs', yuidoc: {} }); return mergeTrees([workingTree, yuidocTree]); }, included: function(app){ this.app = app; }, includedCommands: function() { return { 'yuidoc': require('./lib/commands/yuidoc') } } };
'use strict'; var YuidocCompiler = require('broccoli-yuidoc-fork'); var mergeTrees = require('broccoli-merge-trees'); module.exports = { name: 'ember-cli-yuidoc', postprocessTree: function(type, workingTree) { if (this.app.env !== 'development' || type !== 'all'){ return workingTree; } var codeFolder = this.app.constructor.name === 'EmberAddon' ? 'addon' : 'app'; var yuidocTree = new YuidocCompiler(codeFolder, { srcDir: '/', destDir: '/docs', yuidoc: {} }); return mergeTrees([workingTree, yuidocTree]); }, included: function(app){ this.app = app; }, includedCommands: function() { return { 'yuidoc': require('./lib/commands/yuidoc') } } };
Change reporting url in console message
function run($rootScope, SyncService, $transitions, $location, $trace, $uiRouter) { 'ngInject'; SyncService.init(); if ($featureFlags.debugRouter) { $trace.enable('TRANSITION'); $uiRouter.plugin(require('@uirouter/visualizer').Visualizer); } // Variables for templates that webpack does not automatically correct. $rootScope.$DIM_VERSION = $DIM_VERSION; $rootScope.$DIM_FLAVOR = $DIM_FLAVOR; $rootScope.$DIM_CHANGELOG = $DIM_CHANGELOG; $rootScope.$DIM_BUILD_DATE = new Date($DIM_BUILD_DATE).toLocaleString(); console.log(`DIM v${$DIM_VERSION} (${$DIM_FLAVOR}) - Please report any errors to https://www.github.com/DestinyItemManager/DIM/issues`); } export default run;
function run($rootScope, SyncService, $transitions, $location, $trace, $uiRouter) { 'ngInject'; SyncService.init(); if ($featureFlags.debugRouter) { $trace.enable('TRANSITION'); $uiRouter.plugin(require('@uirouter/visualizer').Visualizer); } // Variables for templates that webpack does not automatically correct. $rootScope.$DIM_VERSION = $DIM_VERSION; $rootScope.$DIM_FLAVOR = $DIM_FLAVOR; $rootScope.$DIM_CHANGELOG = $DIM_CHANGELOG; $rootScope.$DIM_BUILD_DATE = new Date($DIM_BUILD_DATE).toLocaleString(); console.log(`DIM v${$DIM_VERSION} (${$DIM_FLAVOR}) - Please report any errors to https://www.reddit.com/r/destinyitemmanager`); } export default run;
Remove -beta.n suffix from less before republishing.
Package.describe({ name: 'less', version: '2.7.9', summary: 'Leaner CSS language', documentation: 'README.md' }); Package.registerBuildPlugin({ name: "compileLessBatch", use: ['caching-compiler', 'ecmascript', 'underscore'], sources: [ 'plugin/compile-less.js' ], npmDependencies: { // Fork of 2.5.0, deleted large unused files in dist directory. "less": "https://github.com/meteor/less.js/tarball/8130849eb3d7f0ecf0ca8d0af7c4207b0442e3f6" } }); Package.onUse(function (api) { api.use('isobuild:compiler-plugin@1.0.0'); }); Package.onTest(function(api) { api.use('less'); api.use(['tinytest', 'test-helpers']); api.addFiles(['tests/top.import.less', 'tests/top3.import.less', 'tests/dir/in-dir.import.less', 'tests/dir/in-dir2.import.less', 'tests/dir/root.less', 'tests/dir/subdir/in-subdir.import.less']); api.addFiles('tests/imports/not-included.less', 'client', { lazy: true }); api.addFiles('tests/top2.less', 'client', {isImport: true}); api.addFiles('less_tests.js', 'client'); });
Package.describe({ name: 'less', version: '2.7.9-beta.1', summary: 'Leaner CSS language', documentation: 'README.md' }); Package.registerBuildPlugin({ name: "compileLessBatch", use: ['caching-compiler', 'ecmascript', 'underscore'], sources: [ 'plugin/compile-less.js' ], npmDependencies: { // Fork of 2.5.0, deleted large unused files in dist directory. "less": "https://github.com/meteor/less.js/tarball/8130849eb3d7f0ecf0ca8d0af7c4207b0442e3f6" } }); Package.onUse(function (api) { api.use('isobuild:compiler-plugin@1.0.0'); }); Package.onTest(function(api) { api.use('less'); api.use(['tinytest', 'test-helpers']); api.addFiles(['tests/top.import.less', 'tests/top3.import.less', 'tests/dir/in-dir.import.less', 'tests/dir/in-dir2.import.less', 'tests/dir/root.less', 'tests/dir/subdir/in-subdir.import.less']); api.addFiles('tests/imports/not-included.less', 'client', { lazy: true }); api.addFiles('tests/top2.less', 'client', {isImport: true}); api.addFiles('less_tests.js', 'client'); });
Add new class to restart
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); } render() { return ( <div className="navbar"> <a className="restart" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); } } const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(Restart);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store.js'; import { restart } from '../actions/name-actions'; import { selectGender } from '../actions/gender-actions'; import MdBack from 'react-icons/lib/md/keyboard-arrow-left'; class Restart extends Component { constructor(props) { super(props); } restart() { store.dispatch(restart()); store.dispatch(selectGender(null)); localStorage.clear(); } render() { return ( <div className="navbar"> <a className="is-pulled-left" onClick={this.restart}><MdBack></MdBack> Byrja av nýggjum</a> </div> ); } } const mapStateToProps = function (store) { return { names: store.names, gender: store.gender }; } export default connect(mapStateToProps)(Restart);
Use the more generic IMethodInvoker interface instead of ISimpleMethodInvoker
package com.example.samplemodule; import java.util.List; import android.support.annotation.NonNull; import com.artech.actions.ActionResult; import com.artech.application.MyApplication; import com.artech.externalapi.ExternalApi; import com.artech.externalapi.ExternalApiResult; public class BasicExternalObject extends ExternalApi { private static final String METHOD_HELLO = "Hello"; private static final String METHOD_MESSAGE = "Message"; public BasicExternalObject() { addMethodHandler(METHOD_HELLO, 0, mMethodHello); addMethodHandler(METHOD_MESSAGE, 1, mMethodMessage); } private final IMethodInvoker mMethodHello = new IMethodInvoker() { @Override public @NonNull ExternalApiResult invoke(List<Object> parameters) { MyApplication.getInstance().showMessage(getContext().getString(com.example.genexusmodule.R.string.hello_message)); return new ExternalApiResult(ActionResult.SUCCESS_CONTINUE); } }; private final IMethodInvoker mMethodMessage = new IMethodInvoker() { @Override public @NonNull ExternalApiResult invoke(List<Object> parameters) { final String text = (String) parameters.get(0); MyApplication.getInstance().showMessage(text); return new ExternalApiResult(ActionResult.SUCCESS_CONTINUE); } }; }
package com.example.samplemodule; import java.util.List; import com.artech.application.MyApplication; import com.artech.externalapi.ExternalApi; public class BasicExternalObject extends ExternalApi { private static final String METHOD_HELLO = "Hello"; private static final String METHOD_MESSAGE = "Message"; public BasicExternalObject() { addSimpleMethodHandler(METHOD_HELLO, 0, mMethodHello); addSimpleMethodHandler(METHOD_MESSAGE, 1, mMethodMessage); } private final ISimpleMethodInvoker mMethodHello = new ISimpleMethodInvoker() { @Override public Object invoke(List<Object> parameters) { MyApplication.getInstance().showMessage(getContext().getString(com.example.genexusmodule.R.string.hello_message)); return null; } }; private final ISimpleMethodInvoker mMethodMessage = new ISimpleMethodInvoker() { @Override public Object invoke(List<Object> parameters) { final String text = (String) parameters.get(0); MyApplication.getInstance().showMessage(text); return null; } }; }
Use a link tag instead of style, to get sourcemaps to work
var ConcatSource = require("webpack/node_modules/webpack-core/lib/ConcatSource"); function ChunkWithStyleTagTemplate(chunkTemplate) { this.chunkTemplate = chunkTemplate; } module.exports = ChunkWithStyleTagTemplate; ChunkWithStyleTagTemplate.prototype.updateHash = function(hash) { hash.update("ChunkWithStyleTagTemplate"); hash.update("2"); }; ChunkWithStyleTagTemplate.prototype.render = function(chunkA, chunkB) { var chunk = typeof chunkA === "string" ? chunkB : chunkA; var source = new ConcatSource(); if (chunk._chunkStyles) { var fnText = insertCss.toString(); source.add("(("+fnText+")("+JSON.stringify(chunk._chunkStyles)+"));\n"); source.add("function ___go_js_go_go_go___() {\n"); } source.add(this.chunkTemplate.render.apply(this.chunkTemplate, arguments)); if (chunk._chunkStyles) { source.add("\n}"); } source.rendered = true; return source; }; function insertCss(css) { var link = document.createElement("link"); link.setAttribute("rel", "stylesheet"); link.setAttribute("type", "text/css"); link.setAttribute("href", "data:text/css;base64,"+btoa(css)); link.addEventListener("load", ___go_js_go_go_go___); document.getElementsByTagName("head")[0].appendChild(link); }
var ConcatSource = require("webpack/node_modules/webpack-core/lib/ConcatSource"); function ChunkWithStyleTagTemplate(chunkTemplate) { this.chunkTemplate = chunkTemplate; } module.exports = ChunkWithStyleTagTemplate; ChunkWithStyleTagTemplate.prototype.updateHash = function(hash) { hash.update("ChunkWithStyleTagTemplate"); hash.update("2"); }; ChunkWithStyleTagTemplate.prototype.render = function(chunkA, chunkB) { var chunk = typeof chunkA === "string" ? chunkB : chunkA; var source = new ConcatSource(); if (chunk._chunkStyles) { var fnText = insertCss.toString(); source.add("(("+fnText+")("+JSON.stringify(chunk._chunkStyles)+"));"); } source.add(this.chunkTemplate.render.apply(this.chunkTemplate, arguments)); source.rendered = true; return source; }; function insertCss(css) { var style = document.createElement("style"); style.setAttribute("type", "text/css"); style.appendChild(document.createTextNode(css)); document.getElementsByTagName("head")[0].appendChild(style); }
Fix arguments being passed to markdown-to-jsx The argument syntax changed a bit in 4.x. GFM is always enabled, so no need to pass that explicitly.
// (C) Copyright 2016 Hewlett Packard Enterprise Development LP import { PropTypes } from 'react'; import markdownToJSX from 'markdown-to-jsx'; import deepAssign from 'deep-assign'; import Paragraph from './Paragraph'; import Table from './Table'; import Heading from './Heading'; import Anchor from './Anchor'; import Image from './Image'; let Markdown = (props) => { const { content, components } = props; const heading = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] .reduce((heading, current) => { heading[current] = { component: Heading, props: { tag: current } }; return heading; }, {}); const options = deepAssign({ a: { component: Anchor }, img: { component: Image, props: { caption: true } }, p: { component: Paragraph }, table: { component: Table } }, heading, components); return markdownToJSX(content, {overrides: options}); }; Markdown.propTypes = { content: PropTypes.string, components: PropTypes.shape({ props: PropTypes.object }) }; Markdown.defaultProps = { components: {}, content: '' }; export default Markdown;
// (C) Copyright 2016 Hewlett Packard Enterprise Development LP import { PropTypes } from 'react'; import markdownToJSX from 'markdown-to-jsx'; import deepAssign from 'deep-assign'; import Paragraph from './Paragraph'; import Table from './Table'; import Heading from './Heading'; import Anchor from './Anchor'; import Image from './Image'; let Markdown = (props) => { const { content, components } = props; const heading = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] .reduce((heading, current) => { heading[current] = { component: Heading, props: { tag: current } }; return heading; }, {}); const options = deepAssign({ a: { component: Anchor }, img: { component: Image, props: { caption: true } }, p: { component: Paragraph }, table: { component: Table } }, heading, components); return ( markdownToJSX(content, { gfm: true }, options) ); }; Markdown.propTypes = { content: PropTypes.string, components: PropTypes.shape({ props: PropTypes.object }) }; Markdown.defaultProps = { components: {}, content: '' }; export default Markdown;
Fix the router's interfaces listing view to show only the interfaces on the user's networks filtering out interfaces on the mgt and public networks. DHC-1512 Change-Id: I9b68b75d5e8325c4c70090fa500a417e23b1836f Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) # Note(rods): Right now we are listing, for both normal and # admin users, all the ports on the user's networks # the router is associated with. We may want in the # future show the ports on the mgt and the external # networks for the admin users. ports = [api.quantum.Port(p) for p in router.ports if p['device_owner'] == 'network:router_interface'] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
from django.utils.translation import ugettext_lazy as _ # noqa from horizon import exceptions from openstack_dashboard import api def get_interfaces_data(self): try: router_id = self.kwargs['router_id'] router = api.quantum.router_get(self.request, router_id) ports = [api.quantum.Port(p) for p in router.ports] except Exception: ports = [] msg = _( 'Port list can not be retrieved for router ID %s' % self.kwargs.get('router_id') ) exceptions.handle(self.request, msg) for p in ports: p.set_id_as_name_if_empty() return ports
Add lang 'zh' to family 'wikivoyage' , update from compat Change-Id: Ic6c64f356511d1f92eefe9e813c9564786b2b5a5
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'zh', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
# -*- coding: utf-8 -*- __version__ = '$Id$' # The new wikivoyage family that is hosted at wikimedia from pywikibot import family class Family(family.WikimediaFamily): def __init__(self): super(Family, self).__init__() self.name = 'wikivoyage' self.languages_by_size = [ 'en', 'de', 'pt', 'fr', 'it', 'nl', 'pl', 'ru', 'es', 'vi', 'sv', 'he', 'ro', 'uk', 'el', ] self.langs = dict([(lang, '%s.wikivoyage.org' % lang) for lang in self.languages_by_size]) # Global bot allowed languages on http://meta.wikimedia.org/wiki/Bot_policy/Implementation#Current_implementation self.cross_allowed = ['es', 'ru', ] def shared_data_repository(self, code, transcluded=False): return ('wikidata', 'wikidata')
Resolve broken test in appveyor
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static" / "app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name(loaded_module_from_file_location,): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
from pathlib import Path from types import ModuleType import pytest from sanic.exceptions import LoadFileException from sanic.utils import load_module_from_file_location @pytest.fixture def loaded_module_from_file_location(): return load_module_from_file_location( str(Path(__file__).parent / "static/app_test_config.py") ) @pytest.mark.dependency(name="test_load_module_from_file_location") def test_load_module_from_file_location(loaded_module_from_file_location): assert isinstance(loaded_module_from_file_location, ModuleType) @pytest.mark.dependency(depends=["test_load_module_from_file_location"]) def test_loaded_module_from_file_location_name( loaded_module_from_file_location, ): assert loaded_module_from_file_location.__name__ == "app_test_config" def test_load_module_from_file_location_with_non_existing_env_variable(): with pytest.raises( LoadFileException, match="The following environment variables are not set: MuuMilk", ): load_module_from_file_location("${MuuMilk}")
Handle errors in case of a country mismatch.
from urlparse import urljoin from django.conf import settings from django_countries import countries import requests COUNTRY_CODES = {key: value for (value, key) in list(countries)} def reverse_geocode(lat, lng): """Query Mapbox API to get data for lat, lng""" query = '{0},{1}.json'.format(lng, lat) url = urljoin(settings.MAPBOX_GEOCODE_URL, query) params = {'access_token': settings.MAPBOX_TOKEN} response = requests.get(url, params=params) results = {} if response.status_code != 200: return results data = response.json() for feature in data['features']: text = feature['text'] if feature['id'].startswith('country.'): try: results['country'] = COUNTRY_CODES[text] except KeyError: results['country'] = text if feature['id'].startswith('region.'): results['region'] = text if feature['id'].startswith('place.'): results['city'] = text if feature['id'].startswith('address.'): results['address'] = text return results
from urlparse import urljoin from django.conf import settings from django_countries import countries import requests COUNTRY_CODES = {key: value for (value, key) in list(countries)} def reverse_geocode(lat, lng): """Query Mapbox API to get data for lat, lng""" query = '{0},{1}.json'.format(lng, lat) url = urljoin(settings.MAPBOX_GEOCODE_URL, query) params = {'access_token': settings.MAPBOX_TOKEN} response = requests.get(url, params=params) results = {} if response.status_code != 200: return results data = response.json() for feature in data['features']: text = feature['text'] if feature['id'].startswith('country.'): results['country'] = COUNTRY_CODES[text] if feature['id'].startswith('region.'): results['region'] = text if feature['id'].startswith('place.'): results['city'] = text if feature['id'].startswith('address.'): results['address'] = text return results
Set logging to a more detailed level
package net.rodrigoamaral.logging; import java.util.logging.*; public class SPSPLogger { public static final Logger logger = Logger.getLogger(SPSPLogger.class.getName()); static { config(); } private static void config() { LogManager manager = LogManager.getLogManager(); manager.reset(); logger.setLevel(Level.ALL); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(Level.FINE); ch.setFormatter(new SPSPLogFormatter()); logger.addHandler(ch); // TODO: Implement a log file handler } public static void trace(String msg) { logger.finer(msg); } public static void debug(String msg) { logger.fine(msg); } public static void info(String msg) { logger.info(msg); } public static void warning(String msg) { logger.warning(msg); } public static void error(String msg) { logger.severe(msg); } }
package net.rodrigoamaral.logging; import java.util.logging.*; public class SPSPLogger { public static final Logger logger = Logger.getLogger(SPSPLogger.class.getName()); static { config(); } private static void config() { LogManager manager = LogManager.getLogManager(); manager.reset(); logger.setLevel(Level.ALL); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(Level.INFO); ch.setFormatter(new SPSPLogFormatter()); logger.addHandler(ch); // TODO: Implement a log file handler } public static void info(String msg) { logger.info(msg); } public static void warning(String msg) { logger.warning(msg); } public static void severe(String msg) { logger.severe(msg); } }
[TASK] Set active to true, because non active scripts shouldn't appear
<?php namespace Parabot\BDN\BotBundle\Repository; use Doctrine\ORM\EntityRepository; use Parabot\BDN\BotBundle\Entity\Script; use Parabot\BDN\BotBundle\Entity\Scripts\Git; use Parabot\BDN\UserBundle\Entity\User; /** * ScriptRepository */ class ScriptRepository extends EntityRepository { /** * @param int $id * * @return null|Git */ public function findOneGitById($id) { /** @var Script $result */ $result = $this->findOneBy([ 'id' => $id ]); if($result != null) { if(($git = $result->getGit()) != null) { return $result->getGit(); } } return null; } /** * @param User $user * * @return Script[] */ public function findByAuthor($user) { $query = $this->getEntityManager()->createQuery( 'SELECT s FROM BDNBotBundle:Script s JOIN s.authors a WHERE a.id = :id AND s.active = 1' )->setParameter('id', $user->getId()); return $query->getResult(); } }
<?php namespace Parabot\BDN\BotBundle\Repository; use Doctrine\ORM\EntityRepository; use Parabot\BDN\BotBundle\Entity\Script; use Parabot\BDN\BotBundle\Entity\Scripts\Git; use Parabot\BDN\UserBundle\Entity\User; /** * ScriptRepository */ class ScriptRepository extends EntityRepository { /** * @param int $id * * @return null|Git */ public function findOneGitById($id) { /** @var Script $result */ $result = $this->findOneBy([ 'id' => $id ]); if($result != null) { if(($git = $result->getGit()) != null) { return $result->getGit(); } } return null; } /** * @param User $user * * @return Script[] */ public function findByAuthor($user) { $query = $this->getEntityManager()->createQuery( 'SELECT s FROM BDNBotBundle:Script s JOIN s.authors a WHERE a.id = :id' )->setParameter('id', $user->getId()); return $query->getResult(); } }
Revert to non-parallel chmod (argument list too long)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} ;' % dirname)
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_TO), os.path.join(settings.MEDIA_ROOT, "letters"), os.path.join(settings.MEDIA_ROOT, "mailings"), os.path.join(settings.MEDIA_ROOT, "page_picker_thumbs"), settings.PUBLIC_MEDIA_ROOT): print dirname # files: -rw-rw-r-- os.system('sudo chmod -R u=rwX,g=rwX,o=rX "%s"' % dirname) os.system('sudo chown -R www-data.btb "%s"' % dirname) # directories: -rwxrwsr-x os.system('sudo find "%s" -type d -exec sudo chmod g+s {} +' % dirname)
Hide click to play message if video is already playing
/* global AFRAME */ AFRAME.registerComponent('hide-on-play', { schema: {type: 'selector'}, init: function () { this.onPlaying = this.onPlaying.bind(this); this.onPause = this.onPause.bind(this); this.el.object3D.visible = !this.data.playing; }, play: function () { if (this.data) { this.data.addEventListener('playing', this.onPlaying); this.data.addEventListener('pause', this.onPause); } }, pause: function () { if (this.data) { this.data.removeEventListener('playing', this.onPlaying); this.data.removeEventListener('pause', this.onPause); } }, onPlaying: function (evt) { this.el.object3D.visible = false; }, onPause: function (evt) { this.el.object3D.visible = true; } });
/* global AFRAME */ AFRAME.registerComponent('hide-on-play', { schema: {type: 'selector'}, init: function () { this.onPlaying = this.onPlaying.bind(this); this.onPause = this.onPause.bind(this); }, play: function () { if (this.data) { this.data.addEventListener('playing', this.onPlaying); this.data.addEventListener('pause', this.onPause); } }, pause: function () { if (this.data) { this.data.removeEventListener('playing', this.onPlaying); this.data.removeEventListener('pause', this.onPause); } }, onPlaying: function (evt) { this.el.setAttribute('visible', false); }, onPause: function (evt) { this.el.setAttribute('visible', true); } });
Update vert.x to vertx in mongo.
db.broadcast.remove(); db.broadcast.insert({ "_id": 1, "text": "GVM version 0.9.4 " }); db.broadcast.insert({ "_id": 2, "text": "In this release: " }); db.broadcast.insert({ "_id": 3, "text": " * vert.x renamed to vertx " }); db.broadcast.insert({ "_id": 4, "text": " " }); db.broadcast.insert({ "_id": 5, "text": "Report any issues at: " }); db.broadcast.insert({ "_id": 6, "text": " https://github.com/gvmtool/gvm/issues " }); //rename vert.x to vertx db.candidates.update({candidate:"vert.x"}, {$set:{candidate:"vertx"}}); db.versions.update({candidate:"vert.x"}, {$set:{candidate:"vertx"}}, {multi:true});
db.broadcast.remove(); db.broadcast.insert({ "_id": 1, "text": "GVM version 0.9.3 " }); db.broadcast.insert({ "_id": 2, "text": "In this release: " }); db.broadcast.insert({ "_id": 3, "text": " * GVM switches to a modular architecture. " }); db.broadcast.insert({ "_id": 7, "text": " " }); db.broadcast.insert({ "_id": 8, "text": "Report any issues at: " }); db.broadcast.insert({ "_id": 9, "text": " https://github.com/gvmtool/gvm/issues " });
Extend prototype with non-enumerable property This way we don't mess up peoples' code depending on `for..in` or `Object.keys`. Many people rely on Object.prototype having no enumerable properties and do things like: ```js for(key in {a:1, b:2}) foo(key); ``` More info on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
'use strict'; /** * @module object-loops */ var dasherize = require('dasherize'); var exists = require('101/exists'); var envIs = require('101/env-is'); var path = require('path'); /** * Extends Object.prototype with all "object-loops" methods * @function module:object-loops * @param {boolean} hideWarnings - Will hide warnings that appear if a method already exists. */ module.exports = extendObjectPrototype; function extendObjectPrototype (hideWarnings) { [ 'forEach', 'map', 'filter', 'reduce' ].forEach(function (methodName) { var filename = dasherize(methodName); var filepath = path.resolve('./'+filename); if (Object.prototype[methodName] && !hideWarnings) { console.log('warn: "Object.prototype.' + methodName + '" already exists.'); } else { var method = require(filepath); Object.defineProperty(Object.prototype, methodName, { value: function () { if (this === global) { throw new TypeError('this is null or not defined for '+method); } var args = Array.prototype.slice.call(arguments); args.unshift(this); // sets first arg as object instance return method.apply(this, args); }, enumerable: false, configurable: envIs('test') // hack for tests }); } }); }
'use strict'; /** * @module object-loops */ var dasherize = require('dasherize'); var exists = require('101/exists'); var envIs = require('101/env-is'); var path = require('path'); /** * Extends Object.prototype with all "object-loops" methods * @function module:object-loops * @param {boolean} hideWarnings - Will hide warnings that appear if a method already exists. */ module.exports = extendObjectPrototype; function extendObjectPrototype (hideWarnings) { [ 'forEach', 'map', 'filter', 'reduce' ].forEach(function (methodName) { var filename = dasherize(methodName); var filepath = path.resolve('./'+filename); if (Object.prototype[methodName] && !hideWarnings) { console.log('warn: "Object.prototype.' + methodName + '" already exists.'); } else { var method = require(filepath); Object.defineProperty(Object.prototype, methodName, { value: function () { if (this === global) { throw new TypeError('this is null or not defined for '+method); } var args = Array.prototype.slice.call(arguments); args.unshift(this); // sets first arg as object instance return method.apply(this, args); }, configurable: envIs('test') // hack for tests }); } }); }
Change users migration code to empty string
'use strict'; exports.up = function(knex) { return knex.schema.createTable('users', (table) => { table.increments(); table.string('first_name') .notNullable() .defaultTo(''); table.string('last_name') .notNullable() .defaultTo(''); table.string('email') .unique() .notNullable() .defaultTo(''); table.specificType('hashed_password', 'char(60)') .notNullable(); table.boolean('kj') .notNullable() .defaultTo(false); table.string('code').defaultTo(''); table.boolean('accept').defaultTo('false'); table.timestamps(true, true); }); }; exports.down = function(knex) { return knex.schema.dropTable('users'); };
'use strict'; exports.up = function(knex) { return knex.schema.createTable('users', (table) => { table.increments(); table.string('first_name') .notNullable() .defaultTo(''); table.string('last_name') .notNullable() .defaultTo(''); table.string('email') .unique() .notNullable() .defaultTo(''); table.specificType('hashed_password', 'char(60)') .notNullable(); table.boolean('kj') .notNullable() .defaultTo(false); table.string('code').defaultTo(null); table.boolean('accept').defaultTo('false'); table.timestamps(true, true); }); }; exports.down = function(knex) { return knex.schema.dropTable('users'); };
Update futex to allow timeouts to be passed
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // +build akaros package parlib /* #include <parlib.h> #include <uthread.h> #include <vcore.h> #include <mcs.h> #include <futex.h> */ import "C" import "unsafe" func Futex(uaddr *int32, op int32, val int32, timeout *Timespec, uaddr2 *int32, val3 int32) (ret int32) { // For now, akaros futexes don't support uaddr2 or val3, so we // just 0 them out. uaddr2 = nil; val3 = 0; // Also, the minimum timout is 1ms, so up it to that if it's too small if (timeout != nil) { if (timeout.tv_sec == 0) { if (timeout.tv_nsec < 1000000) { timeout.tv_nsec = 1000000; } } } return int32(C.futex((*C.int)(unsafe.Pointer(uaddr)), C.int(op), C.int(val), (*C.struct_timespec)(unsafe.Pointer(timeout)), (*C.int)(unsafe.Pointer(uaddr2)), C.int(val3))) }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // +build akaros package parlib /* #include <parlib.h> #include <uthread.h> #include <vcore.h> #include <mcs.h> #include <futex.h> */ import "C" import "unsafe" func Futex(uaddr *int32, op int32, val int32, timeout *Timespec, uaddr2 *int32, val3 int32) (ret int32) { // For now, akaros futexes don't support timeout, uaddr2 or val3, so we // just 0 them out. timeout = nil uaddr2 = nil val3 = 0 return int32(C.futex((*C.int)(unsafe.Pointer(uaddr)), C.int(op), C.int(val), (*C.struct_timespec)(unsafe.Pointer(timeout)), (*C.int)(unsafe.Pointer(uaddr2)), C.int(val3))) }
Add a pragma and in the future we need to fix the function, because it's a duplicata
# -*- coding: UTF-8 -*- import urllib import httplib import simplejson G = 'maps.google.com' # FIXME: use this function or this one, but the code is in double assopy.utils.geocode def geocode(address, key, country): # pragma: no cover """ Get the coordinates from Google Maps for a specified address """ # see http://code.google.com/intl/it/apis/maps/documentation/geocoding/#GeocodingRequests params = { 'q': address.encode('utf-8') if isinstance(address, unicode) else address, 'key': key, 'sensor': 'false', 'output': 'json', 'oe': 'utf8', } if country: params['gl'] = country url = '/maps/geo?' + urllib.urlencode(params.items()) conn = httplib.HTTPConnection(G) try: conn.request('GET', url) r = conn.getresponse() if r.status == 200: return simplejson.loads(r.read()) else: return {'Status': {'code': r.status }} finally: conn.close()
# -*- coding: UTF-8 -*- import urllib import httplib import simplejson G = 'maps.google.com' def geocode(address, key, country): """ Get the coordinates from Google Maps for a specified address """ # see http://code.google.com/intl/it/apis/maps/documentation/geocoding/#GeocodingRequests params = { 'q': address.encode('utf-8') if isinstance(address, unicode) else address, 'key': key, 'sensor': 'false', 'output': 'json', 'oe': 'utf8', } if country: params['gl'] = country url = '/maps/geo?' + urllib.urlencode(params.items()) conn = httplib.HTTPConnection(G) try: conn.request('GET', url) r = conn.getresponse() if r.status == 200: return simplejson.loads(r.read()) else: return {'Status': {'code': r.status }} finally: conn.close()
Add fling to channel object.
'use strict'; /* jshint -W074 */ const network = require('./network'); const runtime = require('./runtime'); class ChannelDelegate { static create (name, options, context) { options = options || {}; let id; if (!runtime.auth) throw new Error('Not authenticated.'); const array = [runtime.auth.identity.organization, name, (options.system ? 1 : 0), (options.consumer ? 1: 0)]; const string = JSON.stringify(array); if (typeof window === 'undefined') id = (new Buffer(string)).toString('base64'); else id = btoa(string); return new this(id, context); } constructor (id, context) { this.id = id; this.context = context; } broadcast (name, payload, timeout) { return network.broadcast(name, this.id, payload, timeout); } listen (name, callback) { return network.listen(name, this.id, callback, this.context); } fling (payload) { return this.broadcast('fling', payload); } } module.exports = ChannelDelegate;
'use strict'; /* jshint -W074 */ const network = require('./network'); const runtime = require('./runtime'); class ChannelDelegate { static create (name, options, context) { options = options || {}; let id; if (!runtime.auth) throw new Error('Not authenticated.'); const array = [runtime.auth.identity.organization, name, (options.system ? 1 : 0), (options.consumer ? 1: 0)]; const string = JSON.stringify(array); if (typeof window === 'undefined') id = (new Buffer(string)).toString('base64'); else id = btoa(string); return new this(id, context); } constructor (id, context) { this.id = id; this.context = context; } broadcast (name, payload, timeout) { return network.broadcast(name, this.id, payload, timeout); } listen (name, callback) { return network.listen(name, this.id, callback, this.context); } } module.exports = ChannelDelegate;
Fix critical upgrade/repair bug. Initial changes to allow multiple player groups.
package com.untamedears.citadel.entity; import com.untamedears.citadel.Citadel; import javax.persistence.Entity; import javax.persistence.Id; /** * Created by IntelliJ IDEA. * User: chrisrico * Date: 3/21/12 * Time: 1:14 AM */ @Entity public class Faction { @Id private String name; private String founder; public Faction() { } public Faction(String name, String founder) { this.name = name; this.founder = founder; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFounder() { return founder; } public void setFounder(String founder) { this.founder = founder; } public boolean hasMember(String memberName) { return Citadel.getInstance().dao.hasGroupMember(name, memberName); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Faction)) return false; Faction faction = (Faction) o; return name.equals(faction.name); } @Override public int hashCode() { return name.hashCode(); } }
package com.untamedears.citadel.entity; import com.untamedears.citadel.Citadel; import javax.persistence.Entity; import javax.persistence.Id; /** * Created by IntelliJ IDEA. * User: chrisrico * Date: 3/21/12 * Time: 1:14 AM */ @Entity public class Faction { @Id private String name; private String founder; public Faction() { } public Faction(String name, String founder) { this.name = name; this.founder = founder; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFounder() { return founder; } public void setFounder(String founder) { this.founder = founder; } public boolean hasMember(String memberName) { return Citadel.getInstance().dao.hasGroupMember(name, memberName); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Faction)) return false; Faction faction = (Faction) o; return name.equals(faction.name); } @Override public int hashCode() { return name.hashCode(); } }
Rename template_name @config arg to template
from tangled.web import Resource, config from tangled.site.resources.entry import Entry class Docs(Entry): @config('text/html', template='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
from tangled.web import Resource, config from tangled.site.resources.entry import Entry class Docs(Entry): @config('text/html', template_name='tangled.website:templates/docs.mako') def GET(self): static_dirs = self.app.get_all('static_directory', as_dict=True) links = [] for prefix, dir_app in static_dirs.items(): if prefix[0] == 'docs': links.append({ 'href': '/'.join(prefix), 'text': prefix[1], }) self.urlvars['id'] = 'docs' data = super().GET() data['links'] = sorted(links, key=lambda i: i['text']) return data
Use /package instead of /image in url
var config = { width: 300, height: 100, background: '#dedede', stroke: 'red' }; var serve = function(request, response) { var url_parts = request.url.split('/'); var url = `https://atmospherejs.com/a/packages/findByNames?names=${url_parts[1]}`; var opt = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opt, function (err, res) { response.writeHead(200, { "Content-Type": "image/svg+xml" }); response.write(`<svg xmlns="http://www.w3.org/2000/svg" height="${config.height}" width="${config.width}"> <rect x="0" y="0" width="${config.width}" height="${config.height}" fill="${config.background}" stroke-width="4" stroke="${config.stroke}" /> <text x="20" y="20" font-family="Verdana" font-size="30">${res.data[0].name}</text> </svg>`); response.end(); }); }; WebApp.connectHandlers.use("/package", serve);
var config = { width: 300, height: 100, background: '#dedede', stroke: 'red' }; var serve = function(request, response) { var url_parts = request.url.split('/'); var url = `https://atmospherejs.com/a/packages/findByNames?names=${url_parts[1]}`; var opt = {headers: {'Accept': 'application/json'}}; HTTP.get(url, opt, function (err, res) { response.writeHead(200, { "Content-Type": "image/svg+xml" }); response.write(`<svg xmlns="http://www.w3.org/2000/svg" height="${config.height}" width="${config.width}"> <rect x="0" y="0" width="${config.width}" height="${config.height}" fill="${config.background}" stroke-width="4" stroke="${config.stroke}" /> <text x="20" y="20" font-family="Verdana" font-size="30">${res.data[0].name}</text> </svg>`); response.end(); }) }; WebApp.connectHandlers.use("/image", serve);
Rewrite controller for Dependency Injection.
<?php namespace My\TestBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use My\TestBundle\Light\LightSwitch; class LightController extends Controller { protected $lightSwitch; public function __construct(LightSwitch $lightSwitch) { $this->lightSwitch = $lightSwitch; } public function switchAction($switch) { if($switch === "on") { $this->lightSwitch->on(); } else { $this->lightSwitch->off(); } return $this->redirect($this->generateUrl('light_status'), 301); } public function statusAction() { return $this->render('MyTestBundle:Light:status.html.twig', array('status' => $this->lightSwitch->getStatus())); } }
<?php namespace My\TestBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LightController extends Controller { public function switchAction($switch) { $lightSwitch = $this->container->get('light_switch'); if($switch === "on") { $lightSwitch->on(); } else { $lightSwitch->off(); } return $this->redirect($this->generateUrl('light_status'), 301); } public function statusAction() { $lightSwitch = $this->container->get('light_switch'); return $this->render('MyTestBundle:Light:status.html.twig', array('status' => $lightSwitch->getStatus())); } }
Use admin user for admin challenges
const config = require('config') describe('/#/administration', () => { describe('challenge "adminSection"', () => { protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' }) it('should be possible to access administration section with admin user', () => { browser.get('/#/administration') expect(browser.getCurrentUrl()).toMatch(/\/administration/) }) protractor.expect.challengeSolved({ challenge: 'Admin Section' }) }) describe('challenge "fiveStarFeedback"', () => { protractor.beforeEach.login({ email: 'admin@' + config.get('application.domain'), password: 'admin123' }) it('should be possible for any admin user to delete feedback', () => { browser.get('/#/administration') $$('.mat-cell.mat-column-remove > button').first().click() browser.wait(protractor.ExpectedConditions.stalenessOf(element(by.js(selectFiveStarRating))), 5000) }) protractor.expect.challengeSolved({ challenge: 'Five-Star Feedback' }) }) }) function selectFiveStarRating () { var rating = document.querySelector('.br-units') if (rating.querySelectorAll('.br-selected').length === 5) { return rating } }
const config = require('config') describe('/#/administration', () => { describe('challenge "adminSection"', () => { it('should be possible to access administration section even when not authenticated', () => { browser.get('/#/administration') expect(browser.getCurrentUrl()).toMatch(/\/administration/) }) protractor.expect.challengeSolved({ challenge: 'Admin Section' }) }) describe('challenge "fiveStarFeedback"', () => { protractor.beforeEach.login({ email: 'jim@' + config.get('application.domain'), password: 'ncc-1701' }) it('should be possible for any logged-in user to delete feedback', () => { browser.get('/#/administration') $$('.mat-cell.mat-column-remove > button').first().click() browser.wait(protractor.ExpectedConditions.stalenessOf(element(by.js(selectFiveStarRating))), 5000) }) protractor.expect.challengeSolved({ challenge: 'Five-Star Feedback' }) }) }) function selectFiveStarRating () { var rating = document.querySelector('.br-units') if (rating.querySelectorAll('.br-selected').length === 5) { return rating } }
Use base TestCase to properly cleanup indices
from mock import patch from feedhq.feeds.models import Favicon, Feed from .factories import FeedFactory from . import responses, TestCase class FaviconTests(TestCase): @patch("requests.get") def test_existing_favicon_new_feed(self, get): get.return_value = responses(304) FeedFactory.create(url='http://example.com/feed') self.assertEqual(Feed.objects.values_list('favicon', flat=True)[0], '') # Simulate a 1st call of update_favicon which creates a Favicon entry Favicon.objects.create(url='http://example.com/feed', favicon='favicons/example.com.ico') Favicon.objects.update_favicon('http://example.com/feed') self.assertEqual(Feed.objects.values_list('favicon', flat=True)[0], 'favicons/example.com.ico')
from django.test import TestCase from mock import patch from feedhq.feeds.models import Favicon, Feed from .factories import FeedFactory from . import responses class FaviconTests(TestCase): @patch("requests.get") def test_existing_favicon_new_feed(self, get): get.return_value = responses(304) FeedFactory.create(url='http://example.com/feed') self.assertEqual(Feed.objects.values_list('favicon', flat=True)[0], '') # Simulate a 1st call of update_favicon which creates a Favicon entry Favicon.objects.create(url='http://example.com/feed', favicon='favicons/example.com.ico') Favicon.objects.update_favicon('http://example.com/feed') self.assertEqual(Feed.objects.values_list('favicon', flat=True)[0], 'favicons/example.com.ico')
Fix numbers cast to int
Template.dash.total = function(){ var total = 0; Expenses.find().map(function(doc){ total += doc.ammount; }); return total; }; Template.dash.me = function(){ var total = 0; Expenses.find().map(function(doc){ if (doc.payer === Meteor.userId()) { total -= doc.ammount; } if (doc.owers.indexOf(Meteor.userId()) != -1){ total += doc.ammount / doc.owers.length; } }); return total; }; Template.dash.getOwes = function(){ var result = {}; // For each expense where I owe money... Expenses.find({owers : Meteor.userId()}).map(function (doc) { // ...subtract my share of the expense result[doc.payer] = (result[doc.payer]||0) - (doc.ammount / doc.owers.length); }); // For each expense where I paid... Expenses.find({payer: Meteor.userId()}).map(function (doc) { // ...and for each person that is splitting the cost... doc.owers.forEach(function(ower){ // ...add their share of the expense result[ower] = (result[ower]||0) + (doc.ammount / doc.owers.length); }); }); var objs = []; for(var id in result){ if (result[id]){ objs.push({user: id, ammount: result[id]}); } } return objs; }
Template.dash.total = function(){ var total = 0; Expenses.find().map(function(doc){ total += doc.ammount; }); return total; }; Template.dash.me = function(){ var total = 0; Expenses.find().map(function(doc){ if (doc.payer === Meteor.userId()) { total -= doc.ammount; } if (doc.owers.indexOf(Meteor.userId()) != -1){ total += doc.ammount / doc.owers.length; } }); return total; }; Template.dash.getOwes = function(){ var result = {}; // For each expense where I owe money... Expenses.find({owers : Meteor.userId()}).map(function (doc) { // ...subtract my share of the expense result[doc.payer] = (result[doc.payer]|0) - (doc.ammount / doc.owers.length); }); // For each expense where I paid... Expenses.find({payer: Meteor.userId()}).map(function (doc) { // ...and for each person that is splitting the cost... doc.owers.forEach(function(ower){ // ...add their share of the expense result[ower] = (result[ower]|0) + (doc.ammount / doc.owers.length); }); }); var objs = []; for(var id in result){ if (result[id]){ objs.push({user: id, ammount: result[id]}); } } return objs; }
Remove failing test for now
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.contrib.auth.models import User from django.core.urlresolvers import reverse from preferences.models import Preferences class BillViewTests(StaticLiveServerTestCase): fixtures = ['fl_testdata.json'] def setUp(self): u = User.objects.create_user('test') p = Preferences.objects.create(user=u) self.apikey = p.apikey def test_by_topic_view(self): response = self.client.get(reverse('by_topic')) self.assertEqual(response.status_code, 200) # def test_by_topic_view_selected(self): # response = self.client.get(reverse('by_topic_selected')) # self.assertEqual(response.status_code, 200)
from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.contrib.auth.models import User from django.core.urlresolvers import reverse from opencivicdata.models import Bill, LegislativeSession, Person from tot import settings from preferences.models import Preferences BILL_FULL_FIELDS = ('abstracts', 'other_titles', 'other_identifiers', 'actions', 'related_bills', 'sponsorships', 'documents', 'versions', 'sources') class BillViewTests(StaticLiveServerTestCase): fixtures = ['fl_testdata.json'] def setUp(self): u = User.objects.create_user('test') p = Preferences.objects.create(user=u) self.apikey = p.apikey def test_by_topic_view(self): response = self.client.get(reverse('by_topic')) self.assertEqual(response.status_code, 200) def test_by_topic_view_selected(self): response = self.client.get(reverse('by_topic_selected')) self.assertEqual(response.status_code, 200)
Fix issue with https and Google analytics tracking code. Use `str::after($string, $after);` to always get the (sub)domain without `http://` or `https://`.
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // Google analytics.js // ---------------------------------------------------------- // Enable and set analytics ID/API KEY in config.php // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// // ---------------------------------------------------------- // Google Universal Analytics // ---------------------------------------------------------- if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?> <script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::after($site->url(), '://'); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script> <script src="https://www.google-analytics.com/analytics.js" async defer></script> <?php else: ?> <!-- NO TRACKING SET! --> <?php endif; ?>
<?php /////////////////////////////////////////////////////// // ---------------------------------------------------------- // SNIPPET // ---------------------------------------------------------- // Google analytics.js // ---------------------------------------------------------- // Enable and set analytics ID/API KEY in config.php // ---------------------------------------------------------- ///////////////////////////////////////////////////////////// // ---------------------------------------------------------- // Google Universal Analytics // ---------------------------------------------------------- if (c::get('google.analytics') == true && c::get('google.analytics.id') != 'TRACKING ID IS NOT SET'): ?> <script>window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;ga('create','<?php echo c::get("google.analytics.id", "TRACKING ID IS NOT SET"); ?>','<?php echo str::substr($site->url(), 7); ?>');ga('set', 'anonymizeIp', true);ga('set', 'forceSSL', true);ga('send','pageview')</script> <script src="https://www.google-analytics.com/analytics.js" async defer></script> <?php else: ?> <!-- NO TRACKING SET! --> <?php endif; ?>
Rename timestamp to data and show data instead of this.raw (which doesn't do anything)
var five = require("../lib/johnny-five.js"), board, accel; board = new five.Board(); board.on("ready", function() { // Create a new `Accelerometer` hardware instance. // // five.Accelerometer([ x, y[, z] ]); // // five.Accelerometer({ // pins: [ x, y[, z] ] // freq: ms // }); // accel = new five.Accelerometer({ pins: [ "A3", "A4", "A5" ], freq: 100, threshold: 0.2 }); // Accelerometer Event API // "acceleration" // // Fires once every N ms, equal to value of freg // Defaults to 500ms // accel.on("acceleration", function( err, data ) { console.log( "acceleration", data.smooth ); }); // "axischange" // // Fires only when X, Y or Z has changed // accel.on("axischange", function( err, data ) { console.log( "axischange", data.smooth ); }); }); // @markdown // // - [Triple Axis Accelerometer, MMA7361](https://www.sparkfun.com/products/9652) // - [Triple-Axis Accelerometer, ADXL326](http://www.adafruit.com/products/1018) // // @markdown
var five = require("../lib/johnny-five.js"), board, accel; board = new five.Board(); board.on("ready", function() { // Create a new `Accelerometer` hardware instance. // // five.Accelerometer([ x, y[, z] ]); // // five.Accelerometer({ // pins: [ x, y[, z] ] // freq: ms // }); // accel = new five.Accelerometer({ pins: [ "A3", "A4", "A5" ], freq: 100, threshold: 0.2 }); // Accelerometer Event API // "acceleration" // // Fires once every N ms, equal to value of freg // Defaults to 500ms // accel.on("acceleration", function( err, data ) { console.log( "acceleration", data.smooth ); }); // "axischange" // // Fires only when X, Y or Z has changed // accel.on("axischange", function( err, timestamp ) { console.log( "axischange", this.raw ); }); }); // @markdown // // - [Triple Axis Accelerometer, MMA7361](https://www.sparkfun.com/products/9652) // - [Triple-Axis Accelerometer, ADXL326](http://www.adafruit.com/products/1018) // // @markdown
Add player upgrade packet code
module.exports = { // Packet constants PLAYER_START: "1", PLAYER_ADD: "2", PLAYER_ANGLE: "2", PLAYER_UPDATE: "3", PLAYER_ATTACK :"4", LEADERBOAD: "5", PLAYER_MOVE: "3", PLAYER_REMOVE: "4", LEADERS_UPDATE: "5", LOAD_GAME_OBJ: "6", PLAYER_UPGRADE: "6", GATHER_ANIM: "7", AUTO_ATK: "7", WIGGLE: "8", CLAN_CREATE: "8", PLAYER_LEAVE_CLAN: "9", STAT_UPDATE: "9", CLAN_REQ_JOIN: "10", UPDATE_HEALTH: "10", CLAN_ACC_JOIN: "11", CLAN_KICK: "12", ITEM_BUY: "13", UPDATE_AGE: "15", UPGRADES: "16", CHAT: "ch", CLAN_DEL: "ad", PLAYER_SET_CLAN: "st", SET_CLAN_PLAYERS: "sa", CLAN_ADD: "ac", CLAN_NOTIFY: "an", MINIMAP: "mm", UPDATE_STORE: "us", DISCONN: "d" }
module.exports = { // Packet constants PLAYER_START: "1", PLAYER_ADD: "2", PLAYER_ANGLE: "2", PLAYER_UPDATE: "3", PLAYER_ATTACK :"4", LEADERBOAD: "5", PLAYER_MOVE: "3", PLAYER_REMOVE: "4", LEADERS_UPDATE: "5", LOAD_GAME_OBJ: "6", GATHER_ANIM: "7", AUTO_ATK: "7", WIGGLE: "8", CLAN_CREATE: "8", PLAYER_LEAVE_CLAN: "9", STAT_UPDATE: "9", CLAN_REQ_JOIN: "10", UPDATE_HEALTH: "10", CLAN_ACC_JOIN: "11", CLAN_KICK: "12", ITEM_BUY: "13", UPDATE_AGE: "15", UPGRADES: "16", CHAT: "ch", CLAN_DEL: "ad", PLAYER_SET_CLAN: "st", SET_CLAN_PLAYERS: "sa", CLAN_ADD: "ac", CLAN_NOTIFY: "an", MINIMAP: "mm", UPDATE_STORE: "us", DISCONN: "d" }
Update code to work with latest version of mux Add explicit support to HEAD requests otherwise Vagrant will stop working.
// This is a simple web application that makes possible to use Open Build // Service as a simple Vagrant image catalog. package main import ( "flag" "fmt" "log" "net/http" "github.com/codegangsta/negroni" "github.com/gorilla/mux" ) // Returns the "Not found" response. func notFound(w http.ResponseWriter, req *http.Request) { writeError(w, errorResponse{ Error: "Not Found", Code: http.StatusNotFound, }) } func main() { var configFile string const defaultConfigFile = "obs2vagrant.json" flag.StringVar(&configFile, "c", defaultConfigFile, "configuration file") flag.Parse() err := readConfig(configFile) if err != nil { log.Fatalf("Error while parsing configuration file: %s", err) } n := negroni.New(negroni.NewRecovery(), negroni.NewLogger()) r := mux.NewRouter() r.NotFoundHandler = http.HandlerFunc(notFound) r.HandleFunc("/{server}/{project}/{repo}/{box}.json", boxHandler). Methods("GET", "HEAD") n.UseHandler(r) listenOn := fmt.Sprintf("%v:%v", cfg.Address, cfg.Port) n.Run(listenOn) }
// This is a simple web application that makes possible to use Open Build // Service as a simple Vagrant image catalog. package main import ( "flag" "fmt" "log" "net/http" "github.com/codegangsta/negroni" "github.com/gorilla/mux" ) // Returns the "Not found" response. func notFound(w http.ResponseWriter, req *http.Request) { writeError(w, errorResponse{ Error: "Not Found", Code: http.StatusNotFound, }) } func main() { var configFile string const defaultConfigFile = "obs2vagrant.json" flag.StringVar(&configFile, "c", defaultConfigFile, "configuration file") flag.Parse() err := readConfig(configFile) if err != nil { log.Fatalf("Error while parsing configuration file: %s", err) } n := negroni.New(negroni.NewRecovery(), negroni.NewLogger()) r := mux.NewRouter() r.NotFoundHandler = http.HandlerFunc(notFound) r.HandleFunc("/{server}/{project}/{repo}/{box}.json", boxHandler). Methods("GET") n.UseHandler(r) listenOn := fmt.Sprintf("%v:%v", cfg.Address, cfg.Port) n.Run(listenOn) }
Test posts route model works now - wrapped model promise in run loop
/* global ic */ import { test , moduleFor } from 'ghost/tests/helpers/module_for'; import PostsRoute from 'ghost/routes/posts'; moduleFor('route:posts', "Unit - PostsRoute", { setup: function(){ ic.ajax.defineFixture('/ghost/api/v0.1/posts', { response: [{ "posts": [ { "id": 2, "uuid": "4dc16b9e-bf90-44c9-97c5-40a0a81e8297", "title": "Ghost Ember Demo Post", } ] }], jqXHR: {}, textStatus: 'success' }); }, }); test("it exists", function(){ ok(this.subject() instanceof PostsRoute); }); test("model", function(){ expect(1); var expectedResult = ic.ajax.lookupFixture('/ghost/api/v0.1/posts').response; var route = this.subject(); Ember.run(function() { route.model().then(function(model) { deepEqual(model, expectedResult, "Route model should match exptected"); }); }); });
/* global ic */ import { test , moduleFor } from 'ghost/tests/helpers/module_for'; import PostsRoute from 'ghost/routes/posts'; moduleFor('route:posts', "Unit - PostsRoute", { setup: function(){ ic.ajax.defineFixture('/ghost/api/v0.1/posts', { response: [{ "posts": [ { "id": 2, "uuid": "4dc16b9e-bf90-44c9-97c5-40a0a81e8297", "title": "Ghost Ember Demo Post", } ] }], jqXHR: {}, textStatus: 'success' }); }, }); test("it exists", function(){ ok(this.subject() instanceof PostsRoute); }); // not working: model promise seems to never resolve => loading route // test("model", function(){ // expect(1); // var expectedResult = ic.ajax.lookupFixture('/ghost/api/v0.1/posts').response; // var route = this.subject(); // route.model().then(function(model) { // deepEqual(model, expectedResult, "Route model should match exptected"); // }); // });
Add some docs to register_hooks
<?php class WPMessagePresenter implements MessagePresenter { /** * @var string[] */ protected $messages; /** * Registers hooks to WordPress. This is a seperate function so you can control when the hooks are registered. */ public function register_hooks() { add_action( 'admin_notices', array( $this, 'renderMessage' ) ); } /** * Shows a message to the user * * @param string $message The message to show to the user */ public function show( $message ) { $this->messages[] = $message; } public function renderMessage() { ?> <div class="error"> <?php echo $this->kses( $this->messages[0] ); ?> </div> <?php } public function kses( $message ) { return wp_kses( $message, array( 'a' => array( 'href' => true, ), 'strong' => true, 'p' => true, ) ); } }
<?php class WPMessagePresenter implements MessagePresenter { /** * @var string[] */ protected $messages; public function register_hooks() { add_action( 'admin_notices', array( $this, 'renderMessage' ) ); } /** * Shows a message to the user * * @param string $message The message to show to the user */ public function show( $message ) { $this->messages[] = $message; } public function renderMessage() { ?> <div class="error"> <?php echo $this->kses( $this->messages[0] ); ?> </div> <?php } public function kses( $message ) { return wp_kses( $message, array( 'a' => array( 'href' => true, ), 'strong' => true, 'p' => true, ) ); } }
Add comment around tooltip lookup based on component class
import $ from 'jquery'; export default function findTooltip(selector) { if (!selector) { // In case of passing null, undefined, etc selector = '.ember-tooltip, .ember-popover'; } /* We .find() tooltips from $body instead of using ember-test-helper's find() method because tooltips and popovers are often rendered as children of <body> instead of children of the $targetElement */ const $body = $(document.body); let $tooltip = $body.find(selector); if ($tooltip.length && $tooltip.hasClass('ember-tooltip-base')) { /* If what we find is the actually the tooltip component's element, we can * look up the intended tooltip by the element referenced by its target * element's aria-describedby attribute. */ const $target = $tooltip.parents('.ember-tooltip-target, .ember-popover-target'); $tooltip = $body.find(`#${$target.attr('aria-describedby')}`); } if ($tooltip.length && !$tooltip.hasClass('ember-tooltip') && !$tooltip.hasClass('ember-popover')) { throw Error(`getTooltipFromBody(): returned an element that is not a tooltip`); } else if ($tooltip.length > 1) { console.warn(`getTooltipFromBody(): Multiple tooltips were found. Consider passing { selector: '.specific-tooltip-class' }`); } return $tooltip; }
import $ from 'jquery'; export default function findTooltip(selector) { if (!selector) { // In case of passing null, undefined, etc selector = '.ember-tooltip, .ember-popover'; } /* We .find() tooltips from $body instead of using ember-test-helper's find() method because tooltips and popovers are often rendered as children of <body> instead of children of the $targetElement */ const $body = $(document.body); let $tooltip = $body.find(selector); if ($tooltip.length && $tooltip.hasClass('ember-tooltip-base')) { const $target = $tooltip.parents('.ember-tooltip-target, .ember-popover-target'); $tooltip = $body.find(`#${$target.attr('aria-describedby')}`); } if ($tooltip.length && !$tooltip.hasClass('ember-tooltip') && !$tooltip.hasClass('ember-popover')) { throw Error(`getTooltipFromBody(): returned an element that is not a tooltip`); } else if ($tooltip.length > 1) { console.warn(`getTooltipFromBody(): Multiple tooltips were found. Consider passing { selector: '.specific-tooltip-class' }`); } return $tooltip; }
Remove nasty querySelector / head / appendChild hack for ShadowDOM Polyfill - Requires fix from Polymer/ShadowDOM#228
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; document.head.appendChild(el); })();
(function() { function selector(v) { return '[touch-action="' + v + '"]'; } function rule(v) { return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }'; } var attrib2css = [ 'none', 'auto', 'pan-x', 'pan-y', { rule: 'pan-x pan-y', selectors: [ 'pan-x pan-y', 'pan-y pan-x' ] } ]; var styles = ''; attrib2css.forEach(function(r) { if (String(r) === r) { styles += selector(r) + rule(r); } else { styles += r.selectors.map(selector) + rule(r.rule); } }); var el = document.createElement('style'); el.textContent = styles; // Use querySelector instead of document.head to ensure that in // ShadowDOM Polyfill that we have a wrapped head to append to. var h = document.querySelector('head'); // document.write + document.head.appendChild = crazytown // use insertBefore instead for correctness in ShadowDOM Polyfill h.insertBefore(el, h.firstChild); })();
Add link to the repo page
'use strict'; require('es6-promise').polyfill(); require('whatwg-fetch'); const url = require('url'), querystring = require('querystring').parse, githubUrl = require('github-url-from-git'); const registry = 'http://npm-registry.herokuapp.com'; const query = querystring(window.location.search.slice(1)).q; if (query) { window.fetch(url.resolve(registry, query)) .then((response) => { if (response.status >= 400) { document.write(response.status < 500 ? 'Package does not exist' : 'Internal server error'); } else { return response.json(); } }) .then((info) => { if (!info.repository) { return document.write('Package does not have a repository'); } const repo = githubUrl(info.repository.url); document.write(`Redirecting to ${repo}...`); window.location.replace(repo); }); } else { document.write('<form method="get"><input type="text" name="q"><input type="submit" value="Go"></form>' + '<small>Learn more: <a href="https://github.com/npmdocs/www">https://github.com/npmdocs/www</a></small>'); }
'use strict'; require('es6-promise').polyfill(); require('whatwg-fetch'); const url = require('url'), querystring = require('querystring').parse, githubUrl = require('github-url-from-git'); const registry = 'http://npm-registry.herokuapp.com'; const query = querystring(window.location.search.slice(1)).q; if (query) { window.fetch(url.resolve(registry, query)) .then((response) => { if (response.status >= 400) { document.write(response.status < 500 ? 'Package does not exist' : 'Internal server error'); } else { return response.json(); } }) .then((info) => { if (!info.repository) { return document.write('Package does not have a repository'); } const repo = githubUrl(info.repository.url); document.write(`Redirecting to ${repo}...`); window.location.replace(repo); }); } else { document.write('<form method="get"><input type="text" name="q"><input type="submit" value="Go"></form>'); }
Add a link used to clear the purchase date input
<!-- Purchase Date --> <div class="form-group {{ $errors->has('purchase_date') ? ' has-error' : '' }}"> <label for="purchase_date" class="col-md-3 control-label">{{ trans('general.purchase_date') }}</label> <div class="input-group col-md-4"> <div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-autoclose="true"> <input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" readonly value="{{ old('purchase_date', ($item->purchase_date) ? $item->purchase_date->format('Y-m-d') : '') }}" style="background-color:inherit"> <span class="input-group-addon"><i class="fas fa-calendar" aria-hidden="true"></i></span> </div> <a onclick="document.getElementById('purchase_date').value = ''"> Clear </a> {!! $errors->first('purchase_date', '<span class="alert-msg" aria-hidden="true"><i class="fas fa-times" aria-hidden="true"></i> :message</span>') !!} </div> </div>
<!-- Purchase Date --> <div class="form-group {{ $errors->has('purchase_date') ? ' has-error' : '' }}"> <label for="purchase_date" class="col-md-3 control-label">{{ trans('general.purchase_date') }}</label> <div class="input-group col-md-4"> <div class="input-group date" data-provide="datepicker" data-date-format="yyyy-mm-dd" data-autoclose="true"> <input type="text" class="form-control" placeholder="{{ trans('general.select_date') }}" name="purchase_date" id="purchase_date" readonly value="{{ old('purchase_date', ($item->purchase_date) ? $item->purchase_date->format('Y-m-d') : '') }}" style="background-color:inherit"> <span class="input-group-addon"><i class="fas fa-calendar" aria-hidden="true"></i></span> </div> {!! $errors->first('purchase_date', '<span class="alert-msg" aria-hidden="true"><i class="fas fa-times" aria-hidden="true"></i> :message</span>') !!} </div> </div>
Support use real ip and host name for service
#!/usr/bin/python import socket import time from zeroconf import * def main(): service_type = "_ssh._tcp.local." service_port = 22 service_addr = socket.gethostbyname(socket.gethostname()) service_name = socket.gethostname().replace('.local', '.') info = ServiceInfo(service_type, service_name + service_type, socket.inet_aton(service_addr), service_port, 0, 0, "", None) print "Register SSH service %s on %s ..." % (socket.gethostname(), service_addr) zc = Zeroconf() zc.register_service(info) try: while True: time.sleep(1) except KeyboardInterrupt: pass finally: print("Unregistering ...") zc.unregister_service(info) zc.close() if __name__ == '__main__': main()
#!/usr/bin/python import socket import time from zeroconf import * def main(): print "Register SSH service ..." service_type = "_ssh._tcp.local." info = ServiceInfo(service_type, "RPi3." + service_type, socket.inet_aton("127.0.0.1"), 22, 0, 0, "", None) zc = Zeroconf() zc.register_service(info) try: while True: time.sleep(1) except KeyboardInterrupt: pass finally: print("Unregistering ...") zc.unregister_service(info) zc.close() if __name__ == '__main__': main()
Allow tests to be run on 1.4
#!/usr/bin/env python import sys from os.path import dirname, abspath import django from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'django.db.backends.postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'django.db.backends.sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASES=dict(default=dict(ENGINE=db_engine, NAME=db_name)), INSTALLED_APPS = [ 'django.contrib.contenttypes', 'genericm2m', 'genericm2m.genericm2m_tests', ], ) from django.test.utils import get_runner def runtests(*test_args): if not test_args: test_args = ['genericm2m_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(test_args) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'sqlite3' db_name = '' if not settings.configured: settings.configure( DATABASE_ENGINE = db_engine, DATABASE_NAME = db_name, INSTALLED_APPS = [ 'django.contrib.contenttypes', 'genericm2m', 'genericm2m.genericm2m_tests', ], ) from django.test.simple import run_tests def runtests(*test_args): if not test_args: test_args = ['genericm2m_tests'] parent = dirname(abspath(__file__)) sys.path.insert(0, parent) failures = run_tests(test_args, verbosity=1, interactive=True) sys.exit(failures) if __name__ == '__main__': runtests(*sys.argv[1:])
Fix Toggle Files button /2
import {h} from 'dom-chef'; import select from 'select-dom'; import delegate from 'delegate'; import * as icons from '../libs/icons'; import observeEl from '../libs/simplified-element-observer'; function addButton() { const filesHeader = select('.commit-tease .float-right'); if (!filesHeader || select.exists('.rgh-toggle-files')) { return; } filesHeader.append( <button class="btn-octicon p-1 pr-2 rgh-toggle-files" aria-label="Toggle files section" aria-expanded="true"> {icons.chevronDown()} </button> ); } export default function () { const repoContent = select('.repository-content'); observeEl(repoContent, addButton); delegate('.rgh-toggle-files', 'click', ({delegateTarget}) => { delegateTarget.setAttribute('aria-expanded', !repoContent.classList.toggle('rgh-files-hidden')); }); }
import {h} from 'dom-chef'; import select from 'select-dom'; import delegate from 'delegate'; import * as icons from '../libs/icons'; import observeEl from '../libs/simplified-element-observer'; function addButton() { const filesHeader = select('.commit-tease .float-right'); if (!filesHeader) { return; } filesHeader.append( <button class="btn-octicon p-1 pr-2 rgh-toggle-files" aria-label="Toggle files section" aria-expanded="true"> {icons.chevronDown()} </button> ); } export default function () { const repoContent = select('.repository-content'); observeEl(repoContent, addButton); delegate('.rgh-toggle-files', 'click', ({delegateTarget}) => { delegateTarget.setAttribute('aria-expanded', !repoContent.classList.toggle('rgh-files-hidden')); }); }
Add helper for finding files in folder
import logging import os import sys import urllib logger = logging.getLogger('mopidy.utils.path') def get_or_create_folder(folder): folder = os.path.expanduser(folder) if not os.path.isdir(folder): logger.info(u'Creating dir %s', folder) os.mkdir(folder, 0755) return folder def get_or_create_file(filename): filename = os.path.expanduser(filename) if not os.path.isfile(filename): logger.info(u'Creating file %s', filename) open(filename, 'w') return filename def path_to_uri(*paths): path = os.path.join(*paths) #path = os.path.expanduser(path) # FIXME Waiting for test case? path = path.encode('utf-8') if sys.platform == 'win32': return 'file:' + urllib.pathname2url(path) return 'file://' + urllib.pathname2url(path) def find_files(folder): for dirpath, dirnames, filenames in os.walk(folder): for filename in filenames: dirpath = os.path.abspath(dirpath) yield os.path.join(dirpath, filename)
import logging import os import sys import urllib logger = logging.getLogger('mopidy.utils.path') def get_or_create_folder(folder): folder = os.path.expanduser(folder) if not os.path.isdir(folder): logger.info(u'Creating dir %s', folder) os.mkdir(folder, 0755) return folder def get_or_create_file(filename): filename = os.path.expanduser(filename) if not os.path.isfile(filename): logger.info(u'Creating file %s', filename) open(filename, 'w') return filename def path_to_uri(*paths): path = os.path.join(*paths) #path = os.path.expanduser(path) # FIXME Waiting for test case? path = path.encode('utf-8') if sys.platform == 'win32': return 'file:' + urllib.pathname2url(path) return 'file://' + urllib.pathname2url(path)
Use logger rather than raw print
from .. import config import logging logger=logging.getLogger(__name__) import requests from requests.exceptions import * import hashlib, random def run(options): ip = options['ip'] port = options['port'] test = random.choice(config.HTTPS_PAGES) try: r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2) if r.status_code is not 200: logger.debug(r.status_code) return False sha1 = hashlib.sha1() sha1.update(r.content) checksum = sha1.hexdigest() if checksum == test['checksum']: return True except Timeout: logger.debug("Timeout") return False logger.debug("Bad checksum") return False
from .. import config import requests from requests.exceptions import * import hashlib, random def run(options): ip = options['ip'] port = options['port'] test = random.choice(config.HTTPS_PAGES) try: r = requests.get('https://{}:{}/{}'.format(ip, port, test['url']), verify=False, timeout=2) if r.status_code is not 200: print(r.status_code) return False sha1 = hashlib.sha1() sha1.update(r.content) checksum = sha1.hexdigest() if checksum == test['checksum']: return True except Timeout: print("Timeout") return False print("Bad checksum") return False
Remove arrow-body-style. Is too confusing
module.exports = { parserOptions: { ecmaVersion: 2017, sourceType: 'module', ecmaFeatures: { experimentalObjectRestSpread: true } }, rules: { 'arrow-spacing': ['error', { before: true, after: true }], 'no-const-assign': 'error', 'no-duplicate-imports': 'error', 'no-new-symbol': 'error', 'no-this-before-super': 'error', 'no-var': 'error', 'object-shorthand': ['error', 'always', { ignoreConstructors: false, avoidQuotes: true, }], 'prefer-arrow-callback': ['error', { allowNamedFunctions: false, allowUnboundThis: true, }], 'prefer-const': ['error', { destructuring: 'any', ignoreReadBeforeAssign: true, }], 'prefer-rest-params': 'error', // babel inserts `'use strict';` for us 'strict': ['error', 'never'] } };
module.exports = { parserOptions: { ecmaVersion: 2017, sourceType: 'module', ecmaFeatures: { experimentalObjectRestSpread: true } }, rules: { 'arrow-body-style': ['error', 'as-needed', { requireReturnForObjectLiteral: false, }], 'arrow-spacing': ['error', { before: true, after: true }], 'no-const-assign': 'error', 'no-duplicate-imports': 'error', 'no-new-symbol': 'error', 'no-this-before-super': 'error', 'no-var': 'error', 'object-shorthand': ['error', 'always', { ignoreConstructors: false, avoidQuotes: true, }], 'prefer-arrow-callback': ['error', { allowNamedFunctions: false, allowUnboundThis: true, }], 'prefer-const': ['error', { destructuring: 'any', ignoreReadBeforeAssign: true, }], 'prefer-rest-params': 'error', // babel inserts `'use strict';` for us 'strict': ['error', 'never'] } };
Test runtime for template literals
var name, unsupportedFeatures = []; var features = { class: works('class A {}'), arrowFunction: works('() => {}'), let: works('let x'), const: works('const x = 1'), destructuring: works('var {x} = {x:1}'), defaultParamValues: works('function a (a=1) {}'), promises: works('Promise.resolve().then()'), templateLiterals: works('var x=1; `${x}`'), }; function works (code) { try { eval(code); return true; } catch (error) { return false; } } for (name in features) { if (features.hasOwnProperty(name)) { if (! features[name]) { unsupportedFeatures.push(name); } } } if (unsupportedFeatures.length) { throw new Error('Runtime does not support these required EcmaScript features: ' + unsupportedFeatures.join(', ')); }
var name, unsupportedFeatures = []; var features = { class: works('class A {}'), arrowFunction: works('() => {}'), let: works('let x'), const: works('const x = 1'), destructuring: works('var {x} = {x:1}'), defaultParamValues: works('function a (a=1) {}'), promises: works('Promise.resolve().then()'), }; function works (code) { try { eval(code); return true; } catch (error) { return false; } } for (name in features) { if (features.hasOwnProperty(name)) { if (! features[name]) { unsupportedFeatures.push(name); } } } if (unsupportedFeatures.length) { throw new Error('Runtime does not support these required EcmaScript features: ' + unsupportedFeatures.join(', ')); }
Disable order by desc for wallets list
<?php namespace WalletLogger; use Illuminate\Database\Capsule\Manager; class WalletsController extends ItemsController { public function __construct(Manager $db) { $this->db = $db; $this->model = new Wallets($this->db); $this->order_by = 'name'; $this->order_by_desc = false; } public function getTotalAmount($item_id) { $total = 0; $related_accounts = (new Accounts($this->db))->getList(['fk_wallet_id' => $item_id]); foreach ($related_accounts as $account) { $related_transactions = (new Transactions($this->db))->getList(['fk_account_id' => $account->id]); foreach ($related_transactions as $transaction) { $transaction->direction === 'IN' ? $total += $transaction->amount : $total -= $transaction->amount; } } return $total; } }
<?php namespace WalletLogger; use Illuminate\Database\Capsule\Manager; class WalletsController extends ItemsController { public function __construct(Manager $db) { $this->db = $db; $this->model = new Wallets($this->db); $this->order_by = 'name'; } public function getTotalAmount($item_id) { $total = 0; $related_accounts = (new Accounts($this->db))->getList(['fk_wallet_id' => $item_id]); foreach ($related_accounts as $account) { $related_transactions = (new Transactions($this->db))->getList(['fk_account_id' => $account->id]); foreach ($related_transactions as $transaction) { $transaction->direction === 'IN' ? $total += $transaction->amount : $total -= $transaction->amount; } } return $total; } }
Remove override of 'createJSModules' for RN 0.47
package fr.greweb.reactnativeviewshot; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNViewShotPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNViewShotModule(reactContext)); } // Deprecated RN 0.47 // @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
package fr.greweb.reactnativeviewshot; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNViewShotPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNViewShotModule(reactContext)); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
Remove debug line from class
<?php /** * Represents a zone * * @author Edward Rudd <urkle at outoforder.cc> */ class RO_Zone extends RO_Base { protected function configSQL() { return "SELECT * FROM zones WHERE zone_id = ?"; } protected function configCache() { return array('zones','zone_id'); } protected function mobs() { $min_level = empty($this->extra->min_level) ? null : $this->extra->min_level; $max_level = empty($this->extra->max_level) ? null : $this->extra->max_level; $stmt = Database::query("CALL GetAreaMobs(?,?,?)",$this->ID(),$min_level, $max_level); $rows = $stmt->fetchAll(PDO::FETCH_COLUMN); return new ResultIterator($rows,'RO_Mob'); } } ?>
<?php /** * Represents a zone * * @author Edward Rudd <urkle at outoforder.cc> */ class RO_Zone extends RO_Base { protected function configSQL() { return "SELECT * FROM zones WHERE zone_id = ?"; } protected function configCache() { return array('zones','zone_id'); } protected function mobs() { FB::log($this->extra); $min_level = empty($this->extra->min_level) ? null : $this->extra->min_level; $max_level = empty($this->extra->max_level) ? null : $this->extra->max_level; $stmt = Database::query("CALL GetAreaMobs(?,?,?)",$this->ID(),$min_level, $max_level); $rows = $stmt->fetchAll(PDO::FETCH_COLUMN); return new ResultIterator($rows,'RO_Mob'); } } ?>
Correct spelling of downloand to download.
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:8080/my_database'); var Schema = mongoose.Schema; // create a schema var gameInfoSchema = new Schema({ title: { type: String, required: true }, descrption: { type: String }, pictures: [ { type: String } ], videos: [ { type: String } ], link_facebook: { type: String }, link_twitter: { type: String }, link_google_plus: { type: String }, download: { type: String }, version: { type: String }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, admin: Boolean, location: String, created_at: Date, updated_at: Date }); // the schema is useless so far // we need to create a model using it var gameInfo = mongoose.model('gameInfo', gameInfoSchema); // make this available to our users in our Node applications module.exports = gameInfo;
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:8080/my_database'); var Schema = mongoose.Schema; // create a schema var gameInfoSchema = new Schema({ title: { type: String, required: true }, descrption: { type: String }, pictures: [ { type: String } ], videos: [ { type: String } ], link_facebook: { type: String }, link_twitter: { type: String }, link_google_plus: { type: String }, downloand: { type: String }, version: { type: String }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, admin: Boolean, location: String, created_at: Date, updated_at: Date }); // the schema is useless so far // we need to create a model using it var gameInfo = mongoose.model('gameInfo', gameInfoSchema); // make this available to our users in our Node applications module.exports = gameInfo;
Use LOG_LEVEL to enable/disable request logging
#!/usr/bin/env python import logging from flask import Blueprint, current_app, request api_v1_blueprint = Blueprint("api_v1", __name__, url_prefix='/api/v1') log = logging.getLogger('api') @api_v1_blueprint.after_request def log_response(response): """Log any requests/responses with an error code""" if log.getEffectiveLevel() == logging.DEBUG: # pragma: no cover, debugging only log.debug('%7s: %s - %i', request.method, request.url, response.status_code) if response.status_code >= 400: log.debug('Response data: \n%s', response.data) log.debug('Request data: \n%s', request.data) return response # Import the resources to add the routes to the blueprint before the app is # initialized from . import webhook
#!/usr/bin/env python import logging from flask import Blueprint, current_app, request api_v1_blueprint = Blueprint("api_v1", __name__, url_prefix='/api/v1') log = logging.getLogger('api') @api_v1_blueprint.after_request def log_response(response): """Log any requests/responses with an error code""" if current_app.debug: # pragma: no cover, debugging only log.debug('%7s: %s - %i', request.method, request.url, response.status_code) if response.status_code >= 400: log.debug('Response data: \n%s', response.data) log.debug('Request data: \n%s', request.data) return response # Import the resources to add the routes to the blueprint before the app is # initialized from . import webhook
Add encode on global.js file read. node v4.x compat.
var fs = require('fs'); var p = require('path'); var slug = require('slug'); var url = require('url'); var util = require('util'); slug.defaults.mode ='rfc3986'; var env = process.env['FEEDPAPER_ENV']; var feedsCategories = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feeds.json'))); var conf = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feedpaper.json'))); // in lieu of AE86 pre-hook var apiBase = url.format({ protocol: conf.api.protocol, hostname: conf.api.host, pathname: util.format('v%d/%s', conf.api.version, conf.api.path) }); var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js'), 'utf-8'); globalJs = globalJs.replace(/var apiBase = '.*';/, util.format('var apiBase = \'%s\';', apiBase)); exports.params = { slug: function(title, cb) { cb(slug(title)); }, sitemap: { 'index.html': { title: 'Feedpaper' } }, categories: feedsCategories };
var fs = require('fs'); var p = require('path'); var slug = require('slug'); var url = require('url'); var util = require('util'); slug.defaults.mode ='rfc3986'; var env = process.env['FEEDPAPER_ENV']; var feedsCategories = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feeds.json'))); var conf = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feedpaper.json'))); // in lieu of AE86 pre-hook var apiBase = url.format({ protocol: conf.api.protocol, hostname: conf.api.host, pathname: util.format('v%d/%s', conf.api.version, conf.api.path) }); var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js')); globalJs = globalJs.replace(/var apiBase = '.*';/, util.format('var apiBase = \'%s\';', apiBase)); exports.params = { slug: function(title, cb) { cb(slug(title)); }, sitemap: { 'index.html': { title: 'Feedpaper' } }, categories: feedsCategories };
Add missing action parameter for callOnContentRedady
Kwf.onJElementReady('.cssClass .outerYoutubeContainer', function youtubePlayer(el) { var youtubeApiLoaded = false; var animationFinished = false; var imageEl = el.children('.image'); var youtubeContainerEl = el.children('.youtubeContainer'); var youtubePlayerEl = youtubeContainerEl.children('.youtubePlayer'); var loadingEl = youtubeContainerEl.children('.outerLoading'); imageEl.click(function(ev) { Kwf.Utils.YoutubePlayer.load(function() {}); imageEl.fadeOut(300, function() { youtubeContainerEl.css('position', 'relative'); youtubePlayerEl.show(); el.addClass('youtubeActive'); Kwf.callOnContentReady(el.parent(), { action: 'show' }); loadingEl.css('display', 'block'); }); }); });
Kwf.onJElementReady('.cssClass .outerYoutubeContainer', function youtubePlayer(el) { var youtubeApiLoaded = false; var animationFinished = false; var imageEl = el.children('.image'); var youtubeContainerEl = el.children('.youtubeContainer'); var youtubePlayerEl = youtubeContainerEl.children('.youtubePlayer'); var loadingEl = youtubeContainerEl.children('.outerLoading'); imageEl.click(function(ev) { Kwf.Utils.YoutubePlayer.load(function() {}); imageEl.fadeOut(300, function() { youtubeContainerEl.css('position', 'relative'); youtubePlayerEl.show(); el.addClass('youtubeActive'); Kwf.callOnContentReady(el.parent()); loadingEl.css('display', 'block'); }); }); });
Fix trust stores paths for py2exe builds
#!/usr/bin/env python # C:\Python27_32\python.exe setup_py2exe.py py2exe from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores plugin_data_files = [] for file in os.listdir('plugins\\data\\trust_stores'): file = os.path.join('plugins\\data\\trust_stores', file) if os.path.isfile(file): # skip directories plugin_data_files.append( file) data_files.append(('data\\trust_stores', plugin_data_files)) sslyze_setup_py2exe = SSLYZE_SETUP.copy() sslyze_setup_py2exe.update( { 'console' : ['sslyze.py'], 'data_files' : data_files, 'zipfile' : None, 'options' : {'py2exe':{ #'skip_archive': True, 'bundle_files': 1, }} } ) setup(**sslyze_setup_py2exe)
#!/usr/bin/env python # C:\Python27_32\python.exe setup_py2exe.py py2exe from distutils.core import setup from glob import glob import os import py2exe from setup import SSLYZE_SETUP data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))] # Trust Stores plugin_data_path = 'plugins\\data\\trust_stores' plugin_data_files = [] for file in os.listdir(plugin_data_path): file = os.path.join(plugin_data_path, file) if os.path.isfile(file): # skip directories plugin_data_files.append( file) data_files.append((plugin_data_path, plugin_data_files)) sslyze_setup_py2exe = SSLYZE_SETUP.copy() sslyze_setup_py2exe.update( { 'console' : ['sslyze.py'], 'data_files' : data_files, 'zipfile' : None, 'options' : {'py2exe':{ #'skip_archive': True, 'bundle_files': 1, }} } ) setup(**sslyze_setup_py2exe)
Test local version of babel/types
import { createTypeAnnotationBasedOnTypeof } from "../../.."; describe("builders", function() { describe("flow", function() { describe("createTypeAnnotationBasedOnTypeof", function() { const values = { string: typeof "string", number: typeof 123, true: typeof true, object: typeof {}, undefined: typeof undefined, function: typeof function() {}, symbol: typeof Symbol(), }; for (const name in values) { const value = values[name]; it(name, function() { const result = createTypeAnnotationBasedOnTypeof(value); expect(result).toMatchSnapshot(); }); } it("invalid", function() { expect(() => createTypeAnnotationBasedOnTypeof("thisdoesnotexist"), ).toThrow(Error); }); }); }); });
import { createTypeAnnotationBasedOnTypeof } from "@babel/types"; describe("builders", function() { describe("flow", function() { describe("createTypeAnnotationBasedOnTypeof", function() { const values = { string: typeof "string", number: typeof 123, true: typeof true, object: typeof {}, undefined: typeof undefined, function: typeof function() {}, symbol: typeof Symbol(), }; for (const name in values) { const value = values[name]; it(name, function() { const result = createTypeAnnotationBasedOnTypeof(value); expect(result).toMatchSnapshot(); }); } it("invalid", function() { expect(() => createTypeAnnotationBasedOnTypeof("thisdoesnotexist"), ).toThrow(Error); }); }); }); });
Add deleted status to list command
<?php namespace NZTim\Queue\Commands; use Illuminate\Support\Collection; use NZTim\Queue\QueuedJob\QueuedJob; class ListJobs { public function table(Collection $entries) { $jobs = []; foreach ($entries as $entry) { /** @var QueuedJob $entry */ $job['Created'] = $entry->created_at->format('Y-m-d - H:i'); $job['ID'] = "ID:{$entry->getId()}"; $job['Class'] = get_class($entry->getJob()); $job['Status'] = is_null($entry->deleted_at) ? "Incomplete" : "Complete"; $job['Status'] .= " ({$entry->attempts})"; if ($entry->attempts == 0) { $job['Status'] = "Failed!!!"; } $job['Deleted'] = $entry->deleted_at ? "Yes" : ''; $jobs[] = $job; } return $jobs; } }
<?php namespace NZTim\Queue\Commands; use Illuminate\Support\Collection; use NZTim\Queue\QueuedJob\QueuedJob; class ListJobs { public function table(Collection $entries) { $jobs = []; foreach ($entries as $entry) { /** @var QueuedJob $entry */ $job['Created'] = $entry->created_at->format('Y-m-d - H:i'); $job['ID'] = "ID:{$entry->getId()}"; $job['Class'] = get_class($entry->getJob()); $job['Status'] = is_null($entry->deleted_at) ? "Incomplete" : "Complete"; $job['Status'] .= " ({$entry->attempts})"; if ($entry->attempts == 0) { $job['Status'] = "Failed!!!"; } $jobs[] = $job; } return $jobs; } }
Fix occasional crash due to calling rand.Intn(0)
package main import ( "fmt" "github.com/minaguib/berlingo" "math/rand" ) /* This example mimicks the functionality in the berlin-ai demo ruby gem at: https://github.com/thirdside/berlin-ai/ */ type AI1 struct{} func (ai *AI1) GameStart(game *berlingo.Game) { } func (ai *AI1) Turn(game *berlingo.Game) { for _, node := range game.Map.ControlledNodes() { for _, other_node := range node.Paths_Outbound { if node.Available_Soldiers < 1 { continue } soldiers := rand.Intn(node.Available_Soldiers) fmt.Println("Moving", soldiers, "soldiers from node", node.Id, "to node", other_node.Id) if err := game.AddMove(node, other_node, soldiers); err != nil { fmt.Println("Error moving:", err) } } } } func (ai *AI1) GameOver(game *berlingo.Game) { } func (ai *AI1) Ping(game *berlingo.Game) { }
package main import ( "fmt" "github.com/minaguib/berlingo" "math/rand" ) /* This example mimicks the functionality in the berlin-ai demo ruby gem at: https://github.com/thirdside/berlin-ai/ */ type AI1 struct{} func (ai *AI1) GameStart(game *berlingo.Game) { } func (ai *AI1) Turn(game *berlingo.Game) { for _, node := range game.Map.ControlledNodes() { for _, other_node := range node.Paths_Outbound { soldiers := rand.Intn(node.Available_Soldiers) fmt.Println("Moving", soldiers, "soldiers from node", node.Id, "to node", other_node.Id) if err := game.AddMove(node, other_node, soldiers); err != nil { fmt.Println("Error moving:", err) } } } } func (ai *AI1) GameOver(game *berlingo.Game) { } func (ai *AI1) Ping(game *berlingo.Game) { }
Add Genymotion to isEmulator() method
package com.smartdevicelink.test.util; import android.os.Build; public class DeviceUtil { public static boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for") || Build.MANUFACTURER.contains("Genymotion") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic")) || (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone")) || "google_sdk".equals(Build.PRODUCT); } }
package com.smartdevicelink.test.util; import android.os.Build; public class DeviceUtil { public static boolean isEmulator() { return Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for") || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")) || (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic")) || (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone")) || "google_sdk".equals(Build.PRODUCT); } }
Revert "Fix 'start chat' button" This reverts commit c841eb641b85995bddb235d3db2c779daffe97a1.
/* Copyright 2017 Vector Creations 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. */ import React from 'react'; import sdk from '../../../index'; import PropTypes from 'prop-types'; const StartChatButton = function(props) { const ActionButton = sdk.getComponent('elements.ActionButton'); return ( <ActionButton action="start_chat" label="Start chat" iconPath="img/icons-people.svg" size={props.size} tooltip={props.tooltip} /> ); }; StartChatButton.propTypes = { size: PropTypes.string, tooltip: PropTypes.bool, }; export default StartChatButton;
/* Copyright 2017 Vector Creations 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. */ import React from 'react'; import sdk from '../../../index'; import PropTypes from 'prop-types'; const StartChatButton = function(props) { const ActionButton = sdk.getComponent('elements.ActionButton'); return ( <ActionButton action="view_create_chat" label="Start chat" iconPath="img/icons-people.svg" size={props.size} tooltip={props.tooltip} /> ); }; StartChatButton.propTypes = { size: PropTypes.string, tooltip: PropTypes.bool, }; export default StartChatButton;
Remove useless babel-polyfill import in tests
import formatter from "../src/formatter"; describe("formatter", function() { beforeEach(function() { this.n1qlFormatter = { format: (query) => query + " (formatted as N1QL)" }; this.standardSqlFormatter = { format: (query) => query + " (formatted as standard SQL)" }; formatter.__set__({ n1qlFormatter: this.n1qlFormatter, standardSqlFormatter: this.standardSqlFormatter }); }); it("formats N1QL query", function() { const result = formatter.format("n1ql", "SELECT *"); expect(result).toBe("SELECT * (formatted as N1QL)"); }); it("formats standard SQL query", function() { const result = formatter.format("sql", "SELECT *"); expect(result).toBe("SELECT * (formatted as standard SQL)"); }); it("throws error on other language queries", function() { expect(() => formatter.format("hql", "SELECT *")).toThrow("Unsupported language"); }); });
import "babel-polyfill"; import formatter from "../src/formatter"; describe("formatter", function() { beforeEach(function() { this.n1qlFormatter = { format: (query) => query + " (formatted as N1QL)" }; this.standardSqlFormatter = { format: (query) => query + " (formatted as standard SQL)" }; formatter.__set__({ n1qlFormatter: this.n1qlFormatter, standardSqlFormatter: this.standardSqlFormatter }); }); it("formats N1QL query", function() { const result = formatter.format("n1ql", "SELECT *"); expect(result).toBe("SELECT * (formatted as N1QL)"); }); it("formats standard SQL query", function() { const result = formatter.format("sql", "SELECT *"); expect(result).toBe("SELECT * (formatted as standard SQL)"); }); it("throws error on other language queries", function() { expect(() => formatter.format("hql", "SELECT *")).toThrow("Unsupported language"); }); });
Add documentation field and parameter validation
package pete.metrics.adaptability; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class AdaptableElement { private final String name; private final List<String> adaptions; private String documentation; private String locatorExpression = "//*[local-name() = 'definitions']"; public AdaptableElement(String name) { if (name == null) { throw new IllegalArgumentException("name must not be null"); } this.name = name; adaptions = new ArrayList<>(); documentation = ""; } public void addAdaption(String adaption) { if (adaption != null) { adaptions.add(adaption); } } public List<String> getAdaptions() { return Collections.unmodifiableList(adaptions); } public int getNumberOfAdaptions() { return adaptions.size(); } public String getName() { return name; } public int getAdaptabilityScore() { return adaptions.size(); } public String getLocatorExpression() { return locatorExpression; } public void setLocatorExpression(String locatorExpression) { if (!(locatorExpression == null)) { this.locatorExpression += locatorExpression; } } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { if (documentation == null) { this.documentation = ""; } else { this.documentation = documentation; } } }
package pete.metrics.adaptability; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class AdaptableElement { private final String name; private final List<String> adaptions; private String locatorExpression = "//*[local-name() = 'definitions']"; public AdaptableElement(String name) { this.name = name; adaptions = new ArrayList<>(); } public void addAdaption(String adaption) { adaptions.add(adaption); } public List<String> getAdaptions() { return Collections.unmodifiableList(adaptions); } public int getNumberOfAdaptions() { return adaptions.size(); } public String getName() { return name; } public int getAdaptabilityScore() { return adaptions.size(); } public String getLocatorExpression() { return locatorExpression; } public void setLocatorExpression(String locatorExpression) { this.locatorExpression += locatorExpression; } }
Use no_async api by default in FailAction
from bot.action.core.action import Action from bot.action.util.textformat import FormattedText class FailAction(Action): def process(self, event): api = self.api.no_async error = NotARealError("simulated error") response = FormattedText().bold("Simulating bot error...") args = event.command_args.split() if "fatal" in args: error = NotARealFatalError("simulated fatal error") response.newline().normal(" - ").bold("FATAL") if "async" in args: api = self.api.async response.newline().normal(" - ").bold("async") api.send_message(response.build_message().to_chat_replying(event.message)) raise error class NotARealError(Exception): pass class NotARealFatalError(BaseException): pass
from bot.action.core.action import Action from bot.action.util.textformat import FormattedText class FailAction(Action): def process(self, event): api = self.api error = NotARealError("simulated error") response = FormattedText().bold("Simulating bot error...") args = event.command_args.split() if "fatal" in args: error = NotARealFatalError("simulated fatal error") response.newline().normal(" - ").bold("FATAL") if "async" in args: api = self.api.async response.newline().normal(" - ").bold("async") api.send_message(response.build_message().to_chat_replying(event.message)) raise error class NotARealError(Exception): pass class NotARealFatalError(BaseException): pass
Fix runner config default port
'use struct'; var ConsoleAuditStream = require('../audit/console_audit_stream'); function ImplementationRunnerConfig() { this._port = 61616; this._requestTimeoutMillis = 500; this._auditStream = new ConsoleAuditStream(); } ImplementationRunnerConfig.prototype.setHostname = function(hostname) { this._hostname = hostname; return this; } ImplementationRunnerConfig.prototype.setPort = function(port) { this._port = port; return this; } ImplementationRunnerConfig.prototype.setUniqueId = function(uniqueId) { this._uniqueId = uniqueId; return this; } ImplementationRunnerConfig.prototype.setTimeToWaitForRequest = function(timeToWaitForRequest) { this._requestTimeoutMillis = timeToWaitForRequest; return this; } ImplementationRunnerConfig.prototype.setAuditStream = function(auditStream) { this._auditStream = auditStream; return this; } ImplementationRunnerConfig.prototype.getHostName = function() { return this._hostname; } ImplementationRunnerConfig.prototype.getPort = function() { return this._port; } ImplementationRunnerConfig.prototype.getUniqueId = function() { return this._uniqueId; } ImplementationRunnerConfig.prototype.getTimeToWaitForRequest = function() { return this._requestTimeoutMillis; } ImplementationRunnerConfig.prototype.getAuditStream = function() { return this._auditStream; } module.exports = ImplementationRunnerConfig;
'use struct'; var ConsoleAuditStream = require('../audit/console_audit_stream'); function ImplementationRunnerConfig() { this._hostname = 61616; this._requestTimeoutMillis = 500; this._auditStream = new ConsoleAuditStream(); } ImplementationRunnerConfig.prototype.setHostname = function(hostname) { this._hostname = hostname; return this; } ImplementationRunnerConfig.prototype.setPort = function(port) { this._port = port; return this; } ImplementationRunnerConfig.prototype.setUniqueId = function(uniqueId) { this._uniqueId = uniqueId; return this; } ImplementationRunnerConfig.prototype.setTimeToWaitForRequest = function(timeToWaitForRequest) { this._requestTimeoutMillis = timeToWaitForRequest; return this; } ImplementationRunnerConfig.prototype.setAuditStream = function(auditStream) { this._auditStream = auditStream; return this; } ImplementationRunnerConfig.prototype.getHostName = function() { return this._hostname; } ImplementationRunnerConfig.prototype.getPort = function() { return this._port; } ImplementationRunnerConfig.prototype.getUniqueId = function() { return this._uniqueId; } ImplementationRunnerConfig.prototype.getTimeToWaitForRequest = function() { return this._requestTimeoutMillis; } ImplementationRunnerConfig.prototype.getAuditStream = function() { return this._auditStream; } module.exports = ImplementationRunnerConfig;
Use regular expression for target types
'use strict'; var _ = require('lodash'); var commander = require('commander'); var path = require('path'); var Queue = require('gear').Queue; var registry = require('./tasks'); var build, hasTarget, target, targets = ['browser', 'cdn', 'node']; commander .usage('[options] [<languages ...>]') .option('-n, --no-compress', 'Disable compression') .option('-t, --target <name>', 'Build for target [browser, cdn, node]', /^(browser|cdn|node$)/i, 'browser') .parse(process.argv); hasTarget = _.contains(targets, commander.target); target = './' + (hasTarget ? commander.target : 'browser'); build = require(target); global.dir = {}; global.dir.root = path.dirname(__dirname); global.dir.build = path.join(dir.root, 'build'); new Queue({ registry: registry }) .clean(dir.build) .log('Starting build.') .tasks(build(commander)) .log('Finished build.') .run();
'use strict'; var _ = require('lodash'); var commander = require('commander'); var path = require('path'); var Queue = require('gear').Queue; var registry = require('./tasks'); var build, hasTarget, target, targets = ['browser', 'cdn', 'node']; commander .usage('[options] [<languages ...>]') .option('-n, --no-compress', 'Disable compression') .option('-t, --target <name>', 'Build for target <name> ' + '[browser, cdn, node]', 'browser') .parse(process.argv); hasTarget = _.contains(targets, commander.target); target = './' + (hasTarget ? commander.target : 'browser'); build = require(target); global.dir = {}; global.dir.root = path.dirname(__dirname); global.dir.build = path.join(dir.root, 'build'); new Queue({ registry: registry }) .clean(dir.build) .log('Starting build.') .tasks(build(commander)) .log('Finished build.') .run();
Remove extra `%` from the `cli` tools.
# -*- coding: utf-8 -*- """ salt.utils.parser ~~~~~~~~~~~~~~~~~ :copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)` :license: Apache 2.0, see LICENSE for more details. """ import sys import optparse from salt import version class OptionParser(optparse.OptionParser): def __init__(self, *args, **kwargs): kwargs.setdefault("version", version.__version__) kwargs.setdefault('usage', '%prog') optparse.OptionParser.__init__(self, *args, **kwargs) def parse_args(self, args=None, values=None): options, args = optparse.OptionParser.parse_args(self, args, values) if options.versions_report: self.print_versions_report() return options, args def _add_version_option(self): optparse.OptionParser._add_version_option(self) self.add_option( '--versions-report', action='store_true', help="show program's dependencies version number and exit" ) def print_versions_report(self, file=sys.stdout): print >> file, '\n'.join(version.versions_report()) self.exit()
# -*- coding: utf-8 -*- """ salt.utils.parser ~~~~~~~~~~~~~~~~~ :copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)` :license: Apache 2.0, see LICENSE for more details. """ import sys import optparse from salt import version class OptionParser(optparse.OptionParser): def __init__(self, *args, **kwargs): kwargs.setdefault("version", version.__version__) kwargs.setdefault('usage', '%%prog') optparse.OptionParser.__init__(self, *args, **kwargs) def parse_args(self, args=None, values=None): options, args = optparse.OptionParser.parse_args(self, args, values) if options.versions_report: self.print_versions_report() return options, args def _add_version_option(self): optparse.OptionParser._add_version_option(self) self.add_option( '--versions-report', action='store_true', help="show program's dependencies version number and exit" ) def print_versions_report(self, file=sys.stdout): print >> file, '\n'.join(version.versions_report()) self.exit()
Check for ioflo-flavored OrderedDicts as well when outputting YAML
# -*- coding: utf-8 -*- ''' salt.utils.yamldumper ~~~~~~~~~~~~~~~~~~~~~ ''' # pylint: disable=W0232 # class has no __init__ method from __future__ import absolute_import try: from yaml import CDumper as Dumper from yaml import CSafeDumper as SafeDumper except ImportError: from yaml import Dumper from yaml import SafeDumper from salt.utils.odict import OrderedDict try: from ioflo.base.odicting import odict HAS_IOFLO = True except ImportError: odict = None HAS_IOFLO = False class OrderedDumper(Dumper): ''' A YAML dumper that represents python OrderedDict as simple YAML map. ''' class SafeOrderedDumper(SafeDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map. ''' def represent_ordereddict(dumper, data): return dumper.represent_dict(data.items()) OrderedDumper.add_representer(OrderedDict, represent_ordereddict) SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict) if HAS_IOFLO: OrderedDumper.add_representer(odict, represent_ordereddict) SafeOrderedDumper.add_representer(odict, represent_ordereddict)
# -*- coding: utf-8 -*- ''' salt.utils.yamldumper ~~~~~~~~~~~~~~~~~~~~~ ''' # pylint: disable=W0232 # class has no __init__ method from __future__ import absolute_import try: from yaml import CDumper as Dumper from yaml import CSafeDumper as SafeDumper except ImportError: from yaml import Dumper from yaml import SafeDumper from salt.utils.odict import OrderedDict class OrderedDumper(Dumper): ''' A YAML dumper that represents python OrderedDict as simple YAML map. ''' class SafeOrderedDumper(SafeDumper): ''' A YAML safe dumper that represents python OrderedDict as simple YAML map. ''' def represent_ordereddict(dumper, data): return dumper.represent_dict(data.items()) OrderedDumper.add_representer(OrderedDict, represent_ordereddict) SafeOrderedDumper.add_representer(OrderedDict, represent_ordereddict)
[application] Add the left bar in the clear cartrige.
var dispatcher = require('../dispatcher'); var Empty = React.createClass({ render: function() { return <div></div>; } }); module.exports = { render: require('./render'), builtInStore: require('./built-in-store'), actionBuilder: require('./action-builder'), clear: require('./clear'), mountedComponents: require('./mounted-components'), changeMode(newMode, previousMode){ var mode = {newMode: newMode, previousMode: previousMode}; dispatcher.handleViewAction({data: {mode: mode}, type: 'update'}); }, changeRoute(newRoute){ dispatcher.handleViewAction({data: {route: newRoute}, type: 'update'}); }, clearCartridge(){ dispatcher.handleViewAction({ data: { cartridgeComponent: {component: Empty}, barContentLeftComponent: {component: Empty}, summaryComponent: {component: Empty}, actions: {primary: [], secondary: []} }, type: 'update' }); } };
var dispatcher = require('../dispatcher'); var Empty = React.createClass({ render: function() { return <div></div>; } }); module.exports = { render: require('./render'), builtInStore: require('./built-in-store'), actionBuilder: require('./action-builder'), clear: require('./clear'), mountedComponents: require('./mounted-components'), changeMode(newMode, previousMode){ var mode = {newMode: newMode, previousMode: previousMode}; dispatcher.handleViewAction({data: {mode: mode}, type: 'update'}); }, changeRoute(newRoute){ dispatcher.handleViewAction({data: {route: newRoute}, type: 'update'}); }, clearCartridge(){ dispatcher.handleViewAction({ data: { cartridgeComponent: {component: Empty}, summaryComponent: {component: Empty}, actions: {primary: [], secondary: []} }, type: 'update' }); } };
Handle ECONNRESET errors gracefully as well
const Eris = require("eris"); const config = require("./cfg"); const intents = [ // PRIVILEGED INTENTS "guildMembers", // For server greetings // REGULAR INTENTS "directMessages", // For core functionality "guildMessages", // For bot commands and mentions "guilds", // For core functionality "guildVoiceStates", // For member information in the thread header "guildMessageTyping", // For typing indicators "directMessageTyping", // For typing indicators // EXTRA INTENTS (from the config) ...config.extraIntents, ]; const bot = new Eris.Client(config.token, { restMode: true, intents: Array.from(new Set(intents)), allowedMentions: { everyone: false, roles: false, users: false, }, }); bot.on("error", err => { if (err.code === 1006 || err.code === "ECONNRESET") { // 1006 = "Connection reset by peer" // ECONNRESET is similar // Eris allegedly handles these internally, so we can ignore them return; } throw err; }); /** * @type {Eris.Client} */ module.exports = bot;
const Eris = require("eris"); const config = require("./cfg"); const intents = [ // PRIVILEGED INTENTS "guildMembers", // For server greetings // REGULAR INTENTS "directMessages", // For core functionality "guildMessages", // For bot commands and mentions "guilds", // For core functionality "guildVoiceStates", // For member information in the thread header "guildMessageTyping", // For typing indicators "directMessageTyping", // For typing indicators // EXTRA INTENTS (from the config) ...config.extraIntents, ]; const bot = new Eris.Client(config.token, { restMode: true, intents: Array.from(new Set(intents)), allowedMentions: { everyone: false, roles: false, users: false, }, }); bot.on("error", err => { if (err.code === 1006) { // 1006 = "Connection reset by peer" // Eris allegedly handles this internally, so we can ignore it return; } throw err; }); /** * @type {Eris.Client} */ module.exports = bot;
Exit when using the default npm registry
var opener = require('opener'); var http = require('http'); var fs = require('fs'); var url = require('url'); var exec = require('child_process').execSync; var registry = exec('npm config get registry').toString().trim() if (registry.indexOf('registry.npmjs.org') > -1) { console.log('It seems you are using the default npm repository.'); console.log('Please update it to your sinopia url by running:'); console.log(''); console.log('npm config set registry <url>'); process.exit(0); } opener(registry + 'oauth/authorize'); fs.readFile('./index.html', function(err, html) { if (err) { throw err; } http.createServer(function(req, res) { var query = url.parse(req.url, true).query; var token = decodeURIComponent(query.token); var u = url.parse(registry); var keyBase = '//' + u.host + u.path + ':' exec('npm config set ' + keyBase + '_authToken "' + token + '"'); exec('npm config set ' + keyBase + 'always-auth true'); res.writeHeader(200, {"Content-Type": "text/html"}); res.end(html, function() { process.exit(0); }); }).listen(8239); })
var opener = require('opener'); var http = require('http'); var fs = require('fs'); var url = require('url'); var exec = require('child_process').execSync; var registry = exec('npm config get registry').toString().trim() opener(registry + 'oauth/authorize'); fs.readFile('./index.html', function(err, html) { if (err) { throw err; } http.createServer(function(req, res) { var query = url.parse(req.url, true).query; var token = decodeURIComponent(query.token); var u = url.parse(registry); var keyBase = '//' + u.host + u.path + ':' exec('npm config set ' + keyBase + '_authToken "' + token + '"'); exec('npm config set ' + keyBase + 'always-auth true'); res.writeHeader(200, {"Content-Type": "text/html"}); res.end(html, function() { process.exit(0); }); }).listen(8239); })
Add credentials module to core list
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments from .dashboard import DashboardView from .user import User, UserDashboardView from .serviceclass import ServiceClass from .slice import Slice, SliceDeployments from .site import SitePrivilege, SiteDeployments from .userdeployments import UserDeployments from .image import Image, ImageDeployments from .node import Node from .serviceresource import ServiceResource from .slice import SliceRole from .slice import SlicePrivilege from .credential import UserCredential,SiteCredential,SliceCredential from .site import SiteRole from .site import SitePrivilege from .planetstack import PlanetStackRole from .planetstack import PlanetStackPrivilege from .slicetag import SliceTag from .flavor import Flavor from .sliver import Sliver from .reservation import ReservedResource from .reservation import Reservation from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments from .billing import Account, Invoice, Charge, UsableObject, Payment
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPrivilege, SiteDeployments from .dashboard import DashboardView from .user import User, UserDashboardView from .serviceclass import ServiceClass from .slice import Slice, SliceDeployments from .site import SitePrivilege, SiteDeployments from .userdeployments import UserDeployments from .image import Image, ImageDeployments from .node import Node from .serviceresource import ServiceResource from .slice import SliceRole from .slice import SlicePrivilege from .site import SiteRole from .site import SitePrivilege from .planetstack import PlanetStackRole from .planetstack import PlanetStackPrivilege from .slicetag import SliceTag from .flavor import Flavor from .sliver import Sliver from .reservation import ReservedResource from .reservation import Reservation from .network import Network, NetworkParameterType, NetworkParameter, NetworkSliver, NetworkTemplate, Router, NetworkSlice, NetworkDeployments from .billing import Account, Invoice, Charge, UsableObject, Payment
Convert from share() to singleton() Replace the share() methods for the new singleton() ones.
<?php namespace Barryvdh\Omnipay; use Omnipay\Common\GatewayFactory; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $configPath = __DIR__ . '/../config/omnipay.php'; $this->publishes([$configPath => config_path('omnipay.php')]); $this->app['omnipay'] = $this->app->singleton('omnipay',function ($app){ $defaults = $app['config']->get('omnipay.defaults', array()); return new GatewayManager($app, new GatewayFactory, $defaults); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('omnipay'); } }
<?php namespace Barryvdh\Omnipay; use Omnipay\Common\GatewayFactory; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Register the service provider. * * @return void */ public function register() { $configPath = __DIR__ . '/../config/omnipay.php'; $this->publishes([$configPath => config_path('omnipay.php')]); $this->app['omnipay'] = $this->app->share(function ($app){ $defaults = $app['config']->get('omnipay.defaults', array()); return new GatewayManager($app, new GatewayFactory, $defaults); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('omnipay'); } }
Adjust tests for python-monascaclient >= 1.3.0 the exceptions module was moved out of the openstack.common namespace, so try to import the new location first and fall back to the old one if it doesn't exist. Change-Id: I3305775baaab15dca8d5e7e5cfc0932f94d4d153
# # 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. # NOTE(dmllr): Remove me when we require monascaclient >= 1.3.0 try: from monascaclient.apiclient import exceptions as monascacli except ImportError: from monascaclient.openstack.common.apiclient import exceptions as monascacli from openstack_dashboard.test.test_data import exceptions def data(TEST): TEST.exceptions = exceptions.data monitoring_exception = monascacli.ClientException TEST.exceptions.monitoring = exceptions.create_stubbed_exception( monitoring_exception)
# # 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. from monascaclient.openstack.common.apiclient import exceptions as monascacli from openstack_dashboard.test.test_data import exceptions def data(TEST): TEST.exceptions = exceptions.data monitoring_exception = monascacli.ClientException TEST.exceptions.monitoring = exceptions.create_stubbed_exception( monitoring_exception)
Add space between comment summary and @see
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE).then(res => setData(res.json())); }, []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; import {Wrapper} from "./Wrapper"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { const SOURCE = '/data'; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE).then(res => setData(res.json())); }, []); return ( <Wrapper> {data.map(snapshotData => <BuildSnapshot data={snapshotData}/>)} </Wrapper> ); } );
Fix init for startup with no predefined connections
import React, { useEffect } from 'react'; import { Redirect } from 'react-router-dom'; import { connect } from 'unistore/react'; import initApp from './stores/initApp'; import useAppContext from './utilities/use-app-context'; import useSWR from 'swr'; function Authenticated({ children, initApp, initialized }) { const { config, currentUser } = useAppContext(); let { data: connections } = useSWR('/api/connections'); useEffect(() => { if (config && !initialized && connections) { initApp(config, connections); } }, [initApp, config, connections, initialized]); if (!config) { return null; } if (config && !currentUser) { return <Redirect to={{ pathname: '/signin' }} />; } if (!initialized) { return null; } return children; } export default connect(['initialized'], { initApp, })(Authenticated);
import React, { useEffect } from 'react'; import { Redirect } from 'react-router-dom'; import { connect } from 'unistore/react'; import initApp from './stores/initApp'; import useAppContext from './utilities/use-app-context'; import useSWR from 'swr'; function Authenticated({ children, initApp, initialized }) { const { config, currentUser } = useAppContext(); let { data: connectionsData } = useSWR('/api/connections'); const connections = connectionsData || []; useEffect(() => { if (config && !initialized && connections.length > 0) { initApp(config, connections); } }, [initApp, config, connections, initialized]); if (!config) { return null; } if (config && !currentUser) { return <Redirect to={{ pathname: '/signin' }} />; } if (!initialized) { return null; } return children; } export default connect(['initialized'], { initApp, })(Authenticated);
Add isOneOfFieldSet method to Northstar service
'use strict'; const NorthstarClient = require('@dosomething/northstar-js'); /** * Nortstar client service. */ module.exports = { getClient() { if (!this.client) { this.client = new NorthstarClient({ baseURI: sails.config.northstar.apiBaseURI, apiKey: sails.config.northstar.apiKey, }); } return this.client; }, getUserFor(model) { const options = this.resolveRequestId(model); return this.getClient().getUser(options.type, options.id); }, resolveRequestId(model) { let id; let type; if (model.user_id) { type = 'id'; id = model.user_id; } else if (model.email) { type = 'email'; id = model.email; } else if (model.mobile) { type = 'mobile'; id = model.mobile; } return { type, id }; }, isOneOfFieldSet(submission) { return ['user_id', 'email', 'mobile'].every(userField => !submission[userField]); } };
'use strict'; const NorthstarClient = require('@dosomething/northstar-js'); /** * Nortstar client service. */ module.exports = { getClient() { if (!this.client) { this.client = new NorthstarClient({ baseURI: sails.config.northstar.apiBaseURI, apiKey: sails.config.northstar.apiKey, }); } return this.client; }, getUserFor(model) { const options = this.resolveRequestId(model); return this.getClient().getUser(options.type, options.id); }, resolveRequestId(model) { let id; let type; if (model.user_id) { type = 'id'; id = model.user_id; } else if (model.email) { type = 'email'; id = model.email; } else if (model.mobile) { type = 'mobile'; id = model.mobile; } return { type, id }; }, };
Remove hack is was breaking the tests
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { Meteor.flush() describe('The Route "/"', function () { it('Should have the title "Map"', function () { var title = document.title chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a location', function () { var title = $('li.place .place__location').text() chai.assert.ok(title.length > 0) }) }) }) }
if (!(typeof MochaWeb === 'undefined')){ MochaWeb.testOnly(function () { setTimeout(function (){ describe('The Route "/"', function () { it('Should have the title "Map"', function () { var title = document.title console.log(title) chai.assert.include(title, 'Map') }) }) describe('A list of places', function () { it('Should have a main section with the class map', function () { var map = $('main.map') chai.assert.ok(map.length > 0) }) it('Should contain map__places', function () { var placesList = $('main.map ul.map__places') chai.assert.ok(placesList.length > 0) }) it('should at least contain one place', function () { var places = $('ul.map__places li.place') chai.assert.ok(places.length > 0) }) }) describe('A place', function () { it('Should include a location', function () { var title = $('li.place .place__location').text() chai.assert.ok(title.length > 0) }) }) }, 1000) }) }
Fix task not complete error
const childProcess = require('child_process'); const path = require('path'); const setup = require('setup/setup'); function exec(command) { const run = childProcess.exec; return new Promise((resolve, reject) => { run(command, (error, stdout, stderr) => { if (error) { return reject(stderr); } return resolve(stdout); }); }); } module.exports = function(taskDone) { const assets = setup.assets; const execOpts = setup.plugins.exec; const vendorDir = path.join(assets.build, setup.root, assets.vendor); const cmd = 'composer'; const cmdConfig = [cmd, 'config', 'vendor-dir', vendorDir].join(' '); const cmdInstall = [cmd, 'install'] .concat(setup.isOnline ? ['--no-dev', '-o'] : ['--dev']).join(' '); const cmdUnset = [cmd, 'config', '--unset', 'vendor-dir'].join(' '); exec(cmdConfig, execOpts) .then(() => exec(cmdInstall, execOpts)) .then(() => exec(cmdUnset, execOpts)) .then(taskDone) .catch(taskDone); };
const childProcess = require('child_process'); const path = require('path'); const setup = require('setup/setup'); function exec(command) { const run = childProcess.exec; return new Promise((resolve, reject) => { run(command, (error, stdout, stderr) => { if (error) { return reject(stderr); } return resolve(stdout); }); }); } module.exports = function(taskDone) { const assets = setup.assets; const execOpts = setup.plugins.exec; const vendorDir = path.join(assets.build, setup.root, assets.vendor); const cmd = 'composer'; const cmdConfig = [cmd, 'config', 'vendor-dir', vendorDir].join(' '); const cmdInstall = [cmd, 'install'] .concat(setup.isOnline ? ['--no-dev', '-o'] : ['--dev']).join(' '); const cmdUnset = [cmd, 'config', '--unset', 'vendor-dir'].join(' '); exec(cmdConfig, execOpts) .then(() => exec(cmdInstall, execOpts)) .then(() => exec(cmdUnset, execOpts)) .catch(taskDone); };
Expand IRC numerics to name list
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "002": "RPL_YOURHOST", "003": "RPL_CREATED", "004": "RPL_MYINFO", "005": "RPL_ISUPPORT", "251": "RPL_LUSERCLIENT", "252": "RPL_LUSEROP", "253": "RPL_LUSERUNKNOWN", "254": "RPL_LUSERCHANNELS", "255": "RPL_LUSERME", "265": "RPL_LOCALUSERS", "266": "RPL_GLOBALUSERS", "315": "RPL_ENDOFWHO", "332": "RPL_TOPIC", "333": "RPL_TOPICWHOTIME", "352": "RPL_WHOREPLY", "353": "RPL_NAMREPLY", "366": "RPL_ENDOFNAMES", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
CTCP_DELIMITER = chr(1) MAX_MESSAGE_LENGTH = 450 #Officially 512 including the newline characters, but let's be on the safe side CHANNEL_PREFIXES = "#&!+.~" #All the characters that could possibly indicate something is a channel name (usually just '#' though) #Since a grey separator is often used to separate parts of a message, provide an easy way to get one GREY_SEPARATOR = u' \x0314|\x0f ' #'\x03' is the 'color' control char, 14 is grey, and '\x0f' is the 'reset' character ending any decoration IRC_NUMERIC_TO_NAME = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "412": "ERR_NOTEXTTOSEND", "433": "ERR_NICKNAMEINUSE"}
Remove packages. tables not needed anymore, numpy installed with pandas
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'])
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['numpy <= 1.15.4', # remove after PyTables release 3.4.5 'pandas >= 0.19.1', 'requests', 'tables']) # PyTables needed for pandas.HDFStore
Remove dependencies to API from tools (ant, maven, javaflow agent, cdi agent)
/** * Copyright 2013-2017 Valery Silaev (http://vsilaev.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.javaflow.instrumentation.cdi; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; class AroundWeldProxyInvocationAdvice extends AroundCdiProxyInvocationAdvice { protected AroundWeldProxyInvocationAdvice(int api, MethodVisitor mv, int acc, String className, String methodName, String desc) { super(api, mv, acc, className, methodName, desc); } @Override protected void loadProxiedInstance() { loadThis(); invokeVirtual(Type.getType(className), GET_TARGET_INSTANCE); } private static final Method GET_TARGET_INSTANCE = Method.getMethod("java.lang.Object getTargetInstance()"); }
/** * Copyright 2013-2017 Valery Silaev (http://vsilaev.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.javaflow.instrumentation.cdi; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.commons.Method; class AroundWeldProxyInvocationAdvice extends AroundCdiProxyInvocationAdvice { protected AroundWeldProxyInvocationAdvice(int api, MethodVisitor mv, int acc, String className, String methodName, String desc) { super(api, mv, acc, className, methodName, desc); } @Override protected void loadProxiedInstance() { loadThis(); invokeVirtual(Type.getType(className), Method.getMethod("Object getTargetInstance()")); } }
Remove Signal(providing_args) argument b/c it is deprecated RemovedInDjango40Warning: The providing_args argument is deprecated. As it is purely documentational, it has no replacement. If you rely on this argument as documentation, you can move the text to a code comment or docstring.
""" Signals relating to comments. """ from django.dispatch import Signal # Sent just before a comment will be posted (after it's been approved and # moderated; this can be used to modify the comment (in place) with posting # details or other such actions. If any receiver returns False the comment will be # discarded and a 400 response. This signal is sent at more or less # the same time (just before, actually) as the Comment object's pre-save signal, # except that the HTTP request is sent along with this signal. # Arguments: "comment", "request" comment_will_be_posted = Signal() # Sent just after a comment was posted. See above for how this differs # from the Comment object's post-save signal. # Arguments: "comment", "request" comment_was_posted = Signal() # Sent after a comment was "flagged" in some way. Check the flag to see if this # was a user requesting removal of a comment, a moderator approving/removing a # comment, or some other custom user flag. # Arguments: "comment", "flag", "created", "request" comment_was_flagged = Signal()
""" Signals relating to comments. """ from django.dispatch import Signal # Sent just before a comment will be posted (after it's been approved and # moderated; this can be used to modify the comment (in place) with posting # details or other such actions. If any receiver returns False the comment will be # discarded and a 400 response. This signal is sent at more or less # the same time (just before, actually) as the Comment object's pre-save signal, # except that the HTTP request is sent along with this signal. comment_will_be_posted = Signal(providing_args=["comment", "request"]) # Sent just after a comment was posted. See above for how this differs # from the Comment object's post-save signal. comment_was_posted = Signal(providing_args=["comment", "request"]) # Sent after a comment was "flagged" in some way. Check the flag to see if this # was a user requesting removal of a comment, a moderator approving/removing a # comment, or some other custom user flag. comment_was_flagged = Signal(providing_args=["comment", "flag", "created", "request"])
Fix incorrect doc comment for NewDocument
package workspace import "path/filepath" // Document is a file in a directory. type Document struct { Root string RelativePath string } // NewDocument creates a document from the filepath. // The root is typically the root of the exercise, and // path is the absolute path to the file. func NewDocument(root, path string) (Document, error) { path, err := filepath.Rel(root, path) if err != nil { return Document{}, err } return Document{ Root: root, RelativePath: path, }, nil } // Filepath is the absolute path to the document on the filesystem. func (doc Document) Filepath() string { return filepath.Join(doc.Root, doc.RelativePath) } // Path is the normalized path. // It uses forward slashes regardless of the operating system. func (doc Document) Path() string { return filepath.ToSlash(doc.RelativePath) }
package workspace import "path/filepath" // Document is a file in a directory. type Document struct { Root string RelativePath string } // NewDocument creates a document from a relative filepath. // The root is typically the root of the exercise, and // path is the relative path to the file within the root directory. func NewDocument(root, path string) (Document, error) { path, err := filepath.Rel(root, path) if err != nil { return Document{}, err } return Document{ Root: root, RelativePath: path, }, nil } // Filepath is the absolute path to the document on the filesystem. func (doc Document) Filepath() string { return filepath.Join(doc.Root, doc.RelativePath) } // Path is the normalized path. // It uses forward slashes regardless of the operating system. func (doc Document) Path() string { return filepath.ToSlash(doc.RelativePath) }
Update to laravel 5.4 guidelines
<?php namespace Milax\Mconsole\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\View; class ViewComposersServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { // } /** * Register the service provider. * * @return void */ public function register() { View::composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer'); View::composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer'); View::composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer'); View::composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer'); View::composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer'); View::composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer'); View::composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer'); View::composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer'); } }
<?php namespace Milax\Mconsole\Providers; use Illuminate\Support\ServiceProvider; class ViewComposersServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { // } /** * Register the service provider. * * @return void */ public function register() { view()->composer('mconsole::app', 'Milax\Mconsole\Composers\SectionComposer'); view()->composer('mconsole::partials.menu', 'Milax\Mconsole\Composers\MenuComposer'); view()->composer('mconsole::app', 'Milax\Mconsole\Composers\OptionsComposer'); view()->composer(['mconsole::forms.upload', 'mconsole::uploads.form'], 'Milax\Mconsole\Composers\UploadFormComposer'); view()->composer('mconsole::forms.tags', 'Milax\Mconsole\Composers\TagsInputComposer'); view()->composer('mconsole::helpers.blade', 'Milax\Mconsole\Composers\BladeHelperViewComposer'); view()->composer('mconsole::forms.links', 'Milax\Mconsole\Composers\LinksSetsComposer'); view()->composer('mconsole::menu.form', 'Milax\Mconsole\Composers\LanguagesComposer'); } }