text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix the condition to return string
export default class EasyInput { constructor() { this.keys = [] } handleKeyDown(event) { if (event.ctrlKey) { this.keys.push(this.ignoreDupKey('Ctrl+')) } if (event.shiftKey) { this.keys.push(this.ignoreDupKey('Shift+')) } if (event.altKey) { this.keys.push(this.ignoreDupKey('Alt+')) } let res = (this.isPrintableKey(event.keyCode) ? this.keys.join('') + event.key : '') return res } ignoreDupKey(key) { if (this.keys.indexOf(key) == -1) { return key } else { return '' } } isPrintableKey(keyCode) { if (49 <= keyCode && keyCode <= 90) { return true } else { return false } } }
export default class EasyInput { constructor() { this.keys = [] } handleKeyDown(event) { if (event.ctrlKey) { this.keys.push(this.ignoreDupKey('Ctrl+')) } if (event.shiftKey) { this.keys.push(this.ignoreDupKey('Shift+')) } if (event.altKey) { this.keys.push(this.ignoreDupKey('Alt+')) } let res = this.keys.join('') + (this.isPrintableKey(event.keyCode) ? event.key : '') return res } ignoreDupKey(key) { if (this.keys.indexOf(key) == -1) { return key } else { return '' } } isPrintableKey(keyCode) { if (49 <= keyCode && keyCode <= 90) { return true } else { return false } } }
Add log message about starting in the emulator
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else if (navigator.userAgent) { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } else { console.log('No navigator.userAgent, probably running in emulator'); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
/* global Pebble navigator */ function pebbleSuccess(e) { // do nothing } function pebbleFailure(e) { console.error(e); } var reportPhoneBatt; Pebble.addEventListener('ready', function(e) { if (navigator.getBattery) { navigator.getBattery().then(function (battery) { reportPhoneBatt = function () { Pebble.sendAppMessage({ 'PHONE_BATT_LEVEL': Math.floor(battery.level * 100), 'PHONE_BATT_CHARGING': battery.charging ? 1 : 0 }, pebbleSuccess, pebbleFailure); }; battery.addEventListener('levelchange', function() { console.log('Level change: '+ (battery.level * 100) +'%'); reportPhoneBatt(); }); battery.addEventListener('chargingchange', reportPhoneBatt); reportPhoneBatt(); }); } else { console.error('No navigator.getBattery'); console.error('User agent: '+navigator.userAgent); } }); Pebble.addEventListener('appmessage', function(e) { if (e.payload.QUERY_PHONE_BATT && reportPhoneBatt) { return reportPhoneBatt(); } });
Revert "Removed the limit on re-running tests in the same client." This reverts commit ab108ee5f966718833d96260538b13033eda9296.
<?php include "inc/init.php"; $result = mysql_queryf("SELECT run_id FROM run_useragent WHERE useragent_id=%u AND runs < max ORDER BY run_id DESC LIMIT 1;", $useragent_id); # A run was found if ( $row = mysql_fetch_array($result) ) { $run_id = $row[0]; $result = mysql_queryf("SELECT url FROM runs WHERE id=%u LIMIT 1;", $run_id); # TODO: Return more run info to the client (Name, etc.) if ( $row = mysql_fetch_array($result) ) { $url = $row[0]; } # Make sure that we don't re-run the tests in the same client $result = mysql_queryf("SELECT 1 FROM run_client WHERE run_id=%u AND client_id=%u LIMIT 1;", $run_id, $client_id); if ( mysql_num_rows($result) == 0 ) { # Mark the run as "in progress" on the useragent mysql_queryf("UPDATE run_useragent SET runs = runs + 1, status = 1 WHERE run_id=%u AND useragent_id=%u LIMIT 1;", $run_id, $useragent_id); # Initialize the client run mysql_queryf("INSERT INTO run_client (run_id,client_id,status,created) VALUES(%u,%u,1,NOW());", $run_id, $client_id); echo "$run_id $url"; } } exit(); ?>
<?php include "inc/init.php"; $result = mysql_queryf("SELECT run_id FROM run_useragent WHERE useragent_id=%u AND runs < max ORDER BY run_id DESC LIMIT 1;", $useragent_id); # A run was found if ( $row = mysql_fetch_array($result) ) { $run_id = $row[0]; $result = mysql_queryf("SELECT url FROM runs WHERE id=%u LIMIT 1;", $run_id); # TODO: Return more run info to the client (Name, etc.) if ( $row = mysql_fetch_array($result) ) { $url = $row[0]; } # Mark the run as "in progress" on the useragent mysql_queryf("UPDATE run_useragent SET runs = runs + 1, status = 1 WHERE run_id=%u AND useragent_id=%u LIMIT 1;", $run_id, $useragent_id); # Initialize the client run mysql_queryf("INSERT INTO run_client (run_id,client_id,status,created) VALUES(%u,%u,1,NOW());", $run_id, $client_id); echo "$run_id $url"; } exit(); ?>
Deal with commands in any case.
var Chat = function(socket) { this.socket = socket; }; Chat.prototype.sendMessage = function(room, text) { var message = { room: room, text: text }; this.socket.emit('message', message); }; Chat.prototype.changeRoom = function(currentRoom, newRoom) { this.socket.emit('join', { newRoom: newRoom, previousRoom: currentRoom }); }; Chat.prototype.processCommand = function(currentRoom, command) { var words = command.split(' ') , command = words[0].substring(1, words[0].length).toLowerCase() , message; switch(command) { case 'join': words.shift(); var newRoom = words.join(' '); this.changeRoom(currentRoom, newRoom); break; case 'nick': words.shift(); var name = words.join(' '); this.socket.emit('nameAttempt', name); break; default: message = '<i>Unrecognized command.</i>'; break; } return message; };
var Chat = function(socket) { this.socket = socket; }; Chat.prototype.sendMessage = function(room, text) { var message = { room: room, text: text }; this.socket.emit('message', message); }; Chat.prototype.changeRoom = function(currentRoom, newRoom) { this.socket.emit('join', { newRoom: newRoom, previousRoom: currentRoom }); }; Chat.prototype.processCommand = function(currentRoom, command) { var words = command.split(' ') , command = words[0].substring(1, words[0].length) , message; switch(command) { case 'join': words.shift(); var newRoom = words.join(' '); this.changeRoom(currentRoom, newRoom); break; case 'nick': words.shift(); var name = words.join(' '); this.socket.emit('nameAttempt', name); break; default: message = '<i>Unrecognized command.</i>'; break; } return message; };
Fix request scheme: REQUEST_SCHEME doesn't exist for PHP 7 built-in server
<?php session_start(); require __DIR__.'/../vendor/autoload.php'; use \BW\Vkontakte as Vk; $vk = new Vk([ 'client_id' => '5759854', 'client_secret' => 'a556FovqtUBHArlXlAAO', 'redirect_uri' => 'http://localhost:8000', ]); if (isset($_GET['code'])) { $vk->authenticate($_GET['code']); $_SESSION['access_token'] = $vk->getAccessToken(); header('Location: '.'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']); exit; } else { $accessToken = isset($_SESSION['access_token']) ? $_SESSION['access_token'] : null; $vk->setAccessToken($accessToken); } $userId = $vk->getUserId(); var_dump($userId); $users = $vk->api('users.get', [ 'user_id' => '1', 'fields' => [ 'photo_50', 'city', 'sex', ], ]); var_dump($users); ?> <br> <a href="<?= $vk->getLoginUrl() ?>"> <?php if ($userId) : ?> Re-authenticate <?php else : ?> Authenticate <?php endif ?> </a>
<?php session_start(); require __DIR__.'/../vendor/autoload.php'; use \BW\Vkontakte as Vk; $vk = new Vk([ 'client_id' => '5759854', 'client_secret' => 'a556FovqtUBHArlXlAAO', 'redirect_uri' => 'http://localhost:8000', ]); if (isset($_GET['code'])) { $vk->authenticate($_GET['code']); $_SESSION['access_token'] = $vk->getAccessToken(); header('Location: ' . $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); exit; } else { $accessToken = isset($_SESSION['access_token']) ? $_SESSION['access_token'] : null; $vk->setAccessToken($accessToken); } $userId = $vk->getUserId(); var_dump($userId); $users = $vk->api('users.get', [ 'user_id' => '1', 'fields' => [ 'photo_50', 'city', 'sex', ], ]); var_dump($users); ?> <br> <a href="<?= $vk->getLoginUrl() ?>"> <?php if ($userId) : ?> Re-authenticate <?php else : ?> Authenticate <?php endif ?> </a>
BUGFIX: Allow the fetch API to be used since we polyfill it globally
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true, Generator: true, Iterator: true }, settings: { polyfills: ['fetch'] }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
module.exports = { parser: 'babel-eslint', extends: [ 'xo', 'xo-react', 'plugin:jsx-a11y/recommended', 'plugin:promise/recommended', 'plugin:react/recommended' ], plugins: [ 'compat', 'promise', 'babel', 'react', 'jsx-a11y' ], env: { node: true, browser: true, jest: true }, globals: { analytics: true, Generator: true, Iterator: true }, rules: { 'compat/compat': 2, 'react/jsx-boolean-value': 0, 'react/require-default-props': 0, 'react/forbid-component-props': 0, 'promise/avoid-new': 0, 'generator-star-spacing': 0 } };
Add the class name note
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` from rot13. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. Change the class name if necessary. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS feed easily. function feedparse($url) { $feed = @fopen("$url", 'r'); if ($feed) { $data = ''; while (!feof($feed)) { $data .= fread($feed, 8192); } } fclose($feed); echo $data; } ?>
<?php /* * Core functions. * * Don't forget to add own ones. */ // `encrypt` // // Encrypts `$str` in rot13. function encrypt($str) { echo str_rot13($str); } // `decrypt` // // Decrypts `$str` from rot13. function decrypt($str) { echo str_rot13(str_rot13($str)); } // `cfile` // // Checks for current file. function cfile($file) { if (strpos($_SERVER['PHP_SELF'], $file)) { echo 'class="active"'; } } // `fcount` // // Counts number of files in a directory. function fcount($dir) { $i = 0; if ($handle = opendir($dir)) { while (($file = readdir($handle)) !== false) { if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) { $i++; } } } } // `feedparse` // // Parses RSS feed easily. function feedparse($url) { $feed = @fopen("$url", 'r'); if ($feed) { $data = ''; while (!feof($feed)) { $data .= fread($feed, 8192); } } fclose($feed); echo $data; } ?>
Change active to a boolean
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInstallationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('installations', function (Blueprint $table) { $table->increments('id'); $table->string('token')->unique(); $table->boolean('active')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('installations'); } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateInstallationsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('installations', function (Blueprint $table) { $table->increments('id'); $table->string('token')->unique(); $table->integer('active')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('installations'); } }
Use correct IO pins and serial port
import signal import sys import serial import sms from xbee import XBee SERIAL_PORT = '/dev/usbserial-143' MOBILE_NUM = '0400000000' NOTIFICATION_MSG = 'Cock-a-doodle-doo! An egg is waiting for you!' egg_was_present = False def signal_handler(signal, frame): xbee.halt() serial_port.close() sys.exit(0) def packet_received(packet): samples = packet['samples'][0] egg_is_present = samples['dio-1'] if 'dio-1' in samples else False if egg_is_present and egg_is_present != egg_was_present: sms.send(MOBILE_NUM, NOTIFICATION_MSG) egg_was_present = egg_is_present signal.signal(signal.SIGINT, signal_handler) serial_port = serial.Serial(SERIAL_PORT, 9600) xbee = XBee(serial_port, callback=packet_received)
import signal import sys import serial import sms from xbee import XBee MOBILE_NUM = '0400000000' NOTIFICATION_MSG = 'Cock-a-doodle-doo! An egg is waiting for you!' egg_was_present = False def signal_handler(signal, frame): xbee.halt() serial_port.close() sys.exit(0) def packet_received(packet): samples = packet['samples'][0] egg_is_present = samples['dio-4'] if 'dio-4' in samples else False if egg_is_present and egg_is_present != egg_was_present: sms.send(MOBILE_NUM, NOTIFICATION_MSG) egg_was_present = egg_is_present signal.signal(signal.SIGINT, signal_handler) serial_port = serial.Serial('/dev/ttyp0', 9600) xbee = XBee(serial_port, callback=packet_received)
Make String polyfills configurable and writable This prevents breakage when used with other shims, and more closely follows the ECMAScript specification. Fixes #487.
// String.startsWith polyfill if (! String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { enumerable: false, configurable: true, writable: true, value: function(str) { var that = this; for(var i = 0, ceil = str.length; i < ceil; i++) if(that[i] !== str[i]) return false; return true; } }); } // String.endsWith polyfill if (! String.prototype.endsWith) { Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: true, writable: true, value: function(str) { var that = this; for(var i = 0, ceil = str.length; i < ceil; i++) if (that[i + that.length - ceil] !== str[i]) return false; return true; } }); }
// String.startsWith polyfill if (! String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { enumerable: false, configurable: false, writable: false, value: function(str) { var that = this; for(var i = 0, ceil = str.length; i < ceil; i++) if(that[i] !== str[i]) return false; return true; } }); } // String.endsWith polyfill if (! String.prototype.endsWith) { Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: false, writable: false, value: function(str) { var that = this; for(var i = 0, ceil = str.length; i < ceil; i++) if (that[i + that.length - ceil] !== str[i]) return false; return true; } }); }
Allow ember-orbit to be used in addons
'use strict'; const path = require('path'); const assert = require('assert'); const fs = require('fs'); module.exports = { name: require('./package').name, included() { const app = this._findHost(); const addonConfig = app.project.config(app.env)['orbit'] || {}; const collections = addonConfig.collections || {}; const modelsDir = collections.models || 'data-models'; let modelsPath; if ( app.project.pkg['ember-addon'] && app.project.pkg['ember-addon'].configPath ) { modelsPath = path.join('tests', 'dummy', 'app', modelsDir); } else { modelsPath = path.join('app', modelsDir); } const modelsDirectory = path.join(app.project.root, modelsPath); /* eslint-disable ember/no-invalid-debug-function-arguments */ assert( fs.existsSync(modelsDirectory), `[ember-orbit] The models directory is missing: "${modelsDirectory}". You can run 'ember g ember-orbit' to initialize ember-orbit and create this directory.` ); this._super.included.apply(this, arguments); } };
'use strict'; const path = require('path'); const assert = require('assert'); const fs = require('fs'); module.exports = { name: require('./package').name, included() { const app = this._findHost(); const addonConfig = this.app.project.config(app.env)['orbit'] || {}; const collections = addonConfig.collections || {}; const modelsDir = collections.models || 'data-models'; let modelsPath; if ( app.project.pkg['ember-addon'] && app.project.pkg['ember-addon'].configPath ) { modelsPath = path.join('tests', 'dummy', 'app', modelsDir); } else { modelsPath = path.join('app', modelsDir); } const modelsDirectory = path.join(app.project.root, modelsPath); /* eslint-disable ember/no-invalid-debug-function-arguments */ assert( fs.existsSync(modelsDirectory), `[ember-orbit] The models directory is missing: "${modelsDirectory}". You can run 'ember g ember-orbit' to initialize ember-orbit and create this directory.` ); this._super.included.apply(this, arguments); } };
Fix initializer deprecation for 2.x Resolves #4
import Ember from 'ember'; var proxyGenerator = function(name){ return function(msg = '', title = '') { window.toastr[name](msg.toString(), title.toString()); }; }; export function initialize() { // support 1.x and 2.x var application = arguments[1] || arguments[0]; var injectAs = options.injectAs; window.toastr.options = options.toastrOptions; var proxiedToastr = Ember.Object.extend(toastr).create({ success: proxyGenerator('success'), info: proxyGenerator('info'), warning: proxyGenerator('warning'), error: proxyGenerator('error') }); application.register('notify:main', proxiedToastr, { instantiate: false, singleton: true }); application.inject('route', injectAs, 'notify:main'); application.inject('controller', injectAs, 'notify:main'); application.inject('component', injectAs, 'notify:main'); }
import Ember from 'ember'; var proxyGenerator = function(name){ return function(msg = '', title = '') { window.toastr[name](msg.toString(), title.toString()); }; }; export function initialize(container, application, options) { var injectAs = options.injectAs; window.toastr.options = options.toastrOptions; var proxiedToastr = Ember.Object.extend(toastr).create({ success: proxyGenerator('success'), info: proxyGenerator('info'), warning: proxyGenerator('warning'), error: proxyGenerator('error') }); application.register('notify:main', proxiedToastr, { instantiate: false, singleton: true }); application.inject('route', injectAs, 'notify:main'); application.inject('controller', injectAs, 'notify:main'); application.inject('component', injectAs, 'notify:main'); }
FIX broken markdown and entities
const MySql = require("./MySql.js"); const entities = require("entities"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=entities.decodeHTML(obj[k])); } asMarkdown(){ return `*${this.post_title}* ${this.meet_start_time}\n${this.guid}`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT CAST(meta_value AS DATE) AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
const MySql = require("./MySql.js"); class Meet{ constructor(obj){ Object.keys(obj).forEach(k=>this[k]=obj[k]); } asMarkdown(){ return `*${this.post_title}* ${this.meet_start_time}\n_${this.guid}_`; } } Meet.fromObjArray = function(objArray){ return objArray.map(o=>new Meet(o)); }; function getAllMeets(){ return MySql.query(`SELECT * FROM wp_posts WHERE post_type = 'meet'`) .then(results=>Meet.fromObjArray(results.results)); } function getUpcomingMeets(){ return MySql.query(` SELECT meta_value AS meet_start_time, wp_posts.* FROM wp_postmeta LEFT JOIN wp_posts ON post_id=ID WHERE meta_key = 'meet_start_time' AND CAST(meta_value AS DATE) > CURDATE() `).then(results=>Meet.fromObjArray(results.results)); } module.exports = {getAllMeets,getUpcomingMeets};
Remove custom security manager after test finishes
package org.gbif.checklistbank.ws.resources; import java.security.Permission; import org.gbif.ws.app.Application; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.fail; public class WsAppTest { private SecurityManager sm; @Before public void init(){ sm = System.getSecurityManager(); System.setSecurityManager(new NoExitSecurityManager()); } @After public void shutdown(){ System.setSecurityManager(sm); } /** * Test the startup of the webapp. * We expect a ExitException raised as the Application stops because of missing configs. * But no NoSuchMethodError thrown by incompatible jackson we see with a wrong version introduced by solr */ @Test(expected = ExitException.class) public void testWsStartup() { Application.main(new String[]{}); } public static class ExitException extends RuntimeException { public ExitException(int status) { super("Exit status " + status + " called"); } } private static class NoExitSecurityManager extends SecurityManager { @Override public void checkPermission(Permission perm) { // allow anything. } @Override public void checkPermission(Permission perm, Object context) { // allow anything. } @Override public void checkExit(int status) { super.checkExit(status); throw new ExitException(status); } } }
package org.gbif.checklistbank.ws.resources; import java.security.Permission; import org.gbif.ws.app.Application; import org.junit.Test; import static org.junit.Assert.fail; public class WsAppTest { /** * Test the startup of the webapp. * We expect a SecurityException raised as the Application stops because of missing configs. * But no NoSuchMethodError thrown by incompatible jackson we see with a wrong version introduced by solr */ @Test(expected = SecurityException.class) public void testWsStartup() { // throw exception if Application exits System.setSecurityManager(new NoExitSecurityManager()); Application.main(new String[]{}); } private static class NoExitSecurityManager extends SecurityManager { @Override public void checkPermission(Permission perm) { // allow anything. } @Override public void checkPermission(Permission perm, Object context) { // allow anything. } @Override public void checkExit(int status) { super.checkExit(status); throw new SecurityException("Exit status " + status + " called"); } } }
Remove unecessary initialization from Route model
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'routes' origin_point = db.Column(db.String(128), nullable=False) destination_point = db.Column(db.String(128), nullable=False) distance = db.Column(db.Integer, nullable=False) def __repr__(self): return '<Route <{0}-{1}-{2]>'.format(self.origin_pint, self.destination_point, self.distance)
from app import db class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, default=db.func.current_timestamp()) class Route(Base): __tablename__ = 'routes' origin_point = db.Column(db.String(128), nullable=False) destination_point = db.Column(db.String(128), nullable=False) distance = db.Column(db.Integer, nullable=False) def __init__(self, origin_point, destination_point, distance): self.origin_point = origin_point self.destination_point = destination_point self.distance = distance def __repr__(self): return '<Route <{0}-{1}-{2]>'.format(self.origin_pint, self.destination_point, self.distance)
Fix packaging to resolve the PEP420 namespace Setuptools is still lacking support for PEP480 namespace packages when using the find_packages function. Until it does all packages, including the namespace, must be registered in the packages list.
"""Setuptools configuration for interfaces.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='asyncdef.interfaces', version='0.1.3', url='https://github.com/asyncdef/interfaces', description='Public APIs for the core asyncdef components.', author="Kevin Conway", author_email="kevinjacobconway@gmail.com", long_description=README, license='Apache 2.0', packages=[ 'asyncdef', 'asyncdef.interfaces', 'asyncdef.interfaces.engine', ], install_requires=[ 'iface', ], extras_require={ 'testing': [ 'pep257', 'pep8', 'pyenchant', 'pyflakes', 'pylint', ], }, entry_points={ 'console_scripts': [ ], }, include_package_data=True, zip_safe=False, )
"""Setuptools configuration for interfaces.""" from setuptools import setup from setuptools import find_packages with open('README.rst', 'r') as readmefile: README = readmefile.read() setup( name='asyncdef.interfaces', version='0.1.0', url='https://github.com/asyncdef/interfaces', description='Public APIs for the core asyncdef components.', author="Kevin Conway", author_email="kevinjacobconway@gmail.com", long_description=README, license='Apache 2.0', packages=find_packages(exclude=['build', 'dist', 'docs']), install_requires=[ 'iface', ], extras_require={ 'testing': [ 'pep257', 'pep8', 'pyenchant', 'pyflakes', 'pylint', ], }, entry_points={ 'console_scripts': [ ], }, include_package_data=True, zip_safe=False, )
Set Global Variable action created
package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.GroovyParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("Variable Name"), new GroovyParam("Value"), new CheckboxParam("Relative")); } @Override public String getTitle() { return "Set Global Var"; } @Override public String getDescription() { if ((boolean) get("Relative").getValue()) { return String.format("Change global '%s' by %s", get("Variable Name").getValue(), get("Value").getValue()); } else{ return String.format("Set global '%s' to %s", get("Variable Name").getValue(), get("Value").getValue()); } } @Override public String compileSyntax() { if ((boolean) get("Relative").getValue()) { return String.format("globals.%s = globals.%s + %s;\n", get("Variable Name").getValue(), get("Variable Name").getValue(), get("Value").getValue()); } else { return String.format("globals.%s = %s;\n", get("Variable Name").getValue(), get("Value").getValue()); } } @Override protected String getSyntax() { return null; } }
package structures.data.actions.library; import structures.data.DataAction; import structures.data.actions.params.CheckboxParam; import structures.data.actions.params.DoubleParam; import structures.data.actions.params.StringParam; public class SetGlobalVariable extends DataAction { public SetGlobalVariable(){ init(new StringParam("EditVariableKey"), new DoubleParam("EditVariableValue"), new CheckboxParam("RelativeVariable?")); } @Override public String getTitle() { return "SetGlobalVariable"; } @Override public String getDescription() { if((boolean) get("RelativeVariable?").getValue()){ return String.format("change %s by %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } else{ return String.format("make %s equal %.2f", get("EditVariableKey").getValue(), get("EditVariableValue").getValue()); } } @Override protected String getSyntax() { return "library.set_variable('%s', %f, %b);"; } }
Make logs dir if missing
<?php function debug_collectionInfoStart($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data\n", $log); } } function debug_collectionInfoEnd($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Finished collecting data\n\n", $log); } } function debug_collectionInterval($debug, $interval, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log); } } function debug($echo, $log) { if ($echo != "" && $echo !== NULL) { echo $echo; } if ($log == TRUE) { if (!file_exists("logs/debug.log")) { mkdir("logs"); $dbglog = fopen("logs/debug.log", "w"); fclose($dbglog); } file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND); } } ?>
<?php function debug_collectionInfoStart($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data\n", $log); } } function debug_collectionInfoEnd($debug, $log) { if ($debug == TRUE) { debug("[DEBUG] Finished collecting data\n\n", $log); } } function debug_collectionInterval($debug, $interval, $log) { if ($debug == TRUE) { debug("[DEBUG] Collecting data every " . $interval . " seconds\n\n", $log); } } function debug($echo, $log) { if ($echo != "" && $echo !== NULL) { echo $echo; } if ($log == TRUE) { if (!file_exists("logs/debug.log")) { $dbglog = fopen("logs/debug.log", "w"); fclose($dbglog); } file_put_contents("logs/debug.log", date("r") . " - " . $echo, FILE_APPEND); } } ?>
Bump version number and tag release
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = '0.11' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
# The MIT License # # Copyright (c) 2008 Bob Farrell # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import os.path __version__ = 'mercurial' package_dir = os.path.abspath(os.path.dirname(__file__)) def embed(locals_=None, args=['-i', '-q'], banner=None): from bpython.cli import main return main(args, locals_, banner)
Adjust serialization artifacts to match RI. svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=414445
/* * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * 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. */ /** * @author Maxim V. Berkultsev * @version $Revision: 1.2.6.3 $ */ package java.beans; /** * Indicates that a proposed property change is unacceptable. */ public class PropertyVetoException extends Exception { private static final long serialVersionUID = 129596057694162164L; private final PropertyChangeEvent evt; /** * <p>Constructs an instance with a message and the change event.</p> * @param message A description of the veto. * @param event The event that was vetoed. */ public PropertyVetoException(String message, PropertyChangeEvent event) { super(message); this.evt = event; } /** * <p>Gets the property change event.</p> * @return An instance of {@link PropertyChangeEvent} */ public PropertyChangeEvent getPropertyChangeEvent() { return evt; } }
/* * Copyright 2005 The Apache Software Foundation or its licensors, as applicable. * * 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. */ /** * @author Maxim V. Berkultsev * @version $Revision: 1.2.6.3 $ */ package java.beans; /** * @author Maxim V. Berkultsev * @version $Revision: 1.2.6.3 $ */ public class PropertyVetoException extends Exception { private PropertyChangeEvent event; /** * @com.intel.drl.spec_ref */ public PropertyVetoException(String message, PropertyChangeEvent event) { super(message); this.event = event; } /** * @com.intel.drl.spec_ref */ public PropertyChangeEvent getPropertyChangeEvent() { return event; } }
Fix for backwards trigger check on Art of Peace
const ProvinceCard = require('../../provincecard.js'); class TheArtOfPeace extends ProvinceCard { setupCardAbilities() { this.interrupt({ title: 'Honor all defenders and dishonor all attackers', when: { onBreakProvince: (event, context) => event.card === context.source && ( event.conflict.attackers.some(card => card.allowGameAction('dishonor', context)) || event.conflict.defenders.some(card => card.allowGameAction('honor', context)) ) }, handler: context => { this.game.addMessage('{0} uses {1} to dishonor all attackers and honor all defenders in this conflict', this.controller, this); this.game.applyGameAction(context, { honor: context.event.conflict.defenders, dishonor: context.event.conflict.attackers }); } }); } } TheArtOfPeace.id = 'the-art-of-peace'; module.exports = TheArtOfPeace;
const ProvinceCard = require('../../provincecard.js'); class TheArtOfPeace extends ProvinceCard { setupCardAbilities() { this.interrupt({ title: 'Honor all defenders and dishonor all attackers', when: { onBreakProvince: (event, context) => event.card === context.source && ( event.conflict.attackers.some(card => card.allowGameAction('honor', context)) || event.conflict.defenders.some(card => card.allowGameAction('dishonor', context)) ) }, handler: context => { this.game.addMessage('{0} uses {1} to dishonor all attackers and honor all defenders in this conflict', this.controller, this); this.game.applyGameAction(context, { honor: context.event.conflict.defenders, dishonor: context.event.conflict.attackers }); } }); } } TheArtOfPeace.id = 'the-art-of-peace'; module.exports = TheArtOfPeace;
Add line to save an entity in test
package servers; import com.onyx.application.WebDatabaseServer; import entities.SimpleEntity; /** * Created by timothy.osborn on 4/1/15. */ public class SampleDatabaseServer extends WebDatabaseServer { public SampleDatabaseServer() { } /** * Run Database Server * * ex: executable /Database/Location/On/Disk 8080 admin admin * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { SampleDatabaseServer server1 = new SampleDatabaseServer(); server1.setPort(8080); server1.setWebServicePort(8082); server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd"); server1.start(); SimpleEntity simpleEntity = new SimpleEntity(); simpleEntity.setName("Test Name"); simpleEntity.setSimpleId("ASDF"); server1.getPersistenceManager().saveEntity(simpleEntity); server1.join(); System.out.println("Started"); } }
package servers; import com.onyx.application.WebDatabaseServer; import entities.SimpleEntity; /** * Created by timothy.osborn on 4/1/15. */ public class SampleDatabaseServer extends WebDatabaseServer { public SampleDatabaseServer() { } /** * Run Database Server * * ex: executable /Database/Location/On/Disk 8080 admin admin * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { SampleDatabaseServer server1 = new SampleDatabaseServer(); server1.setPort(8080); server1.setWebServicePort(8082); server1.setDatabaseLocation("C:/Sandbox/Onyx/Tests/server.oxd"); server1.start(); SimpleEntity simpleEntity = new SimpleEntity(); simpleEntity.setName("Test Name"); simpleEntity.setSimpleId("ASDF"); server1.join(); System.out.println("Started"); } }
Handle unauthorized exceptions (do not pollute error log)
<?php if (defined('PHAST_SERVICE')) { $service = PHAST_SERVICE; } else if (!isset ($_GET['service'])) { http_response_code(404); exit; } else { $service = $_GET['service']; } if (isset ($_GET['src']) && !headers_sent()) { header('Location: ' . $_GET['src']); } else { http_response_code(404); exit; } require_once __DIR__ . '/bootstrap.php'; $config = require_once PHAST_CONFIG_FILE; try { $response = (new \Kibo\Phast\Factories\Services\ServicesFactory()) ->make($service, $config) ->serve(\Kibo\Phast\HTTP\Request::fromGlobals()); } catch (\Kibo\Phast\Exceptions\UnauthorizedException $e) { exit(); } header_remove('Location'); http_response_code($response->getCode()); foreach ($response->getHeaders() as $name => $value) { header($name . ': ' . $value); } echo $response->getContent();
<?php if (defined('PHAST_SERVICE')) { $service = PHAST_SERVICE; } else if (!isset ($_GET['service'])) { http_response_code(404); exit; } else { $service = $_GET['service']; } if (isset ($_GET['src']) && !headers_sent()) { header('Location: ' . $_GET['src']); } else { http_response_code(404); exit; } require_once __DIR__ . '/bootstrap.php'; $config = require_once PHAST_CONFIG_FILE; $response = (new \Kibo\Phast\Factories\Services\ServicesFactory()) ->make($service, $config) ->serve(\Kibo\Phast\HTTP\Request::fromGlobals()); header_remove('Location'); http_response_code($response->getCode()); foreach ($response->getHeaders() as $name => $value) { header($name . ': ' . $value); } echo $response->getContent();
Add id to Geek schema (we need it on client side!).
require.paths.unshift(__dirname + "/vendor/rest-mongo/src") var rest_mongo = require("rest-mongo") var schema = { Geek: { schema: { id: "Geek", description: "A geek / person / dev ...", type: "object", properties: { id: {type: "string"}, name: {type: "string"}, pole: {type: "string"}, width: {type: "float"}, height: {type: "float"}, top: {type: "float"}, left: {type: "float"} } } }, URL: { schema: { id: "URL", description: "URL, potentially interesting for geeks", type: "object", properties: { url: {type: "string"}, // the URL value from: {type: "string"}, // who posted the url (nick, name...) channel: {type: "string"} // where it has been posted (irc chan...) } } } } exports.RFactory = rest_mongo.getRFactory(schema, {db_name: "Geeks_dev"})
require.paths.unshift(__dirname + "/vendor/rest-mongo/src") var rest_mongo = require("rest-mongo") var schema = { Geek: { schema: { id: "Geek", description: "A geek / person / dev ...", type: "object", properties: { name: {type: "string"}, pole: {type: "string"}, width: {type: "float"}, height: {type: "float"}, top: {type: "float"}, left: {type: "float"} } } }, URL: { schema: { id: "URL", description: "URL, potentially interesting for geeks", type: "object", properties: { url: {type: "string"}, // the URL value from: {type: "string"}, // who posted the url (nick, name...) channel: {type: "string"} // where it has been posted (irc chan...) } } } } exports.RFactory = rest_mongo.getRFactory(schema, {db_name: "Geeks_dev"})
Apply class comments and refactor spacing
/* * Copyright 2015 Ryan Gilera. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.daytron.revworks.authentication; /** * Custom Exception for invalid authentication when cross-checking the user's * credentials with the information in the database. * * @author Ryan Gilera */ public class AuthenticationException extends Exception { public AuthenticationException(String msg, Throwable t) { super(msg, t); } public AuthenticationException(String msg) { super(msg); } public AuthenticationException(Throwable t) { super(t); } }
/* * Copyright 2015 Ryan Gilera. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.daytron.revworks.authentication; /** * * @author Ryan Gilera */ public class AuthenticationException extends Exception { public AuthenticationException(String msg, Throwable t) { super(msg, t); } public AuthenticationException(String msg) { super(msg); } public AuthenticationException(Throwable t) { super(t); } }
Change api route for consistency
#!/usr/bin/env node var path = require('path'); var express = require('express'); var bodyParser = require('body-parser'); var session = require('express-session'); var apiRouter = require('./lib/apiRouter.js'); var status = require('./lib/statusMiddleware.js'); var uploads = require('./lib/uploadMiddlewares.js'); var authentication = require('./lib/authenticationMiddlewares.js'); var app = express(); app.listen(80); app.use(bodyParser.json()); app.use(session({ secret: 'tall gels', resave: false, saveUninitialized: false })); app.use('/', express.static(path.resolve(__dirname, 'static'))); app.use('/', express.static(path.resolve(process.cwd(), 'public'))); app.use('/files', express.static(path.resolve(process.cwd(), 'files'))); app.use('/chill/api', apiRouter); app.post('/chill/login', authentication.postLogin); app.post('/chill/admins', authentication.postAdmins); app.get('/chill/uploads', requireAuthentication, uploads.getUploads); app.post('/chill/uploads', requireAuthentication, uploads.postUpload); app.delete('/chill/uploads/:filename', requireAuthentication, uploads.deleteUpload); app.get('/chill/status', status); function requireAuthentication(req, res, next) { if (req.session.admin) next(); else res.status(403).end(); } console.log('Chill CMS is now running...');
#!/usr/bin/env node var path = require('path'); var express = require('express'); var bodyParser = require('body-parser'); var session = require('express-session'); var apiRouter = require('./lib/apiRouter.js'); var status = require('./lib/statusMiddleware.js'); var uploads = require('./lib/uploadMiddlewares.js'); var authentication = require('./lib/authenticationMiddlewares.js'); var app = express(); app.listen(80); app.use(bodyParser.json()); app.use(session({ secret: 'tall gels', resave: false, saveUninitialized: false })); app.use('/', express.static(path.resolve(__dirname, 'static'))); app.use('/', express.static(path.resolve(process.cwd(), 'public'))); app.use('/files', express.static(path.resolve(process.cwd(), 'files'))); app.use('/api', apiRouter); app.post('/chill/login', authentication.postLogin); app.post('/chill/admins', authentication.postAdmins); app.get('/chill/uploads', requireAuthentication, uploads.getUploads); app.post('/chill/uploads', requireAuthentication, uploads.postUpload); app.delete('/chill/uploads/:filename', requireAuthentication, uploads.deleteUpload); app.get('/chill/status', status); function requireAuthentication(req, res, next) { if (req.session.admin) next(); else res.status(403).end(); } console.log('Chill CMS is now running...');
NEW: Add link to the pull request that fix the issue.
var scrapinode = require('./../main.js')(); // Issue with this page similar to https://github.com/tmpvar/jsdom/issues/290 // Fix https://github.com/tmpvar/jsdom/pull/387 // Works great with cheerio var url = 'http://www.dell.com/uk/p/xps-15z/pd?oc=n0015z01epp&model_id=xps-15z&'; scrapinode.createScraper(url,'jsdom',function(err,scraper){ if(err){ console.log(err); }else{ var title = scraper.get('title'); var description = scraper.get('description'); var images = scraper.get('images'); console.log('IMAGES'); console.log(images); console.log('TITLE:'+title); console.log('DESCRIPTION'); console.log(description); } });
var scrapinode = require('./../main.js')(); // Issue with this page similar to https://github.com/tmpvar/jsdom/issues/290 // Works great with cheerio var url = 'http://www.dell.com/uk/p/xps-15z/pd?oc=n0015z01epp&model_id=xps-15z&'; scrapinode.createScraper(url,'jsdom',function(err,scraper){ if(err){ console.log(err); }else{ var title = scraper.get('title'); var description = scraper.get('description'); var images = scraper.get('images'); console.log('IMAGES'); console.log(images); console.log('TITLE:'+title); console.log('DESCRIPTION'); console.log(description); } });
Fix ESLint error causing Travis build to fail 'jsx-max-props-per-line' rule
import React from 'react'; import commonUrl from 'shared/constants/commonLinks'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './opCodeCon.css'; const OpCodeCon = () => ( <div className={styles.hero}> <div className={styles.heading}> <h1>OpCodeCon</h1> <h3>Join us for our inaugural Operation Code Convention!</h3> <p>September 19th-20th, 2018</p> <p>Raleigh Convention Center, Raleigh, NC</p> <p> <a href="mailto:eilish@operationcode.org" className={styles.textLink}> Contact us </a>{' '} for sponsorship information. </p> <LinkButton role="button" text="Donate" theme="red" link={commonUrl.donateLink} isExternal /> {/* <p>Check back for more information.</p> */} </div> </div> ); export default OpCodeCon;
import React from 'react'; import commonUrl from 'shared/constants/commonLinks'; import LinkButton from 'shared/components/linkButton/linkButton'; import styles from './opCodeCon.css'; const OpCodeCon = () => ( <div className={styles.hero}> <div className={styles.heading}> <h1>OpCodeCon</h1> <h3>Join us for our inaugural Operation Code Convention!</h3> <p>September 19th-20th, 2018</p> <p>Raleigh Convention Center, Raleigh, NC</p> <p> <a href="mailto:eilish@operationcode.org" className={styles.textLink}> Contact us </a>{' '} for sponsorship information. </p> <LinkButton role="button" text="Donate" theme="red" link={commonUrl.donateLink} isExternal /> {/* <p>Check back for more information.</p> */} </div> </div> ); export default OpCodeCon;
Remove deployState parameter, forgotten during rebase to master. - Was used for spooler only.
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.builder.xml.dom; import com.yahoo.config.model.ConfigModelContext; import com.yahoo.config.model.builder.xml.ConfigModelId; import com.yahoo.vespa.model.clients.Clients; import org.w3c.dom.Element; import java.util.Arrays; import java.util.List; /** * Builds the Clients plugin * * @author hmusum */ public class DomClientsBuilder extends LegacyConfigModelBuilder<Clients> { public DomClientsBuilder() { super(Clients.class); } @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(ConfigModelId.fromNameAndVersion("clients", "2.0")); } @Override public void doBuild(Clients clients, Element clientsE, ConfigModelContext modelContext) { String version = clientsE.getAttribute("version"); if (version.startsWith("2.")) { DomV20ClientsBuilder parser = new DomV20ClientsBuilder(clients, version); parser.build(clientsE); } else { throw new IllegalArgumentException("Version '" + version + "' of 'clients' not supported."); } } }
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.builder.xml.dom; import com.yahoo.config.model.ConfigModelContext; import com.yahoo.config.model.builder.xml.ConfigModelId; import com.yahoo.vespa.model.clients.Clients; import org.w3c.dom.Element; import java.util.Arrays; import java.util.List; /** * Builds the Clients plugin * * @author hmusum */ public class DomClientsBuilder extends LegacyConfigModelBuilder<Clients> { public DomClientsBuilder() { super(Clients.class); } @Override public List<ConfigModelId> handlesElements() { return Arrays.asList(ConfigModelId.fromNameAndVersion("clients", "2.0")); } @Override public void doBuild(Clients clients, Element clientsE, ConfigModelContext modelContext) { String version = clientsE.getAttribute("version"); if (version.startsWith("2.")) { DomV20ClientsBuilder parser = new DomV20ClientsBuilder(clients, version); parser.build(modelContext.getDeployState(), clientsE); } else { throw new IllegalArgumentException("Version '" + version + "' of 'clients' not supported."); } } }
Make test_get_application_access_token_raises_error compatible with Python < 2.7
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def mock(): global mock_request mock_request = patch.start()().request def unmock(): patch.stop() @with_setup(mock, unmock) def test_get_application_access_token(): mock_request.return_value.content = 'access_token=...' access_token = get_application_access_token('<application id>', '<application secret key>') mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token', allow_redirects = True, params = { 'client_id': '<application id>', 'client_secret': '<application secret key>', 'grant_type': 'client_credentials' } ) assert access_token == '...' @with_setup(mock, unmock) def test_get_application_access_token_raises_error(): mock_request.return_value.content = 'An unknown error occurred' assert_raises( GraphAPI.FacebookError, get_application_access_token, '<application id>', '<application secret key>' )
"""Tests for the ``utils`` module.""" from mock import patch, Mock as mock from nose.tools import * from facepy import * patch = patch('requests.session') def mock(): global mock_request mock_request = patch.start()().request def unmock(): patch.stop() @with_setup(mock, unmock) def test_get_application_access_token(): mock_request.return_value.content = 'access_token=...' access_token = get_application_access_token('<application id>', '<application secret key>') mock_request.assert_called_with('GET', 'https://graph.facebook.com/oauth/access_token', allow_redirects = True, params = { 'client_id': '<application id>', 'client_secret': '<application secret key>', 'grant_type': 'client_credentials' } ) assert access_token == '...' @with_setup(mock, unmock) def test_get_application_access_token_raises_error(): mock_request.return_value.content = 'An unknown error occurred' with assert_raises(GraphAPI.FacebookError): get_application_access_token('<application id>', '<application secret key>')
Fix indent and trailing whitespace.
var settings = require('ep_etherpad-lite/node/utils/Settings'); var githubAuth = require('github-auth'); var config = { organization: settings.users.github.org, autologin: true // This automatically redirects you to github to login. }; var gh = githubAuth(settings.users.github.appId,settings.users.github.appSecret, config); exports.expressConfigure = function(hook_name, args, cb) { var app = args.app; app.get('/login', gh.login); app.use(gh.authenticate); app.use(function(req, res, next) { if (req.path.match(/^\/(static|javascripts|pluginfw)/)) { // Don't ask for github auth for static paths next(); } else { // Use Github Auth if (!req.github) return res.send('<a href="/login">Please login</a>'); if (!req.github.authenticated) return res.send('You shall not pass'); next(); } }); }
var settings = require('ep_etherpad-lite/node/utils/Settings'); var githubAuth = require('github-auth'); var config = { organization: settings.users.github.org, autologin: true // This automatically redirects you to github to login. }; var gh = githubAuth(settings.users.github.appId,settings.users.github.appSecret, config); exports.expressConfigure = function(hook_name, args, cb) { var app = args.app; app.get('/login', gh.login); app.use(gh.authenticate); app.use(function(req, res, next) { if (req.path.match(/^\/(static|javascripts|pluginfw)/)) { // Don't ask for github auth for static paths next(); } else { // Use Github Auth if (!req.github) return res.send('<a href="/login">Please login</a>'); if (!req.github.authenticated) return res.send('You shall not pass'); next(); } }); }
Add Response class for unsupported media
from django.http import HttpResponse class HttpResponseCreated(HttpResponse): status_code = 201 class HttpResponseNoContent(HttpResponse): status_code = 204 class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, allow_headers): """ RFC2616: The response MUST include an Allow header containing a list of valid methods for the requested resource. """ super(HttpResponseNotAllowed, self).__init__() try: iter(allow_headers) except TypeError: self['Allow'] = allow_headers else: self['Allow'] = ", ".join(allow_headers) class HttpResponseNotAcceptable(HttpResponse): status_code = 406 class HttpResponseConflict(HttpResponse): status_code = 409 class HttpResponseUnsupportedMediaType(HttpResponse): status_code = 415 class HttpResponseNotImplemented(HttpResponse): status_code = 501
from django.http import HttpResponse class HttpResponseCreated(HttpResponse): status_code = 201 class HttpResponseNoContent(HttpResponse): status_code = 204 class HttpResponseNotAllowed(HttpResponse): status_code = 405 def __init__(self, allow_headers): """ RFC2616: The response MUST include an Allow header containing a list of valid methods for the requested resource. """ super(HttpResponseNotAllowed, self).__init__() try: iter(allow_headers) except TypeError: self['Allow'] = allow_headers else: self['Allow'] = ", ".join(allow_headers) class HttpResponseNotAcceptable(HttpResponse): status_code = 406 class HttpResponseConflict(HttpResponse): status_code = 409 class HttpResponseNotImplemented(HttpResponse): status_code = 501
Exclude filter expression from selector
'use strict' /** * @license * node-scrapy <https://github.com/eeshi/node-scrapy> * Copyright Stefan Maric, Adrian Obelmejias, and other contributors <https://github.com/eeshi/node-scrapy/graphs/contributors> * Released under MIT license <https://github.com/eeshi/node-scrapy/blob/master/LICENSE> */ module.exports = exports = queryParser function queryParser (query) { return { selector: extractSelector(query), getter: extractGetter(query), filters: extractFilters(query) } } function extractSelector (query) { return query.split(/\s*(=>|\|)\s*/)[0] } function extractGetter (query) { let matches = query.match(/=>([^|]+)/) return matches ? matches[1].replace(/\s/g, '') : null } function extractFilters (query) { return query.split(/\s*\|\s*/).slice(1).map(extractFilter) } function extractFilter (filterString) { return { name: filterString.match(/^\w+/)[0], args: filterString.split(/:/).slice(1) } }
'use strict' /** * @license * node-scrapy <https://github.com/eeshi/node-scrapy> * Copyright Stefan Maric, Adrian Obelmejias, and other contributors <https://github.com/eeshi/node-scrapy/graphs/contributors> * Released under MIT license <https://github.com/eeshi/node-scrapy/blob/master/LICENSE> */ module.exports = exports = queryParser function queryParser (query) { return { selector: extractSelector(query), getter: extractGetter(query), filters: extractFilters(query) } } function extractSelector (query) { return query.split(/\s*=>\s*/)[0] } function extractGetter (query) { let matches = query.match(/=>([^|]+)/) return matches ? matches[1].replace(/\s/g, '') : null } function extractFilters (query) { return query.split(/\s*\|\s*/).slice(1).map(extractFilter) } function extractFilter (filterString) { return { name: filterString.match(/^\w+/)[0], args: filterString.split(/:/).slice(1) } }
Rename the library sessions instead of Sessions
# Copyright 2014 Donald Stufft # # 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 __future__ import absolute_import, division, print_function __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "sessions" __summary__ = "Web framework agnostic management of sessions" __uri__ = "https://github.com/dstufft/sessions" __version__ = "0.1.0" __author__ = "Donald Stufft" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2014 %s" % __author__
# Copyright 2014 Donald Stufft # # 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 __future__ import absolute_import, division, print_function __all__ = [ "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ] __title__ = "Sessions" __summary__ = "Web framework agnostic management of sessions" __uri__ = "https://github.com/dstufft/sessions" __version__ = "0.1.0" __author__ = "Donald Stufft" __email__ = "donald@stufft.io" __license__ = "Apache License, Version 2.0" __copyright__ = "Copyright 2014 %s" % __author__
Change custom markup to asynchronous testing
'use strict'; var _ = require('lodash'); var fs = require('fs'); var utility = require('../utility'); var handleFile = utility.handleExpectedFile; describe('custom markup', function() { before(function() { var testHTML = document.querySelectorAll('#custom-markup .hljs'); this.blocks = _.map(testHTML, 'innerHTML'); }); it('should replace tabs', function(done) { var filename = utility.buildPath('expect', 'tabreplace.txt'), actual = this.blocks[0]; fs.readFile(filename, 'utf-8', handleFile(actual, done)); }); it('should keep custom markup', function(done) { var filename = utility.buildPath('expect', 'custommarkup.txt'), actual = this.blocks[1]; fs.readFile(filename, 'utf-8', handleFile(actual, done)); }); it('should keep custom markup and replace tabs', function(done) { var filename = utility.buildPath('expect', 'customtabreplace.txt'), actual = this.blocks[2]; fs.readFile(filename, 'utf-8', handleFile(actual, done)); }); it('should keep the same amount of void elements (<br>, <hr>, ...)', function(done) { var filename = utility.buildPath('expect', 'brInPre.txt'), actual = this.blocks[3]; fs.readFile(filename, 'utf-8', handleFile(actual, done)); }); });
'use strict'; var _ = require('lodash'); var fs = require('fs'); var utility = require('../utility'); describe('custom markup', function() { before(function() { var testHTML = document.querySelectorAll('#custom-markup .hljs'); this.blocks = _.map(testHTML, 'innerHTML'); }); it('should replace tabs', function() { var filename = utility.buildPath('expect', 'tabreplace.txt'), expected = fs.readFileSync(filename, 'utf-8'), actual = this.blocks[0]; actual.should.equal(expected); }); it('should keep custom markup', function() { var filename = utility.buildPath('expect', 'custommarkup.txt'), expected = fs.readFileSync(filename, 'utf-8'), actual = this.blocks[1]; actual.should.equal(expected); }); it('should keep custom markup and replace tabs', function() { var filename = utility.buildPath('expect', 'customtabreplace.txt'), expected = fs.readFileSync(filename, 'utf-8'), actual = this.blocks[2]; actual.should.equal(expected); }); it('should keep the same amount of void elements (<br>, <hr>, ...)', function() { var filename = utility.buildPath('expect', 'brInPre.txt'), expected = fs.readFileSync(filename, 'utf-8'), actual = this.blocks[3]; actual.should.equal(expected); }); });
Fix amd part of umd to return r function correctly.
function r() { var strings = arguments[0]; // template strings var values = Array.prototype.slice.call(arguments, 1); // interpolation values // concentrate strings and interpolations var str = strings.raw.reduce(function(prev, cur, idx) { return prev + values[idx-1] + cur; }) .replace(/\r\n/g, '\n'); // replace for window newline \r\n // check top-tagged applied var newlineAndTabs = str.match(/^\n[\t]*/); if( newlineAndTabs != null ) { var matched = newlineAndTabs[0]; str = str.replace(new RegExp(matched, 'g'), '\n') .substr(1); } else { var matched = str.match(/^[\t]*/)[0]; str = str.substr(matched.length) .replace(new RegExp('\n'+matched, 'g'), '\n'); } return str; } (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], function(){ return factory; }); } else if (typeof module === 'object' && module.exports) { module.exports = factory; } else { // Browser globals (root is window) root["removeTabs"] = factory; } }(this, r));
function r() { var strings = arguments[0]; // template strings var values = Array.prototype.slice.call(arguments, 1); // interpolation values // concentrate strings and interpolations var str = strings.raw.reduce(function(prev, cur, idx) { return prev + values[idx-1] + cur; }) .replace(/\r\n/g, '\n'); // replace for window newline \r\n // check top-tagged applied var newlineAndTabs = str.match(/^\n[\t]*/); if( newlineAndTabs != null ) { var matched = newlineAndTabs[0]; str = str.replace(new RegExp(matched, 'g'), '\n') .substr(1); } else { var matched = str.match(/^[\t]*/)[0]; str = str.substr(matched.length) .replace(new RegExp('\n'+matched, 'g'), '\n'); } return str; } (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory; } else { // Browser globals (root is window) root["removeTabs"] = factory; } }(this, r));
Add missing use for \Doctrine\DBAL\Cache\QueryCacheProfile
<?php namespace Bolt\Storage\Database; use Bolt\Events\FailedConnectionEvent; use Doctrine\DBAL\Cache\QueryCacheProfile; use Doctrine\DBAL\DBALException; /** * Extension of DBAL's Connection class to allow catching of database connection * exceptions. * * @author Gawain Lynch <gawain.lynch@gmail.com> * @author Carson Full <carsonfull@gmail.com> */ class MasterSlaveConnection extends \Doctrine\DBAL\Connections\MasterSlaveConnection { protected $_queryCacheProfile; /** * {@inheritdoc} */ public function connect($connectionName = null) { try { return parent::connect($connectionName); } catch (DBALException $e) { if ($this->_eventManager->hasListeners('failConnect')) { $eventArgs = new FailedConnectionEvent($this, $e); $this->_eventManager->dispatchEvent('failConnect', $eventArgs); } } } /** * Sets an optional Query Cache handler on the connection class * * @param QueryCacheProfile $profile */ public function setQueryCacheProfile(QueryCacheProfile $profile) { $this->_queryCacheProfile = $profile; } }
<?php namespace Bolt\Storage\Database; use Bolt\Events\FailedConnectionEvent; use Doctrine\DBAL\DBALException; /** * Extension of DBAL's Connection class to allow catching of database connection * exceptions. * * @author Gawain Lynch <gawain.lynch@gmail.com> * @author Carson Full <carsonfull@gmail.com> */ class MasterSlaveConnection extends \Doctrine\DBAL\Connections\MasterSlaveConnection { protected $_queryCacheProfile; /** * {@inheritdoc} */ public function connect($connectionName = null) { try { return parent::connect($connectionName); } catch (DBALException $e) { if ($this->_eventManager->hasListeners('failConnect')) { $eventArgs = new FailedConnectionEvent($this, $e); $this->_eventManager->dispatchEvent('failConnect', $eventArgs); } } } /** * Sets an optional Query Cache handler on the connection class * * @param QueryCacheProfile $profile */ public function setQueryCacheProfile(QueryCacheProfile $profile) { $this->_queryCacheProfile = $profile; } }
Add a test so that other regions are fine with DynamoDB using the STS service
var fmt = require('fmt'); var awssum = require('awssum'); var amazon = awssum.load('amazon/amazon'); var DynamoDB = awssum.load('amazon/dynamodb').DynamoDB; var env = process.env; var accessKeyId = env.ACCESS_KEY_ID; var secretAccessKey = env.SECRET_ACCESS_KEY; var awsAccountId = env.AWS_ACCOUNT_ID; var ddb = new DynamoDB({ 'accessKeyId' : accessKeyId, 'secretAccessKey' : secretAccessKey, 'awsAccountId' : awsAccountId, 'region' : amazon.US_EAST_1 }); var ddbWest = new DynamoDB({ 'accessKeyId' : accessKeyId, 'secretAccessKey' : secretAccessKey, 'awsAccountId' : awsAccountId, 'region' : amazon.US_WEST_2 }); fmt.field('Region', ddb.region() ); fmt.field('EndPoint', ddb.host() ); fmt.field('AccessKeyId', ddb.accessKeyId() ); fmt.field('SecretAccessKey', ddb.secretAccessKey().substr(0, 3) + '...' ); fmt.field('AwsAccountId', ddb.awsAccountId() ); ddb.ListTables(function(err, data) { fmt.msg("listing all the tables in us-east-1 - expecting success"); fmt.dump(err, 'Error'); fmt.dump(data, 'Data'); }); ddbWest.ListTables(function(err, data) { fmt.msg("listing all the tables in us-west-1 - expecting success"); fmt.dump(err, 'Error'); fmt.dump(data, 'Data'); });
var fmt = require('fmt'); var awssum = require('awssum'); var amazon = awssum.load('amazon/amazon'); var DynamoDB = awssum.load('amazon/dynamodb').DynamoDB; var env = process.env; var accessKeyId = env.ACCESS_KEY_ID; var secretAccessKey = env.SECRET_ACCESS_KEY; var awsAccountId = env.AWS_ACCOUNT_ID; var ddb = new DynamoDB({ 'accessKeyId' : accessKeyId, 'secretAccessKey' : secretAccessKey, 'awsAccountId' : awsAccountId, 'region' : amazon.US_EAST_1 }); fmt.field('Region', ddb.region() ); fmt.field('EndPoint', ddb.host() ); fmt.field('AccessKeyId', ddb.accessKeyId() ); fmt.field('SecretAccessKey', ddb.secretAccessKey().substr(0, 3) + '...' ); fmt.field('AwsAccountId', ddb.awsAccountId() ); ddb.ListTables(function(err, data) { fmt.msg("listing all the tables - expecting success"); fmt.dump(err, 'Error'); fmt.dump(data, 'Data'); });
Switch to external source map
var path = require('path'); var webpack = require('webpack'); var webpackSettings = require('./webpack-helper'); module.exports = webpackSettings({ entry: { 'backbone': path.join(__dirname, './adaptors/backbone'), 'ampersand': path.join(__dirname, './adaptors/ampersand'), 'core': path.join(__dirname, './tungsten'), 'template': [path.join(__dirname, './src/template/template.js')] }, output: { filename: path.join(__dirname, './dist/tungsten.[name].js'), libraryTarget: 'var', library: ['tungsten', '[name]'] }, resolve: { alias: { jquery: 'backbone.native' } }, externals: [ {underscore: 'var window._'}, {lodash: 'var window._'} ], resolveLoader: { modulesDirectories: [path.join(__dirname, 'node_modules')] }, devtool: '#source-map', module: { loaders: [] }, plugins: [ new webpack.optimize.CommonsChunkPlugin(path.join(__dirname, './dist/tungsten.core.js')) ] });
var path = require('path'); var webpack = require('webpack'); var webpackSettings = require('./webpack-helper'); module.exports = webpackSettings({ entry: { 'backbone': path.join(__dirname, './adaptors/backbone'), 'ampersand': path.join(__dirname, './adaptors/ampersand'), 'core': path.join(__dirname, './tungsten'), 'template': [path.join(__dirname, './src/template/template.js')] }, output: { filename: path.join(__dirname, './dist/tungsten.[name].js'), libraryTarget: 'var', library: ['tungsten', '[name]'] }, resolve: { alias: { jquery: 'backbone.native' } }, externals: [ {underscore: 'var window._'}, {lodash: 'var window._'} ], resolveLoader: { modulesDirectories: [path.join(__dirname, 'node_modules')] }, devtool: '#eval-source-map', module: { loaders: [] }, plugins: [ new webpack.optimize.CommonsChunkPlugin(path.join(__dirname, './dist/tungsten.core.js')) ] });
Add overridden behaviour to testapp.
from django.db import models from binder.models import BinderModel from binder.exceptions import BinderValidationError # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) def _binder_unset_relation_caretaker(self): raise BinderValidationError({'animal': {self.pk: {'caretaker': [{ 'code': 'cant_unset', 'message': 'You can\'t unset zoo.', }]}}}) class Binder: history = True
from django.db import models from binder.models import BinderModel # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) class Binder: history = True
Hide secret channels from /NAMES users
from twisted.words.protocols import irc from txircd.modbase import Mode class SecretMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "NAMES": return data remove = [] for chan in data["targetchan"]: if "p" in chan.mode and chan.name not in user.channels: user.sendMessage(irc.ERR_NOSUCHNICK, chan, ":No such nick/channel") remove.append(chan) for chan in remove: data["targetchan"].remove(chan) return data def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"].clear() # other +s stuff is hiding in other modules. class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.mode_s = None def spawn(self): self.mode_s = SecretMode() return { "modes": { "cns": self.mode_s }, "actions": { "commandextra": [self.mode_s.listOutput] } } def cleanup(self): self.ircd.removeMode("cns") self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)
from txircd.modbase import Mode class SecretMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"].clear() # other +s stuff is hiding in other modules. class Spawner(object): def __init__(self, ircd): self.ircd = ircd self.mode_s = None def spawn(self): self.mode_s = SecretMode() return { "modes": { "cns": self.mode_s }, "actions": { "commandextra": [self.mode_s.listOutput] } } def cleanup(self): self.ircd.removeMode("cns") self.ircd.actions["commandextra"].remove(self.mode_s.listOutput)
Clean up content and header output
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print('\n--- %s%s\n%s' % (self.command, self.path, self.headers)) print content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
#!/usr/bin/env python import BaseHTTPServer ServerClass = BaseHTTPServer.HTTPServer RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler SERVER_NAME = '' SERVER_PORT = 9000 class JsonPostResponder(RequestHandlerClass): def _get_content_from_stream(self, length, stream): return stream.read(length) def do_POST(self): content_length = int(self.headers['Content-Length']) content = self._get_content_from_stream(content_length, self.rfile) print '\n---> dummy server: got post!' print 'command:', self.command print 'path:', self.path print 'headers:\n\n', self.headers print 'content:\n\n', content, '\n' self.send_response(200) self.end_headers() server_address = (SERVER_NAME, SERVER_PORT) httpd = ServerClass(server_address, JsonPostResponder) httpd.serve_forever()
Make test dependencies installable as an extra Signed-off-by: Daniel Bluhm <6df8625bb799b640110458f819853f591a9910cb@sovrin.org>
from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' TEST_DEPS = [ 'pytest<3.7', 'pytest-asyncio', 'base58' ] setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['base58'], tests_require=TEST_DEPS, extras_require={ 'test': TEST_DEPS } )
from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] )
Replace hard coded timestamp with time.time()
# -*- coding: utf-8 -*- import time from chai import Chai from arrow import util class UtilTests(Chai): def test_is_timestamp(self): timestamp_float = time.time() timestamp_int = int(timestamp_float) self.assertTrue(util.is_timestamp(timestamp_int)) self.assertTrue(util.is_timestamp(timestamp_float)) self.assertFalse(util.is_timestamp(str(timestamp_int))) self.assertFalse(util.is_timestamp(str(timestamp_float))) self.assertFalse(util.is_timestamp(True)) self.assertFalse(util.is_timestamp(False)) full_datetime = "2019-06-23T13:12:42" self.assertFalse(util.is_timestamp(full_datetime)) overflow_timestamp_float = 99999999999999999999999999.99999999999999999999999999 with self.assertRaises((OverflowError, ValueError)): util.is_timestamp(overflow_timestamp_float) overflow_timestamp_int = int(overflow_timestamp_float) with self.assertRaises((OverflowError, ValueError)): util.is_timestamp(overflow_timestamp_int)
# -*- coding: utf-8 -*- from chai import Chai from arrow import util class UtilTests(Chai): def test_is_timestamp(self): timestamp_float = 1563047716.958061 timestamp_int = int(timestamp_float) self.assertTrue(util.is_timestamp(timestamp_int)) self.assertTrue(util.is_timestamp(timestamp_float)) self.assertFalse(util.is_timestamp(str(timestamp_int))) self.assertFalse(util.is_timestamp(str(timestamp_float))) self.assertFalse(util.is_timestamp(True)) self.assertFalse(util.is_timestamp(False)) full_datetime = "2019-06-23T13:12:42" self.assertFalse(util.is_timestamp(full_datetime)) overflow_timestamp_float = 99999999999999999999999999.99999999999999999999999999 with self.assertRaises((OverflowError, ValueError)): util.is_timestamp(overflow_timestamp_float) overflow_timestamp_int = int(overflow_timestamp_float) with self.assertRaises((OverflowError, ValueError)): util.is_timestamp(overflow_timestamp_int)
Add storage role to inspector
package cmd import ( "fmt" "io" "strings" "github.com/apprenda/kismatic/pkg/inspector/rule" ) func getNodeRoles(commaSepRoles string) ([]string, error) { roles := strings.Split(commaSepRoles, ",") for _, r := range roles { if r != "etcd" && r != "master" && r != "worker" && r != "ingress" && r != "storage" { return nil, fmt.Errorf("%s is not a valid node role", r) } } return roles, nil } func getRulesFromFileOrDefault(out io.Writer, file string) ([]rule.Rule, error) { var rules []rule.Rule var err error if file != "" { rules, err = rule.ReadFromFile(file) if err != nil { return nil, err } if ok := validateRules(out, rules); !ok { return nil, fmt.Errorf("rules read from %q did not pass validation", file) } } else { rules = rule.DefaultRules() } return rules, nil } func validateOutputType(outputType string) error { if outputType != "json" && outputType != "table" { return fmt.Errorf("output type %q not supported", outputType) } return nil }
package cmd import ( "fmt" "io" "strings" "github.com/apprenda/kismatic/pkg/inspector/rule" ) func getNodeRoles(commaSepRoles string) ([]string, error) { roles := strings.Split(commaSepRoles, ",") for _, r := range roles { if r != "etcd" && r != "master" && r != "worker" && r != "ingress" { return nil, fmt.Errorf("%s is not a valid node role", r) } } return roles, nil } func getRulesFromFileOrDefault(out io.Writer, file string) ([]rule.Rule, error) { var rules []rule.Rule var err error if file != "" { rules, err = rule.ReadFromFile(file) if err != nil { return nil, err } if ok := validateRules(out, rules); !ok { return nil, fmt.Errorf("rules read from %q did not pass validation", file) } } else { rules = rule.DefaultRules() } return rules, nil } func validateOutputType(outputType string) error { if outputType != "json" && outputType != "table" { return fmt.Errorf("output type %q not supported", outputType) } return nil }
Upgrade missing element log to error
(function() { var element = null; var nav_elements = document.querySelectorAll('.nav-item-container'); for (var i = 0; i < nav_elements.length; i++) { var current = nav_elements[i]; if (current.innerHTML == 'My Library') { element = current; break; } } if (element != null) { chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) { element.setAttribute('data-type', item.gpmDefaultLibraryView); }); } else { console.error('No element found; did Google change the page?'); } })();
(function() { var element = null; var nav_elements = document.querySelectorAll('.nav-item-container'); for (var i = 0; i < nav_elements.length; i++) { var current = nav_elements[i]; if (current.innerHTML == 'My Library') { element = current; break; } } if (element != null) { chrome.storage.sync.get({'gpmDefaultLibraryView': 'albums'}, function(item) { element.setAttribute('data-type', item.gpmDefaultLibraryView); }); } else { console.log('No element found; did Google change the page?'); } })();
Remove output_dir fixture from test
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 'tox.ini'), '-e', 'py' ]) except subprocess.CalledProcessError as e: pytest.fail(e) def test_run_cookiecutter_and_plugin_tests(cookies): """Create a new plugin via cookiecutter and run its tests.""" result = cookies.bake() assert result.project.basename == 'pytest-foobar' assert result.project.isdir() run_tox(str(result.project))
# -*- coding: utf-8 -*- """ test_create_template -------------------- """ import os import pytest import subprocess @pytest.fixture def output_dir(tmpdir): return str(tmpdir.mkdir('output')) def run_tox(plugin): """Run the tox suite of the newly created plugin.""" try: subprocess.check_call([ 'tox', plugin, '-c', os.path.join(plugin, 'tox.ini'), '-e', 'py' ]) except subprocess.CalledProcessError as e: pytest.fail(e) def test_run_cookiecutter_and_plugin_tests(cookies): """Create a new plugin via cookiecutter and run its tests.""" result = cookies.bake() assert result.project.basename == 'pytest-foobar' assert result.project.isdir() run_tox(str(result.project))
Add overlay option for debugging
const Environment = require('../environment') const { dev_server } = require('../config') const assetHost = require('../asset_host') const webpack = require('webpack') module.exports = class extends Environment { constructor() { super() if (dev_server.hmr) { this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin()) this.plugins.set('NamedModules', new webpack.NamedModulesPlugin()) } } toWebpackConfig() { const result = super.toWebpackConfig() if (dev_server.hmr) { result.output.filename = '[name]-[hash].js' } result.output.pathinfo = true result.devtool = 'cheap-eval-source-map' result.devServer = { host: dev_server.host, port: dev_server.port, https: dev_server.https, hot: dev_server.hmr, contentBase: assetHost.path, publicPath: assetHost.publicPath, clientLogLevel: 'none', compress: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, overlay: true, watchContentBase: true, watchOptions: { ignored: /node_modules/ }, stats: { errorDetails: true } } return result } }
const Environment = require('../environment') const { dev_server } = require('../config') const assetHost = require('../asset_host') const webpack = require('webpack') module.exports = class extends Environment { constructor() { super() if (dev_server.hmr) { this.plugins.set('HotModuleReplacement', new webpack.HotModuleReplacementPlugin()) this.plugins.set('NamedModules', new webpack.NamedModulesPlugin()) } } toWebpackConfig() { const result = super.toWebpackConfig() if (dev_server.hmr) { result.output.filename = '[name]-[hash].js' } result.output.pathinfo = true result.devtool = 'cheap-eval-source-map' result.devServer = { host: dev_server.host, port: dev_server.port, https: dev_server.https, hot: dev_server.hmr, contentBase: assetHost.path, publicPath: assetHost.publicPath, clientLogLevel: 'none', compress: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, watchOptions: { ignored: /node_modules/ }, stats: { errorDetails: true } } return result } }
Change the call of httpGet, now it will work with button
/** * Print the current url */ chrome.tabs.query({ active: true, lastFocusedWindow: true}, function(array_of_Tabs) { // Since there can only be one active tab in one active window, // the array has only one element var tab = array_of_Tabs[0]; var url = tab.url; console.log("new Current " + url); }); /** * add event listener to a group of buttuns */ var cpfValue = 3; function setCpfValue(newCpf) { cpfValue = newCpf; } function httpGet(cpf) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request xmlHttp.send( null ); console.log( xmlHttp.responseText); return xmlHttp.responseText; } document.addEventListener('DOMContentLoaded', function () { //console.log(document.querySelector('button')); //document.querySelector('button').addEventListener('click', httpGet(cpfValue)); var requestButton = document.getElementById('RequestJson'); requestButton.addEventListener("click", function(){ httpGet(cpfValue); }); }); // https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3
/** * Print the current url */ chrome.tabs.query({ active: true, lastFocusedWindow: true}, function(array_of_Tabs) { // Since there can only be one active tab in one active window, // the array has only one element var tab = array_of_Tabs[0]; var url = tab.url; console.log("new Current " + url); }); /** * add event listener to a group of buttuns */ var cpfValue = 3; function setCpfValue(newCpf) { cpfValue = newCpf; } function httpGet(cpf) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request xmlHttp.send( null ); console.log( xmlHttp.responseText); return xmlHttp.responseText; } document.addEventListener('DOMContentLoaded', function () { //console.log(document.querySelector('button')); //document.querySelector('button').addEventListener('click', httpGet(cpfValue)); document.getElementById('RequestJson').addEventListener('click', httpGet(cpfValue)); }); // https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3
Document that this part of the unit test code must remain in src/ git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@602096 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.jorphan.test; /** * Implement this interface to work with the AllTests class. This interface * allows AllTests to pass a configuration file to your application before * running the junit unit tests. * * @see AllTests * * N.B. This must be in the main src/ tree (not test/) because it is * implemented by JMeterUtils */ public interface UnitTestManager { /** * Your implementation will be handed the filename that was provided to * AllTests as a configuration file. It can hold whatever properties you * need to configure your system prior to the unit tests running. * * @param filename */ public void initializeProperties(String filename); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.jorphan.test; /** * Implement this interface to work with the AllTests class. This interface * allows AllTests to pass a configuration file to your application before * running the junit unit tests. * * @see AllTests * @author Michael Stover (mstover at apache.org) * @version $Revision$ */ public interface UnitTestManager { /** * Your implementation will be handed the filename that was provided to * AllTests as a configuration file. It can hold whatever properties you * need to configure your system prior to the unit tests running. * * @param filename */ public void initializeProperties(String filename); }
Fix incorrect call to database and sloppy callback
// FIXME: don't use hardcoded params var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; todo.getAll = function(callback) { var results = []; db.view('todos', 'all_todos', function(err, body) { for (var row of body.rows) { results.push(row.value); } callback(err, results); }); }; todo.addTask = function(task, callback) { db.insert(task, function(err, body) { if (err) { callback(err); } else { task._id = body.id; task._rev = body.rev; // assign a url based on id and commit back to database // FIXME: don't use hardcoded params task.url = 'http://localhost:3000/' + body.id; db.insert(task, function(err, body) { callback(err, task); }); } }); }; module.exports = todo;
// FIXME: don't use hardcoded params var nano = require('nano')('http://localhost:5984'); var db = nano.db.use('todo'); var todo = {}; todo.getAll = function(callback) { var results = []; db.view('todos', 'all_todos', function(err, body) { for (var row of body.rows) { results.push(row.value); } callback(err, results); }); }; todo.addTask = function(task, callback) { db.insert(task, function(err, body) { if (err) { callback(err); } else { task._id = body.id; task._rev = body.rev; // assign a url based on id and commit back to database // FIXME: don't use hardcoded params task.url = 'http://localhost:3000/' + body.id; todo.insert(task, function(err, body) { if (err) { callback(err); } else { callback(nil, task); } }); } }); }; module.exports = todo;
Add test for link redirect
from django.test import Client, TestCase from .models import Category, Link class CategoryModelTests(TestCase): def test_category_sort(self): Category(title='Test 2', slug='test2').save() Category(title='Test 1', slug='test1').save() self.assertEqual(['Test 1', 'Test 2'], map(str, Category.objects.all())) class LinkModelTests(TestCase): def setUp(self): self.url = 'https://github.com/' self.link = Link(title='GitHub', url=self.url) def test_track_link(self): self.assertEqual(self.link.get_absolute_url(), self.url) self.link.save() self.assertEqual(self.link.visits, 0) self.assertEqual(self.link.get_absolute_url(), '/links/go/%d/' % self.link.id) def test_link_title(self): self.assertEqual(str(self.link), 'GitHub') def test_increment_visits(self): self.link.save() client = Client() response = client.get('/links/go/%d/' % self.link.id) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], self.link.url) self.assertEqual(Link.objects.get(pk=self.link.id).visits, 1)
from django.test import TestCase from .models import Category, Link class CategoryModelTests(TestCase): def test_category_sort(self): Category(title='Test 2', slug='test2').save() Category(title='Test 1', slug='test1').save() self.assertEqual(['Test 1', 'Test 2'], map(str, Category.objects.all())) class LinkModelTests(TestCase): def setUp(self): self.url = 'https://github.com/' self.link = Link(title='GitHub', url=self.url) def test_track_link(self): self.assertEqual(self.link.get_absolute_url(), self.url) self.link.save() self.assertEqual(self.link.visits, 0) self.assertEqual(self.link.get_absolute_url(), '/links/go/%d/' % self.link.id) def test_link_title(self): self.assertEqual(str(self.link), 'GitHub')
Remove not needed callback arguments 💀
var buildFile = require('./build-file') var runGitCommand = require('./helpers/run-git-command') var COMMITHASH_COMMAND = 'rev-parse HEAD' var VERSION_COMMAND = 'describe --always' function GitRevisionPlugin (options) { this.gitWorkTree = options && options.gitWorkTree this.lightweightTags = options && options.lightweightTags || false this.commithashCommand = options && options.commithashCommand || COMMITHASH_COMMAND this.versionCommand = options && options.versionCommand || VERSION_COMMAND } GitRevisionPlugin.prototype.apply = function (compiler) { buildFile(compiler, this.gitWorkTree, this.commithashCommand, /\[git-revision-hash\]/gi, 'COMMITHASH' ) buildFile(compiler, this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : ''), /\[git-revision-version\]/gi, 'VERSION' ) } GitRevisionPlugin.prototype.commithash = function () { return runGitCommand( this.gitWorkTree, this.commithashCommand ) } GitRevisionPlugin.prototype.version = function () { return runGitCommand( this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : '') ) } module.exports = GitRevisionPlugin
var buildFile = require('./build-file') var runGitCommand = require('./helpers/run-git-command') var COMMITHASH_COMMAND = 'rev-parse HEAD' var VERSION_COMMAND = 'describe --always' function GitRevisionPlugin (options) { this.gitWorkTree = options && options.gitWorkTree this.lightweightTags = options && options.lightweightTags || false this.commithashCommand = options && options.commithashCommand || COMMITHASH_COMMAND this.versionCommand = options && options.versionCommand || VERSION_COMMAND } GitRevisionPlugin.prototype.apply = function (compiler) { buildFile(compiler, this.gitWorkTree, this.commithashCommand, /\[git-revision-hash\]/gi, 'COMMITHASH' ) buildFile(compiler, this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : ''), /\[git-revision-version\]/gi, 'VERSION' ) } GitRevisionPlugin.prototype.commithash = function (callback) { return runGitCommand( this.gitWorkTree, this.commithashCommand ) } GitRevisionPlugin.prototype.version = function (callback) { return runGitCommand( this.gitWorkTree, this.versionCommand + (this.lightweightTags ? ' --tags' : '') ) } module.exports = GitRevisionPlugin
API: Clear embargo fields once embargo processed
<?php /** * A queued job that publishes a target after a delay. * * @package advancedworkflow */ class WorkflowPublishTargetJob extends AbstractQueuedJob { public function __construct($obj = null, $type = null) { if ($obj) { $this->setObject($obj); $this->publishType = $type ? strtolower($type) : 'publish'; $this->totalSteps = 1; } } public function getTitle() { return "Scheduled $this->publishType of " . $this->getObject()->Title; } public function process() { if ($target = $this->getObject()) { if ($this->publishType == 'publish') { $target->PublishOnDate = ''; $target->writeWithoutVersion(); $target->doPublish(); } else if ($this->publishType == 'unpublish') { $target->UnPublishOnDate = ''; $target->writeWithoutVersion(); $target->doUnpublish(); } } $this->currentStep = 1; $this->isComplete = true; } }
<?php /** * A queued job that publishes a target after a delay. * * @package advancedworkflow */ class WorkflowPublishTargetJob extends AbstractQueuedJob { public function __construct($obj = null, $type = null) { if ($obj) { $this->setObject($obj); $this->publishType = $type ? strtolower($type) : 'publish'; $this->totalSteps = 1; } } public function getTitle() { return "Scheduled $this->publishType of " . $this->getObject()->Title; } public function process() { if ($target = $this->getObject()) { if ($this->publishType == 'publish') { $target->doPublish(); } else if ($this->publishType == 'unpublish') { $target->doUnpublish(); } } $this->currentStep = 1; $this->isComplete = true; } }
Change test to reflect changes to coords
const chai = require('chai') const assert = chai.assert; const sinon = require('sinon'); const Bumper = require("../lib/bumper") describe("Bumper", function(){ context("with assigned attributes", function(){ var bumper = new Bumper({minX: 0, minY:0, maxX:10, maxY:10}) it("should have an x min position", function(){ assert.equal(bumper.minX, 0) }) it("should have a y min position", function(){ assert.equal(bumper.minY, 0) }) it("should have an x max position", function(){ assert.equal(bumper.maxX, 10) }) it("should have a y max position", function(){ assert.equal(bumper.maxY, 10) }) it("should have a default color of white", function(){ assert.equal(bumper.color, "white") }); }); });
const chai = require('chai') const assert = chai.assert; const sinon = require('sinon'); const Bumper = require("../lib/bumper") describe("Bumper", function(){ context("with assigned attributes", function(){ var bumper = new Bumper(0,0,10,10) it("should have an x min position", function(){ assert.equal(bumper.minX, 0) }) it("should have a y min position", function(){ assert.equal(bumper.minY, 0) }) it("should have an x max position", function(){ assert.equal(bumper.maxX, 10) }) it("should have a y max position", function(){ assert.equal(bumper.maxY, 10) }) it("should have a default color of white", function(){ assert.equal(bumper.color, "white") }); }); });
Increase timeout for trakt.tv API calls
'use strict'; var Settings = require('./settings.js'); var ChromeStorage = require('./chrome-storage.js'); function Request() {}; Request._send = function _send(options, accessToken) { var xhr = new XMLHttpRequest(); xhr.open(options.method, options.url, true); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('trakt-api-key', Settings.clientId); xhr.setRequestHeader('trakt-api-version', Settings.apiVersion); xhr.timeout = 10000; // increase the timeout for trakt.tv calls if (accessToken) { xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); } xhr.onload = function() { if (this.status >= 200 && this.status < 400) { options.success.call(this, this.response); } else { options.error.call(this, this.status, this.responseText); } }; xhr.onerror = options.error; xhr.send(JSON.stringify(options.params)); }; Request.send = function send(options) { ChromeStorage.get('access_token', function(data) { Request._send(options, data.access_token); }.bind(this)); }; module.exports = Request;
'use strict'; var Settings = require('./settings.js'); var ChromeStorage = require('./chrome-storage.js'); function Request() {}; Request._send = function _send(options, accessToken) { var xhr = new XMLHttpRequest(); xhr.open(options.method, options.url, true); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('trakt-api-key', Settings.clientId); xhr.setRequestHeader('trakt-api-version', Settings.apiVersion); xhr.timeout = 4000; // increase the timeout for trakt.tv calls if (accessToken) { xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken); } xhr.onload = function() { if (this.status >= 200 && this.status < 400) { options.success.call(this, this.response); } else { options.error.call(this, this.status, this.responseText); } }; xhr.onerror = options.error; xhr.send(JSON.stringify(options.params)); }; Request.send = function send(options) { ChromeStorage.get('access_token', function(data) { Request._send(options, data.access_token); }.bind(this)); }; module.exports = Request;
Load default.js if it exists.
var pageMod = require('page-mod'), data = require('self').data, file = require('file'), url = require('url'); pageMod.PageMod({ include: "*", contentScriptWhen: 'ready', contentScriptFile: data.url('jquery-1.5.min.js'), contentScript: '(function($) {' + 'onMessage = function onMessage(script) { eval(script); };' + 'postMessage(document.URL);' + '}(jQuery.noConflict(true)));', onAttach: function onAttach(worker) { worker.on('message', function(data) { var domain = url.URL(data).host; if (domain.indexOf('www.') === 0) { domain = domain.substring(4, domain.length); } var files = ['default', domain]; for (var i=0; i < files.length; i++) { filename = '~/.js/' + files[i] + '.js'; if (file.exists(filename)) { worker.postMessage(file.read(filename)); } } }); } });
var pageMod = require('page-mod'), data = require('self').data, file = require('file'), url = require('url'); pageMod.PageMod({ include: "*", contentScriptWhen: 'ready', contentScriptFile: data.url('jquery-1.5.min.js'), contentScript: '(function($) {' + 'onMessage = function onMessage(script) { eval(script); };' + 'postMessage(document.URL);' + '}(jQuery.noConflict(true)));', onAttach: function onAttach(worker) { worker.on('message', function(data) { var domain = url.URL(data).host; if (domain.indexOf('www.') === 0) { domain = domain.substring(4, domain.length); } var filename = '~/.js/' + domain + '.js'; if (file.exists(filename)) { worker.postMessage(file.read(filename)); } }); } });
Add a border until we can theme this sucker
<?php function pubsites_content(&$a) { $dirmode = intval(get_config('system','directory_mode')); if(($dirmode == DIRECTORY_MODE_PRIMARY) || ($dirmode == DIRECTORY_MODE_STANDALONE)) { $url = z_root() . '/dirsearch'; } if(! $url) { $directory = find_upstream_directory($dirmode); if($directory) { $url = $directory['url'] . '/dirsearch'; } else { $url = DIRECTORY_FALLBACK_MASTER . '/dirsearch'; } } $url .= '/sites'; $o .= '<h1>' . t('Public Sites') . '</h1>'; $ret = z_fetch_url($url); if($ret['success']) { $j = json_decode($ret['body'],true); if($j) { $o .= '<table border="1"><tr><td>' . t('Site URL') . '</td><td>' . t('Access Type') . '</td><td>' . t('Registration Policy') . '</td></tr>'; foreach($j['sites'] as $jj) { $o .= '<tr><td>' . $jj['url'] . '</td><td>' . $jj['access'] . '</td><td>' . $jj['register'] . '</td></tr>'; } $o .= '</table>'; } } return $o; }
<?php function pubsites_content(&$a) { $dirmode = intval(get_config('system','directory_mode')); if(($dirmode == DIRECTORY_MODE_PRIMARY) || ($dirmode == DIRECTORY_MODE_STANDALONE)) { $url = z_root() . '/dirsearch'; } if(! $url) { $directory = find_upstream_directory($dirmode); if($directory) { $url = $directory['url'] . '/dirsearch'; } else { $url = DIRECTORY_FALLBACK_MASTER . '/dirsearch'; } } $url .= '/sites'; $o .= '<h1>' . t('Public Sites') . '</h1>'; $ret = z_fetch_url($url); if($ret['success']) { $j = json_decode($ret['body'],true); if($j) { $o .= '<table><tr><td>' . t('Site URL') . '</td><td>' . t('Access Type') . '</td><td>' . t('Registration Policy') . '</td></tr>'; foreach($j['sites'] as $jj) { $o .= '<tr><td>' . $jj['url'] . '</td><td>' . $jj['access'] . '</td><td>' . $jj['register'] . '</td></tr>'; } $o .= '</table>'; } } return $o; }
Remove support for Webpack 3.x and prior from `WatchTimestampsPlugin`.
const fs = require('fs'); /** A Webpack plugin to refresh file mtime values from disk before compiling. * This is used in order to account for SCSS-generated .d.ts files written * as part of compilation so they trigger only a single recompile per write. * * All credit for the technique and implementation goes to @reiv. See: * https://github.com/Jimdo/typings-for-css-modules-loader/issues/48#issuecomment-347036461 */ module.exports = class WatchTimestampsPlugin { constructor(patterns) { this.patterns = patterns; } apply(compiler) { compiler.plugin('watch-run', (watch, callback) => { const patterns = this.patterns; const timestamps = watch.fileTimestamps; Object.keys(timestamps).forEach(filepath => { if (patterns.some(pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat) === 0)) { let time = fs.statSync(filepath).mtime; if (timestamps instanceof Map) timestamps.set(filepath, time); else timestamps[filepath] = time; } }); callback(); }); } };
const fs = require('fs'); /** A Webpack plugin to refresh file mtime values from disk before compiling. * This is used in order to account for SCSS-generated .d.ts files written * as part of compilation so they trigger only a single recompile per write. * * All credit for the technique and implementation goes to @reiv. See: * https://github.com/Jimdo/typings-for-css-modules-loader/issues/48#issuecomment-347036461 */ module.exports = class WatchTimestampsPlugin { constructor(patterns) { this.patterns = patterns; } apply(compiler) { compiler.plugin('watch-run', (watch, callback) => { let patterns = this.patterns; let timestamps = watch.fileTimestamps || watch.compiler.fileTimestamps; Object.keys(timestamps).forEach(filepath => { if (patterns.some(pat => pat instanceof RegExp ? pat.test(filepath) : filepath.indexOf(pat) === 0)) { let time = fs.statSync(filepath).mtime; if (timestamps instanceof Map) timestamps.set(filepath, time); else timestamps[filepath] = time; } }); callback(); }); } };
Change path following import of build folder
import os,sys #General vars CURDIR=os.path.dirname(os.path.abspath(__file__)) TOPDIR=os.path.dirname(os.path.dirname(CURDIR)) DOWNLOAD_DIR=os.path.join(TOPDIR,'downloads') #Default vars PY_VER='Python27' BIN_DIR=os.path.join(TOPDIR,'bin') PY_DIR=os.path.join(BIN_DIR,PY_VER) #Don't mess with PYTHONHOME ############################################################ #Check environment settings in case they'e been overridden env=os.environ CURDIR=env.get('CURDIR',CURDIR) TOPDIR=env.get('TOPDIR',os.path.dirname(os.path.dirname(CURDIR))) DOWNLOAD_DIR=env.get('DOWNLOAD_DIR',DOWNLOAD_DIR) PY_VER=env.get('PY_VER',PY_VER) BIN_DIR=env.get('BIN_DIR',BIN_DIR) PY_DIR=env.get('PY_DIR',PY_DIR) #Hide from autocomplete IDEs del os del sys del env
import os,sys #General vars CURDIR=os.path.dirname(os.path.abspath(__file__)) TOPDIR=os.path.dirname(CURDIR) DOWNLOAD_DIR=TOPDIR+'\\downloads' #Default vars PY_VER='Python27' BIN_DIR=TOPDIR+'\\bin' PY_DIR=BIN_DIR+'\\'+PY_VER #Don't mess with PYTHONHOME ############################################################ #Check environment settings in case they'e been overridden env=os.environ CURDIR=env.get('CURDIR',CURDIR) TOPDIR=env.get('TOPDIR',os.path.dirname(CURDIR)) DOWNLOAD_DIR=env.get('DOWNLOAD_DIR',DOWNLOAD_DIR) PY_VER=env.get('PY_VER',PY_VER) BIN_DIR=env.get('BIN_DIR',BIN_DIR) PY_DIR=env.get('PY_DIR',PY_DIR) #Hide from autocomplete IDEs del os del sys del env
Update the sample proxy list
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://bit.ly/36GtZa1 * https://www.us-proxy.org/ * https://hidemy.name/en/proxy-list/ * http://free-proxy.cz/en/proxylist/country/all/https/ping/all """ PROXY_LIST = { "example1": "152.26.66.140:3128", # (Example) - set your own proxy here "example2": "64.235.204.107:8080", # (Example) - set your own proxy here "example3": "82.200.233.4:3128", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Send QR Code when riddle created
<?php /** * CodeMOOC QuizzleBot * =================== * UWiClab, University of Urbino * =================== * Command message processing functionality. */ /** * Processes commands. * @return bool True if the message was handled. */ function process_command($context, $text) { $command = extract_command($text); if($command === 'new' && $context->is_abmin()) { $last_open_riddle = get_last_open_riddle_id(); if($last_open_riddle === null) { // New question! $new_riddle_data = open_riddle(); Logger::info("New riddle ID: {$new_riddle_data[0]}", __FILE__, $context); $riddle_deeplink_url = get_riddle_qrcode_url($new_riddle_data[0]); telegram_send_photo($context->get_telegram_chat_id(), $riddle_deeplink_url, QUIZ_CREATED_OK . $new_riddle_data[1]); } else { $context->reply(QUIZ_ALREADY_OPEN); } return true; } else if($command === 'help') { $context->reply(COMMAND_HELP); return true; } return false; }
<?php /** * CodeMOOC QuizzleBot * =================== * UWiClab, University of Urbino * =================== * Command message processing functionality. */ /** * Processes commands. * @return bool True if the message was handled. */ function process_command($context, $text) { $command = extract_command($text); if($command === 'new' && $context->is_abmin()) { $last_open_riddle = get_last_open_riddle_id(); if($last_open_riddle === null) { // New question! $new_riddle_id = open_riddle(); Logger::info("New riddle ID: {$new_riddle_id}", __FILE__, $context); $context->reply(QUIZ_CREATED_OK); } else { $context->reply(QUIZ_ALREADY_OPEN); } return true; } else if($command === 'help') { $context->reply(COMMAND_HELP); return true; } return false; }
Update repository addresses and emails
#!/usr/bin/env python import os.path from distutils.core import setup README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read() CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ] import ptch VERSION = ptch.__version__ setup( name = "python-ptch", py_modules = ["ptch"], author = "Jerome Leclanche", author_email = "jerome@leclan.ch", classifiers = CLASSIFIERS, description = "Blizzard BSDIFF-based PTCH file format support", download_url = "https://github.com/jleclanche/python-ptch/tarball/master", long_description = README, url = "https://github.com/jleclanche/python-ptch", version = VERSION, )
#!/usr/bin/env python import os.path from distutils.core import setup README = open(os.path.join(os.path.dirname(__file__), "README.rst")).read() CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", ] import ptch VERSION = ptch.__version__ setup( name = "python-ptch", py_modules = ["ptch"], author = "Jerome Leclanche", author_email = "jerome.leclanche+python-ptch@gmail.com", classifiers = CLASSIFIERS, description = "Blizzard BSDIFF-based PTCH file format support", download_url = "http://github.com/Adys/python-ptch/tarball/master", long_description = README, url = "http://github.com/Adys/python-ptch", version = VERSION, )
Remove extra space at EOL
<?php namespace Test\View; use Slim\Slim; use Twig\Test\IntegrationTestCase; use View\FiltersExtension; use View\FunctionsExtension; class TwigExtensionIntegrationTest extends IntegrationTestCase { private $slim; public function setUp(): void { $this->slim = $this->getMockBuilder(Slim::class) ->disableOriginalConstructor() ->getMock(); $this->slim->method('urlFor') ->willReturn('https://www.joind.in'); parent::setUp(); } protected function getExtensions(): array { return [ new FiltersExtension(), new FunctionsExtension($this->slim) ]; } protected function getFixturesDir(): string { return dirname(__FILE__).'/Fixtures/'; } }
<?php namespace Test\View; use Slim\Slim; use Twig\Test\IntegrationTestCase; use View\FiltersExtension; use View\FunctionsExtension; class TwigExtensionIntegrationTest extends IntegrationTestCase { private $slim; public function setUp(): void { $this->slim = $this->getMockBuilder(Slim::class) ->disableOriginalConstructor() ->getMock(); $this->slim->method('urlFor') ->willReturn('https://www.joind.in'); parent::setUp(); } protected function getExtensions(): array { return [ new FiltersExtension(), new FunctionsExtension($this->slim) ]; } protected function getFixturesDir(): string { return dirname(__FILE__).'/Fixtures/'; } }
Fix a typo in the contents constraints creation.
#------------------------------------------------------------------------------ # Copyright (c) 2013, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ STRENGTHS = set(['required', 'strong', 'medium', 'weak']) def add_symbolic_constraints(namespace): """ Add constraints to a namespace that are LinearExpressions of basic constraints. """ bottom = namespace.bottom left = namespace.left width = namespace.layout_width height = namespace.layout_height namespace.right = left + width namespace.top = bottom + height namespace.h_center = left + width / 2.0 namespace.v_center = bottom + height / 2.0 def add_symbolic_contents_constraints(namespace): """ Add constraints to a namespace that are LinearExpressions of basic constraints. """ left = namespace.contents_left right = namespace.contents_right top = namespace.contents_top bottom = namespace.contents_bottom namespace.contents_width = right - left namespace.contents_height = top - bottom namespace.contents_v_center = bottom + namespace.contents_height / 2.0 namespace.contents_h_center = left + namespace.contents_width / 2.0
#------------------------------------------------------------------------------ # Copyright (c) 2013, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ STRENGTHS = set(['required', 'strong', 'medium', 'weak']) def add_symbolic_constraints(namespace): """ Add constraints to a namespace that are LinearExpressions of basic constraints. """ bottom = namespace.bottom left = namespace.left width = namespace.layout_width height = namespace.layout_height namespace.right = left + width namespace.top = bottom + height namespace.h_center = left + width / 2.0 namespace.v_center = bottom + height / 2.0 def add_symbolic_contents_constraints(namespace): """ Add constraints to a namespace that are LinearExpressions of basic constraints. """ left = namespace.contents_left right = namespace.contents_right top = namespace.contents_top bottom = namespace.contents_bottom namespace.contents_width = left - right namespace.contents_height = top - bottom namespace.contents_v_center = bottom + namespace.contents_height / 2.0 namespace.contents_h_center = left + namespace.contents_width / 2.0
Set fallback to true on get text to avoid crash on missing language file
# -*- coding: utf-8 -*- import os import config import gettext # Change this variable to your app name! # The translation files will be under # @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo APP_NAME = "simpleValidator" LOCALE_DIR = os.path.abspath('lang') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ DEFAULT_LANGUAGE = config.LOCALE #lc, encoding = locale.getdefaultlocale() #if lc: # languages = [lc] defaultlang = gettext.translation(APP_NAME, LOCALE_DIR, languages=DEFAULT_LANGUAGE, fallback=True) def switch_language(lang): global defaultlang defaultlang = gettext.translation(APP_NAME, LOCALE_DIR, languages=[lang], fallback=True)
# -*- coding: utf-8 -*- import os import config import gettext # Change this variable to your app name! # The translation files will be under # @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@APP_NAME@.mo APP_NAME = "simpleValidator" LOCALE_DIR = os.path.abspath('lang') # .mo files will then be located in APP_Dir/i18n/LANGUAGECODE/LC_MESSAGES/ DEFAULT_LANGUAGE = config.LOCALE #lc, encoding = locale.getdefaultlocale() #if lc: # languages = [lc] defaultlang = gettext.translation(APP_NAME, LOCALE_DIR, languages=DEFAULT_LANGUAGE, fallback=False) def switch_language(lang): global defaultlang defaultlang = gettext.translation(APP_NAME, LOCALE_DIR, languages=[lang], fallback=False)
Add URL for django admin access to screenshots
from django.conf.urls import patterns, include, url from django.views.generic.base import RedirectView from django.conf import settings from django.contrib import admin admin.autodiscover() from . import views from projects.views import screenshot urlpatterns = patterns('', # Examples: # url(r'^blog/', include('blog.urls')), url(r'^$', 'narcis.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/favicon.ico')), url(r'^projects/', include('projects.urls')), # Access controlled screenshot images url(r'^{0}[0-9]+/[0-9]+/[0-9]+/(?P<id>[0-9a-f\-]+)'.format(settings.PRIVATE_SCREENSHOT_URL.lstrip('/')), screenshot), url(r'^{0}(?P<id>[0-9a-f\-]+)'.format(settings.PRIVATE_SCREENSHOT_URL.lstrip('/')), screenshot), )
from django.conf.urls import patterns, include, url from django.views.generic.base import RedirectView from django.conf import settings from django.contrib import admin admin.autodiscover() from . import views from projects.views import screenshot urlpatterns = patterns('', # Examples: # url(r'^blog/', include('blog.urls')), url(r'^$', 'narcis.views.home', name='home'), url(r'^admin/', include(admin.site.urls)), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/favicon.ico')), url(r'^projects/', include('projects.urls')), # Access controlled screenshot images url(r'^{0}(?P<id>[0-9a-f\-]+)'.format(settings.PRIVATE_SCREENSHOT_URL.lstrip('/')), screenshot), )
Fix console output bug in history
(function() { angular .module('history') .controller('HistoryController', HistoryController); HistoryController.$inject = ['$scope', '$state', 'localStorage', 'HistoryService', 'SettingsService']; function HistoryController($scope, $state, localStorage, HistoryService, SettingsService) { $scope.history = HistoryService; $scope.filter = filter; $scope.loadMore = loadMore; $scope.refresh = refresh; // load on entering view $scope.$on('$ionicView.beforeEnter', function() { // send to login screen if they haven't logged in yet if (!SettingsService.loggedIn) SettingsService.reallyLogOut(); refresh(); }); function filter() { console.log('Filter yo'); } function loadMore() { // this is necessary because the loadMore function may just // return if there are no games loaded yet, so we can't expect // a promise, so we must check for one. var loadMore = HistoryService.loadMore(); if (loadMore) loadMore.then(done); } function refresh() { HistoryService.refresh().then(done); } function done() { $scope.$broadcast('scroll.refreshComplete'); $scope.$broadcast('scroll.infiniteScrollComplete'); } } })();
(function() { angular .module('history') .controller('HistoryController', HistoryController); HistoryController.$inject = ['$scope', '$state', 'localStorage', 'HistoryService', 'SettingsService']; function HistoryController($scope, $state, localStorage, HistoryService, SettingsService) { $scope.history = HistoryService; $scope.filter = filter; $scope.loadMore = loadMore; $scope.refresh = refresh; // load on entering view $scope.$on('$ionicView.beforeEnter', function() { // send to login screen if they haven't logged in yet if (!SettingsService.loggedIn) SettingsService.reallyLogOut(); refresh(); }); function filter() { console.log('Filter yo'); } function loadMore() { HistoryService.loadMore().then(done); } function refresh() { HistoryService.refresh().then(done); } function done() { $scope.$broadcast('scroll.refreshComplete'); $scope.$broadcast('scroll.infiniteScrollComplete'); } } })();
Use formatted log values instead of raw values when emitting to Socket.io, to avoid errors when exceptions are thrown and Socket.io tries to pack them
<?php /** * @file */ namespace CultuurNet\UDB3\Monolog; use Monolog\Formatter\FormatterInterface; use Monolog\Formatter\NormalizerFormatter; use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger; use SocketIO\Emitter; class SocketIOEmitterHandler extends AbstractProcessingHandler { /** * @var Emitter */ protected $emitter; /** * @param Emitter $emitter * @param integer $level The minimum logging level at which this handler will be triggered * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not */ public function __construct(Emitter $emitter, $level = Logger::DEBUG, $bubble = true) { parent::__construct( $level, $bubble ); $this->emitter = $emitter; } /** * {@inheritdoc} */ protected function write(array $record) { $event = $record['formatted']['message']; $data = $record['formatted']['context']; $this->emitter->emit($event, $data); } /** * @inheritdoc */ protected function getDefaultFormatter() { return new NormalizerFormatter(); } }
<?php /** * @file */ namespace CultuurNet\UDB3\Monolog; use Monolog\Handler\AbstractProcessingHandler; use Monolog\Logger; use SocketIO\Emitter; class SocketIOEmitterHandler extends AbstractProcessingHandler { /** * @var Emitter */ protected $emitter; /** * @param Emitter $emitter * @param integer $level The minimum logging level at which this handler will be triggered * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not */ public function __construct(Emitter $emitter, $level = Logger::DEBUG, $bubble = true) { parent::__construct( $level, $bubble ); $this->emitter = $emitter; } /** * {@inheritdoc} */ protected function write(array $record) { $event = $record['formatted']['message']; $data = $record['formatted']['context']; $this->emitter->emit($event, $data); } }
Add reverse relationship serializer to Category
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories')
from .models import Category, Keyword, Subcategory from rest_framework import serializers class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name')
chore: Fix lint problem in cleanup-plugin
function cleanupPlugins(resolve, reject) { 'use strict'; if (!axe._audit) { throw new Error('No audit configured'); } var q = axe.utils.queue(); // If a plugin fails it's cleanup, we still want the others to run var cleanupErrors = []; Object.keys(axe.plugins).forEach(function (key) { q.defer(function (res) { var rej = function (err) { cleanupErrors.push(err); res(); }; try { axe.plugins[key].cleanup(res, rej); } catch(err) { rej(err); } }); }); var flattenedTree = axe.utils.getFlattenedTree(document.body); axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function (node) { q.defer(function (res, rej) { return axe.utils.sendCommandToFrame(node.actualNode, { command: 'cleanup-plugin' }, res, rej); }); }); q.then(function (results) { if (cleanupErrors.length === 0) { resolve(results); } else { reject(cleanupErrors); } }) .catch(reject); } axe.cleanup = cleanupPlugins;
function cleanupPlugins(resolve, reject) { 'use strict'; if (!axe._audit) { throw new Error('No audit configured'); } var q = axe.utils.queue(); // If a plugin fails it's cleanup, we still want the others to run var cleanupErrors = []; Object.keys(axe.plugins).forEach(function (key) { q.defer(function (res) { var rej = function (err) { cleanupErrors.push(err); res(); }; try { axe.plugins[key].cleanup(res, rej); } catch(err) { rej(err); } }); }); var flattenedTree = axe.utils.getFlattenedTree(document.body) axe.utils.querySelectorAll(flattenedTree, 'iframe, frame').forEach(function (node) { q.defer(function (res, rej) { return axe.utils.sendCommandToFrame(node.actualNode, { command: 'cleanup-plugin' }, res, rej); }); }); q.then(function (results) { if (cleanupErrors.length === 0) { resolve(results); } else { reject(cleanupErrors); } }) .catch(reject); } axe.cleanup = cleanupPlugins;
Add "hurt" flag to Bleed effect So you can use the effect without the hurt part.
package de.slikey.effectlib.effect; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Entity; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.RandomUtils; public class BleedEntityEffect extends EntityEffect { public boolean hurt = true; /** * Duration in ticks, the blood-particles take to despawn. */ public int duration = 10; /** * Color of blood. Default is red (152) */ public int color = 152; public BleedEntityEffect(EffectManager effectManager, Entity entity) { super(effectManager, entity); type = EffectType.REPEATING; period = 4; iterations = 25; } @Override public void onRun() { // Location to spawn the blood-item. Location spawn = entity.getLocation(); spawn.add(0, RandomUtils.random.nextFloat() * 1.75f, 0); spawn.getWorld().playEffect(spawn, Effect.STEP_SOUND, 152); if (hurt) { entity.playEffect(org.bukkit.EntityEffect.HURT); } } }
package de.slikey.effectlib.effect; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Entity; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.RandomUtils; public class BleedEntityEffect extends EntityEffect { /** * Duration in ticks, the blood-particles take to despawn. */ public int duration = 10; /** * Color of blood. Default is red (152) */ public int color = 152; public BleedEntityEffect(EffectManager effectManager, Entity entity) { super(effectManager, entity); type = EffectType.REPEATING; period = 4; iterations = 25; } @Override public void onRun() { // Location to spawn the blood-item. Location spawn = entity.getLocation(); spawn.add(0, RandomUtils.random.nextFloat() * 1.75f, 0); spawn.getWorld().playEffect(spawn, Effect.STEP_SOUND, 152); entity.playEffect(org.bukkit.EntityEffect.HURT); } }
Rework imports and ignore known mypy issues
# Copyright 2018 Donald Stufft and individual contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __copyright__ = "Copyright 2019 Donald Stufft and individual contributors" try: # https://github.com/python/mypy/issues/1393 from importlib.metadata import metadata # type: ignore except ImportError: # https://github.com/python/mypy/issues/1153 from importlib_metadata import metadata # type: ignore twine_metadata = metadata('twine') __title__ = twine_metadata['name'] __summary__ = twine_metadata['summary'] __uri__ = twine_metadata['home-page'] __version__ = twine_metadata['version'] __author__ = twine_metadata['author'] __email__ = twine_metadata['author-email'] __license__ = twine_metadata['license']
# Copyright 2018 Donald Stufft and individual contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __copyright__ = "Copyright 2019 Donald Stufft and individual contributors" try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata metadata = importlib_metadata.metadata('twine') __title__ = metadata['name'] __summary__ = metadata['summary'] __uri__ = metadata['home-page'] __version__ = metadata['version'] __author__ = metadata['author'] __email__ = metadata['author-email'] __license__ = metadata['license']
Put numpy namespace in scipy for backward compatibility... git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@1530 d6536bca-fef9-0310-8506-e4c0a848fbcf
"""\ SciPy --- A scientific computing package for Python =================================================== You can support the development of SciPy by purchasing documentation at http://www.trelgol.com It is being distributed for a fee for a limited time to try and raise money for development. Documentation is also available in the docstrings. Available subpackages --------------------- """ try: import pkg_resources as _pr # activate namespace packages (manipulates __path__) del _pr except ImportError: pass from numpy import show_config as show_numpy_config if show_numpy_config is None: raise ImportError,"Cannot import scipy when running from numpy source directory." from numpy import __version__ as __numpy_version__ from __config__ import show as show_config from version import version as __version__ import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni import os as _os SCIPY_IMPORT_VERBOSE = int(_os.environ.get('SCIPY_IMPORT_VERBOSE','0')) pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True) del _os from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') import numpy as _num from numpy import * __all__ += _num.__all__ del _num __doc__ += pkgload.get_pkgdocs()
"""\ SciPy --- A scientific computing package for Python =================================================== You can support the development of SciPy by purchasing documentation at http://www.trelgol.com It is being distributed for a fee for a limited time to try and raise money for development. Documentation is also available in the docstrings. Available subpackages --------------------- """ try: import pkg_resources as _pr # activate namespace packages (manipulates __path__) del _pr except ImportError: pass from numpy import show_config as show_numpy_config if show_numpy_config is None: raise ImportError,"Cannot import scipy when running from numpy source directory." from numpy import __version__ as __numpy_version__ from __config__ import show as show_config from version import version as __version__ import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni import os as _os SCIPY_IMPORT_VERBOSE = int(_os.environ.get('SCIPY_IMPORT_VERBOSE','0')) pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True) del _os from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') __doc__ += pkgload.get_pkgdocs()
Allow method PATCH in cors
require('babel-register') import Koa from 'koa' import cors from 'koa2-cors' import Router from 'koa-router' import bodyParser from 'koa-bodyparser' import serve from 'koa-static' import mongoose from 'mongoose' import error from './middlewares/error' import logger from './middlewares/logger' import route from './routes' import { DATABASE, NODE_ENV, ALLOW_ORIGIN } from '../.env' mongoose.Promise = global.Promise mongoose.connect(DATABASE, { promiseLibrary: global.Promise, config: { autoIndex: NODE_ENV !== 'production' } }) const app = new Koa() const router = new Router() app.use(error()) app.use( cors({ origin: ALLOW_ORIGIN, methods: 'GET,HEAD,PUT,PATCH,POST,DELETE' }) ) app.use(logger()) app.use(serve('assets')) app.use(bodyParser()) route(router) app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3001)
require('babel-register') import Koa from 'koa' import cors from 'koa2-cors' import Router from 'koa-router' import bodyParser from 'koa-bodyparser' import serve from 'koa-static' import mongoose from 'mongoose' import error from './middlewares/error' import logger from './middlewares/logger' import route from './routes' import { DATABASE, NODE_ENV, ALLOW_ORIGIN } from '../.env' mongoose.Promise = global.Promise mongoose.connect(DATABASE, { promiseLibrary: global.Promise, config: { autoIndex: NODE_ENV !== 'production' } }) const app = new Koa() const router = new Router() app.use(error()) app.use(cors({ origin: ALLOW_ORIGIN })) app.use(logger()) app.use(serve('assets')) app.use(bodyParser()) route(router) app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3001)
Add depots into Import and increase mime version to 2.2
package fi.cosky.sdk; /* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ import java.util.List; public class ImportData extends BaseData { public static final String MimeType = "application/vnd.jyu.nfleet.import"; public static final double MimeVersion = 2.2; private int VersionNumber; private int ErrorCount; private String State; private List<VehicleError> Vehicles; private List<TaskError> Tasks; private List<DepotError> Depots; public int getVersionNumber() { return VersionNumber; } public void setVersionNumber(int versionNumber) { VersionNumber = versionNumber; } public int getErrorCount() { return ErrorCount; } public void setErrorCount(int errorCount) { ErrorCount = errorCount; } public String getState() { return State; } public void setState(String state) { State = state; } public List<VehicleError> getVehicles() { return Vehicles; } public void setVehicles(List<VehicleError> vehicles) { Vehicles = vehicles; } public List<TaskError> getTasks() { return Tasks; } public void setTasks(List<TaskError> tasks) { Tasks = tasks; } public List<DepotError> getDepots() { return Depots; } public void setDepots(List<DepotError> depots) { Depots = depots; } }
package fi.cosky.sdk; /* * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ import java.util.List; public class ImportData extends BaseData { public static final String MimeType = "application/vnd.jyu.nfleet.import"; public static final double MimeVersion = 2.1; private int VersionNumber; private int ErrorCount; private String State; private List<VehicleError> Vehicles; private List<TaskError> Tasks; public int getVersionNumber() { return VersionNumber; } public void setVersionNumber(int versionNumber) { VersionNumber = versionNumber; } public int getErrorCount() { return ErrorCount; } public void setErrorCount(int errorCount) { ErrorCount = errorCount; } public String getState() { return State; } public void setState(String state) { State = state; } public List<VehicleError> getVehicles() { return Vehicles; } public void setVehicles(List<VehicleError> vehicles) { Vehicles = vehicles; } public List<TaskError> getTasks() { return Tasks; } public void setTasks(List<TaskError> tasks) { Tasks = tasks; } }
Fix Travis errors on recent Go
package main import ( "flag" "image" "log" "os" "github.com/pixiv/go-libjpeg/jpeg" ) func main() { flag.Parse() file := flag.Arg(0) io, err := os.Open(file) if err != nil { log.Fatalln("Can't open file: ", file) } img, err := jpeg.Decode(io, &jpeg.DecoderOptions{}) if img == nil { log.Fatalln("Got nil") } if err != nil { log.Fatalf("Got Error: %v", err) } // // write your code here ... // switch img.(type) { case *image.YCbCr: log.Println("decoded YCbCr") case *image.Gray: log.Println("decoded Gray") default: log.Println("unknown format") } }
package main import ( "flag" "image" "log" "os" "github.com/pixiv/go-libjpeg/jpeg" ) func main() { flag.Parse() file := flag.Arg(0) io, err := os.Open(file) if err != nil { log.Fatalln("Can't open file: ", file) } img, err := jpeg.Decode(io, &jpeg.DecoderOptions{}) if img == nil { log.Fatalln("Got nil") } if err != nil { log.Fatalln("Got Error: %v", err) } // // write your code here ... // switch img.(type) { case *image.YCbCr: log.Println("decoded YCbCr") case *image.Gray: log.Println("decoded Gray") default: log.Println("unknown format") } }
Add GraphQL type for ContentType
import graphene from django.contrib.contenttypes.models import ContentType from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) # # Base types # class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ custom_fields = GenericScalar() class Meta: abstract = True def resolve_custom_fields(self, info): return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all() # # Miscellaneous types # class ContentTypeType(DjangoObjectType): class Meta: model = ContentType fields = ('id', 'app_label', 'model')
import graphene from graphene.types.generic import GenericScalar from graphene_django import DjangoObjectType __all__ = ( 'BaseObjectType', 'ObjectType', 'TaggedObjectType', ) class BaseObjectType(DjangoObjectType): """ Base GraphQL object type for all NetBox objects """ class Meta: abstract = True @classmethod def get_queryset(cls, queryset, info): # Enforce object permissions on the queryset return queryset.restrict(info.context.user, 'view') class ObjectType(BaseObjectType): """ Extends BaseObjectType with support for custom field data. """ # custom_fields = GenericScalar() class Meta: abstract = True # def resolve_custom_fields(self, info): # return self.custom_field_data class TaggedObjectType(ObjectType): """ Extends ObjectType with support for Tags """ tags = graphene.List(graphene.String) class Meta: abstract = True def resolve_tags(self, info): return self.tags.all()
Add etc/* files to wheel
from setuptools import setup, find_packages import sys install_requires_list = [ 'falcon>=0.1.8', 'requests', 'six>=1.4.1', 'oslo.config>=1.2.0', 'softlayer', 'pycrypto', 'iso8601', ] if sys.version_info[0] < 3: install_requires_list.append('py2-ipaddress') setup( name='jumpgate', version='0.1', description='OpenStack Transation Layer for cloud providers', long_description=open('README.rst', 'r').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 3.3', ], author_email='innovation@softlayer.com', url='http://sldn.softlayer.com', license='MIT', packages=find_packages(exclude=['*.tests']), data_files=[('etc', [ 'etc/identity.templates', 'etc/identity_v3.templates', 'etc/jumpgate.conf', 'etc/tempest.conf.sample' ])], include_package_data=True, zip_safe=False, install_requires=install_requires_list, setup_requires=[], test_suite='nose.collector', entry_points={'console_scripts': ['jumpgate = jumpgate.cmd_main:main']} )
from setuptools import setup, find_packages import sys install_requires_list = [ 'falcon>=0.1.8', 'requests', 'six>=1.4.1', 'oslo.config>=1.2.0', 'softlayer', 'pycrypto', 'iso8601', ] if sys.version_info[0] < 3: install_requires_list.append('py2-ipaddress') setup( name='jumpgate', version='0.1', description='OpenStack Transation Layer for cloud providers', long_description=open('README.rst', 'r').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Programming Language :: Python :: 3.3', ], author_email='innovation@softlayer.com', url='http://sldn.softlayer.com', license='MIT', packages=find_packages(exclude=['*.tests']), include_package_data=True, zip_safe=False, install_requires=install_requires_list, setup_requires=[], test_suite='nose.collector', entry_points={'console_scripts': ['jumpgate = jumpgate.cmd_main:main']} )
Use query parameters to limit results
from flask import Flask from flask import render_template from flask import request import argparse import games import json GAMES_COUNT = 100 app = Flask(__name__) @app.route("/") def index(): return render_template('games_list.html') @app.route("/api/") def games_api(): limit = request.args.get('limit') or GAMES_COUNT skip = request.args.get('skip') or 0 return json.dumps(game_list[int(skip):int(skip)+int(limit)]) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("players", type=file, help="JSON file with a list of players") args = parser.parse_args() with args.players as players_file: players = json.load(players_file) game_gen = games.game_data(players, GAMES_COUNT) game_list = list(game_gen) app.run(debug=True)
from flask import Flask from flask import render_template import argparse import games import json GAMES_COUNT = 100 app = Flask(__name__) @app.route("/") def index(): return render_template('games_list.html') @app.route("/api/") def games_api(): return json.dumps(game_list) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("players", type=file, help="JSON file with a list of players") args = parser.parse_args() with args.players as players_file: players = json.load(players_file) game_gen = games.game_data(players, GAMES_COUNT) game_list = list(game_gen) app.run(debug=True)
Add call controller in method start app
<?php namespace Uphp\web; use \UPhp\ActionDispach\Routes as Route; use \UPhp\ActionController\ActionController; class Application { public function __construct() { set_exception_handler("src\uphpExceptionHandler"); set_error_handler("src\uphpErrorHandler"); } public function start($config) { //carregando os initializers $this->getInitializersFiles(); $this->getRoutes(); ActionController::callController($config); } private function getInitializersFiles() { $path = "config/initializers/"; $directory = dir($path); while ($file = $directory -> read()) { if ($file != "." && $file != "..") { require($path . $file); } } $directory->close(); } private function getRoutes() { return require("config/routes.php"); } }
<?php namespace Uphp\web; use \UPhp\ActionDispach\Routes as Route; use \UPhp\ActionController\ActionController; class Application { public function __construct() { set_exception_handler("src\uphpExceptionHandler"); set_error_handler("src\uphpErrorHandler"); } public function start($config) { //carregando os initializers $this->getInitializersFiles(); $this->getRoutes(); ActionController::callController($config); } private function getInitializersFiles() { $path = "config/initializers/"; $directory = dir($path); while ($file = $directory -> read()) { if ($file != "." && $file != "..") { require($path . $file); } } $directory->close(); } private function getRoutes() { return require("config/routes.php"); } }
Add new line on the end of every message
'use strict'; const dateformat = require('dateformat'); const directory = require('./directory'); const fs = require('fs'); const path = require('path'); module.exports = { '_get_message': function (data) { const hour = dateformat('HH:MM:ss'); return '[' + hour + ']: ' + data + '\n'; }, 'log': function (data, verbose, callback) { if (!callback) { callback = function () {}; } var log_path = directory.logs(); ['yyyy', 'mm'].forEach(function (part) { log_path = path.join(log_path, dateformat(part)); if (fs.existsSync(log_path) === false) { fs.mkdirSync(log_path); } }); const filename = dateformat('dd') + '.log'; log_path = path.join(log_path, filename); var message = this._get_message(data); if (verbose) { console.log(message); } fs.appendFile(log_path, message, null, callback); } };
'use strict'; const dateformat = require('dateformat'); const directory = require('./directory'); const fs = require('fs'); const path = require('path'); module.exports = { '_get_message': function (data) { const hour = dateformat('HH:MM:ss'); return '[' + hour + ']: ' + data; }, 'log': function (data, verbose, callback) { if (!callback) { callback = function () {}; } var log_path = directory.logs(); ['yyyy', 'mm'].forEach(function (part) { log_path = path.join(log_path, dateformat(part)); if (fs.existsSync(log_path) === false) { fs.mkdirSync(log_path); } }); const filename = dateformat('dd') + '.log'; log_path = path.join(log_path, filename); var message = this._get_message(data); if (verbose) { console.log(message); } fs.appendFile(log_path, message, null, callback); } };
Fix typos in Swedish weekdays translation
// Swedish $.extend( $.fn.pickadate.defaults, { monthsFull: [ 'januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december' ], monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'söndag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag' ], weekdaysShort: [ 'sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör' ], firstDay: 1, format: 'd/m yyyy', formatSubmit: 'yyyy-mm-dd' })
// Swedish $.extend( $.fn.pickadate.defaults, { monthsFull: [ 'januari', 'februari', 'mars', 'april', 'maj', 'juni', 'juli', 'augusti', 'september', 'oktober', 'november', 'december' ], monthsShort: [ 'jan', 'feb', 'mar', 'apr', 'maj', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'dec' ], weekdaysFull: [ 'söödag', 'måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lö̈ödag' ], weekdaysShort: [ 'sön', 'mån', 'tis', 'ons', 'tor', 'fre', 'lör' ], firstDay: 1, format: 'd/m yyyy', formatSubmit: 'yyyy-mm-dd' })
Disable troublesome imports for now
import { Controller } from 'stimulus' // import '@ap-spectrum-web-components/slider' // import '@spectrum-web-components/theme/lib/theme-lightest' // import '@spectrum-web-components/theme/lib/scale-large' // import '@spectrum-web-components/theme/lib/theme' export default class extends Controller { static targets = ['image'] connect() { this.changeQuality() this.scale = this.data.get('scale').split(',') } changeQuality(event) { let quality = this.data.get('quality') let newQuality if (event) { newQuality = this.scale[Number.parseInt(event.target.value, 10)] } else { newQuality = quality } if (event && quality === newQuality) { return } else { this.data.set('quality', newQuality) } this.imageTarget.src = this.baseSrc().replace('??', newQuality) } baseSrc() { return this.imageTarget.dataset.src } }
import { Controller } from 'stimulus' import '@ap-spectrum-web-components/slider' import '@spectrum-web-components/theme/lib/theme-lightest' import '@spectrum-web-components/theme/lib/scale-large' import '@spectrum-web-components/theme/lib/theme' export default class extends Controller { static targets = ['image'] connect() { this.changeQuality() this.scale = this.data.get('scale').split(',') } changeQuality(event) { let quality = this.data.get('quality') let newQuality if (event) { newQuality = this.scale[Number.parseInt(event.target.value, 10)] } else { newQuality = quality } if (event && quality === newQuality) { return } else { this.data.set('quality', newQuality) } this.imageTarget.src = this.baseSrc().replace('??', newQuality) } baseSrc() { return this.imageTarget.dataset.src } }
Fix Travis build by using require("../main") instead of require("recast").
var assert = require("assert"), fs = require("fs"), path = require("path"); function identity(ast, callback) { assert.deepEqual(ast.original, ast); callback(ast); } function testFile(t, path) { fs.readFile(path, "utf-8", function(err, source) { assert.equal(err, null); assert.strictEqual(typeof source, "string"); require("../main").runString(source, identity, { writeback: function(code) { assert.strictEqual(source, code); t.finish(); } }); }); } function addTest(name) { exports["test " + name] = function(t) { testFile(t, path.join(__dirname, "..", name + ".js")); }; } // Add more tests here as need be. addTest("test/data/regexp-props"); addTest("test/data/empty"); addTest("test/data/jquery-1.9.1"); addTest("test/lines"); addTest("lib/lines"); addTest("lib/printer");
var assert = require("assert"), fs = require("fs"), path = require("path"); function identity(ast, callback) { assert.deepEqual(ast.original, ast); callback(ast); } function testFile(t, path) { fs.readFile(path, "utf-8", function(err, source) { assert.equal(err, null); assert.strictEqual(typeof source, "string"); require("recast").runString(source, identity, { writeback: function(code) { assert.strictEqual(source, code); t.finish(); } }); }); } function addTest(name) { exports["test " + name] = function(t) { testFile(t, path.join(__dirname, "..", name + ".js")); }; } // Add more tests here as need be. addTest("test/data/regexp-props"); addTest("test/data/empty"); addTest("test/data/jquery-1.9.1"); addTest("test/lines"); addTest("lib/lines"); addTest("lib/printer");
Remove buttons added in the wrong step.
define(function (require, exports, module) { var definition = ['todoList']; var getTemplate = function () { var template = ''; template += '<ul>'; template += ' <li ng-repeat="task in tasks track by task.id">'; template += ' <span ng-bind="task.title"></span>'; template += ' </li>'; template += '</ul>'; return template; }; var TodoListDirective = function (Tasks) { return { restrict: 'E', // AEC scope: {}, template: getTemplate(), link: function (scope, element, attrs) { scope.tasks = Tasks; } }; }; TodoListDirective.$inject = ['Tasks']; definition.push(TodoListDirective); return definition; });
define(function (require, exports, module) { var definition = ['todoList']; var getTemplate = function () { var template = ''; template += '<ul>'; template += ' <li ng-repeat="task in tasks track by task.id">'; template += ' <span ng-bind="task.title"></span>'; template += ' <button ng-click="done()">Mark done</button>'; template += ' <button ng-click="remove()">Remove</button>'; template += ' </li>'; template += '</ul>'; return template; }; var TodoListDirective = function (Tasks) { return { restrict: 'E', // AEC scope: {}, template: getTemplate(), link: function (scope, element, attrs) { scope.tasks = Tasks; } }; }; TodoListDirective.$inject = ['Tasks']; definition.push(TodoListDirective); return definition; });
Fix MappingInstantiationException for no default constructor
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api; import java.io.Serializable; /** * A simple reference to another Facebook object without the complete set of object data. * @author Craig Walls */ @SuppressWarnings("serial") public class Reference extends FacebookObject implements Serializable { private final String id; private final String name; @SuppressWarnings("unused") private Reference() { this(null, null); } public Reference(String id) { this(id, null); } public Reference(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api; import java.io.Serializable; /** * A simple reference to another Facebook object without the complete set of object data. * @author Craig Walls */ @SuppressWarnings("serial") public class Reference extends FacebookObject implements Serializable { private final String id; private final String name; public Reference(String id) { this(id, null); } public Reference(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public String getName() { return name; } }
Update work around for disabling store caching
import Ember from 'ember'; import layout from './template'; export default Ember.Component.extend({ layout, store: Ember.inject.service(), internalState: Ember.inject.service(), leftTitle: null, leftView: null, leftPanelColor: null, leftModel: null, rightTitle: null, rightView: null, rightPanelColor: null, init() { this._super(...arguments); console.log("Left View = " + this.get("leftView")); console.log("Right View = " + this.get("rightView")); }, didRender() { }, actions: { onLeftModelChange: function (model) { this.set("leftModel", model); }, taleLaunched: function() { // TODO convert this interaction to use the wt-events service instead // Update right panel models let self = this; // NOTE: using store.query here as a work around to disable store.findAll caching this.get('store').query('instance', {}) .then(models => { self.set('rightModelTop', models); }); }, } });
import Ember from 'ember'; import layout from './template'; export default Ember.Component.extend({ layout, store: Ember.inject.service(), internalState: Ember.inject.service(), leftTitle: null, leftView: null, leftPanelColor: null, leftModel: null, rightTitle: null, rightView: null, rightPanelColor: null, init() { this._super(...arguments); console.log("Left View = " + this.get("leftView")); console.log("Right View = " + this.get("rightView")); }, didRender() { }, actions: { onLeftModelChange: function (model) { this.set("leftModel", model); }, taleLaunched: function() { // TODO convert this interaction to use the wholetale events service instead // Update model and test if the interface updates automatically let self = this; this.get('store').unloadAll('instance'); this.get('store').findAll('instance', { reload: true, adapterOptions: { queryParams:{sort: "created", sortdir: "-1", limit: "0"}} }) .then(models => { self.set('rightModelTop', models); }); }, } });
Change environment attribute name to datetime_format
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( datetime_format='%Y-%m-%d', ) def _now(self, timezone, datetime_format): datetime_format = datetime_format or self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno)
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.extend( date_format='%Y-%m-%d', ) def _now(self, timezone, date_format): date_format = date_format or self.environment.date_format return arrow.now(timezone).strftime(date_format) def parse(self, parser): lineno = next(parser.stream).lineno args = [parser.parse_expression()] if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) call = self.call_method('_now', args, lineno=lineno) return nodes.Output([call], lineno=lineno)
Allow cross-origin headers on dev builds
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_login import LoginManager from rauth import OAuth2Service app = Flask(__name__) BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) app.static_folder = os.path.join(BASE_FOLDER, 'static') app.config.from_pyfile('../config') mail = Mail(app) db = SQLAlchemy(app) lm = LoginManager(app) migrate = Migrate(app, db) app.config['SQLALC_INSTANCE'] = db app.config['MAILADDR'] = mail oauth_alveo = OAuth2Service( name='alveo', client_id=app.config['OAUTH_ALVEO_APPID'], client_secret=app.config['OAUTH_ALVEO_APPSEC'], authorize_url='https://example.com/oauth/authorize', access_token_url='https://example.com/oauth/access_token', base_url='https://example.com/' ) # Allow cross origin headers only on dev mode if app.config['DEVELOPMENT'] == True: @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') return response import application.views
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_mail import Mail from flask_login import LoginManager from rauth import OAuth2Service app = Flask(__name__) BASE_FOLDER = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..')) app.static_folder = os.path.join(BASE_FOLDER, 'static') app.config.from_pyfile('../config') mail = Mail(app) db = SQLAlchemy(app) lm = LoginManager(app) migrate = Migrate(app, db) app.config['SQLALC_INSTANCE'] = db app.config['MAILADDR'] = mail oauth_alveo = OAuth2Service( name='alveo', client_id=app.config['OAUTH_ALVEO_APPID'], client_secret=app.config['OAUTH_ALVEO_APPSEC'], authorize_url='https://example.com/oauth/authorize', access_token_url='https://example.com/oauth/access_token', base_url='https://example.com/' ) import application.views
Change version 0.1.4 to 0.1.5
from setuptools import setup from sys import version if version < '2.6.0': raise Exception("This module doesn't support any version less than 2.6") import sys sys.path.append("./test") with open('README.rst', 'r') as f: long_description = f.read() classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', "Programming Language :: Python", 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Python Modules' ] setup( author='Keita Oouchi', author_email='keita.oouchi@gmail.com', url = 'https://github.com/keitaoouchi/seleniumwrapper', name = 'seleniumwrapper', version = '0.1.5', package_dir={"":"src"}, packages = ['seleniumwrapper'], test_suite = "test_seleniumwrapper.suite", license='BSD License', classifiers=classifiers, description = 'selenium webdriver wrapper to make manipulation easier.', long_description=long_description, )
from setuptools import setup from sys import version if version < '2.6.0': raise Exception("This module doesn't support any version less than 2.6") import sys sys.path.append("./test") with open('README.rst', 'r') as f: long_description = f.read() classifiers = [ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', "Programming Language :: Python", 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Python Modules' ] setup( author='Keita Oouchi', author_email='keita.oouchi@gmail.com', url = 'https://github.com/keitaoouchi/seleniumwrapper', name = 'seleniumwrapper', version = '0.1.4', package_dir={"":"src"}, packages = ['seleniumwrapper'], test_suite = "test_seleniumwrapper.suite", license='BSD License', classifiers=classifiers, description = 'selenium webdriver wrapper to make manipulation easier.', long_description=long_description, )
Support to check the ast node is valid or not
/** * Using esprima JS parser to parse AST * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-27 */ /** Import esprima module */ var esprima = require('esprima'); /** * JS parser * @constructor */ function JSParser() { } /* start-public-methods */ /** * Check if the node is an AST node * @param {Object} ast An AST node * @returns {Boolean} True if it\'s, false otherwise */ JSParser.prototype.isValidAST = function (ast) { "use strict"; return (typeof ast === 'object') && !!ast.type; }; /** * Parse the code to AST with specified options for esprima parser or use the default range and loc options * @param {String} code Content of source code * @param {Object} [options] Option object * @returns {Object} Parsed JS AST */ JSParser.prototype.parseAST = function (code, options) { 'use strict'; var optionObj = options || {range: true, loc: true}; if (!optionObj.range) { optionObj.range = true; } if (!optionObj.loc) { optionObj.loc = true; } return esprima.parse(code, optionObj); }; /* end-public-methods */ var parser = new JSParser(); module.exports = parser;
/** * Using esprima JS parser to parse AST * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-07-27 */ /** Import esprima module */ var esprima = require('esprima'); /** * JS parser * @constructor */ function JSParser() { } /** * Parse the code to AST with specified options for esprima parser or use the default range and loc options * @param {String} code Content of source code * @param {Object} [options] Option object * @returns {Object} Parsed JS AST */ JSParser.prototype.parseAST = function (code, options) { 'use strict'; var optionObj = options || {range: true, loc: true}; if (!optionObj.range) { optionObj.range = true; } if (!optionObj.loc) { optionObj.loc = true; } return esprima.parse(code, optionObj); }; var parser = new JSParser(); module.exports = parser;
Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory.
import tempfile, os import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh']) os.rmdir(tmpd)
import tempfile, os import nose.tools as nt ip = get_ipython() ip.magic('load_ext storemagic') def test_store_restore(): ip.user_ns['foo'] = 78 ip.magic('alias bar echo "hello"') tmpd = tempfile.mkdtemp() ip.magic('cd ' + tmpd) ip.magic('store foo') ip.magic('store bar') # Check storing nt.assert_equal(ip.db['autorestore/foo'], 78) nt.assert_in('bar', ip.db['stored_aliases']) # Remove those items ip.user_ns.pop('foo', None) ip.alias_manager.undefine_alias('bar') ip.magic('cd -') ip.user_ns['_dh'][:] = [] # Check restoring ip.magic('store -r') nt.assert_equal(ip.user_ns['foo'], 78) nt.assert_in('bar', ip.alias_manager.alias_table) nt.assert_in(tmpd, ip.user_ns['_dh']) os.rmdir(tmpd)
Fix syntax bug on stream emptying
import time import numpy as np import pyaudio import config def start_stream(callback): p = pyaudio.PyAudio() frames_per_buffer = int(config.MIC_RATE / config.FPS) stream = p.open(format=pyaudio.paInt16, channels=1, rate=config.MIC_RATE, input=True, frames_per_buffer=frames_per_buffer) overflows = 0 prev_ovf_time = time.time() while True: try: y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16) y = y.astype(np.float32) stream.read(stream.get_read_available(), exception_on_overflow=False) callback(y) except IOError: overflows += 1 if time.time() > prev_ovf_time + 1: prev_ovf_time = time.time() print('Audio buffer has overflowed {} times'.format(overflows)) stream.stop_stream() stream.close() p.terminate()
import time import numpy as np import pyaudio import config def start_stream(callback): p = pyaudio.PyAudio() frames_per_buffer = int(config.MIC_RATE / config.FPS) stream = p.open(format=pyaudio.paInt16, channels=1, rate=config.MIC_RATE, input=True, frames_per_buffer=frames_per_buffer) overflows = 0 prev_ovf_time = time.time() while True: try: y = np.fromstring(stream.read(frames_per_buffer, exception_on_overflow=False), dtype=np.int16) y = y.astype(np.float32) stream.read(get_read_available(), exception_on_overflow=False) callback(y) except IOError: overflows += 1 if time.time() > prev_ovf_time + 1: prev_ovf_time = time.time() print('Audio buffer has overflowed {} times'.format(overflows)) stream.stop_stream() stream.close() p.terminate()
Fix mac - OS buttons overlap with back/forward buttons requies https://github.com/brave/electron/commit/92c9e25
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' /** * Get list of styles which should be applied to root window div * return array of strings (each being a class name) */ module.exports.getPlatformStyles = () => { const platform = process.platform() const styleList = ['platform--' + platform] switch (platform) { case 'win32': if (process.platformVersion() === 'win7') { styleList.push('win7') } else { styleList.push('win10') } } return styleList } module.exports.isDarwin = () => { return process.platform() === 'darwin' || navigator.platform === 'MacIntel' } module.exports.isWindows = () => { return process.platform() === 'win32' || navigator.platform === 'Win32' }
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' const os = require('os') /** * Get list of styles which should be applied to root window div * return array of strings (each being a class name) */ module.exports.getPlatformStyles = () => { const platform = os.platform() const styleList = ['platform--' + platform] switch (platform) { case 'win32': if (/6.1./.test(os.release())) { styleList.push('win7') } else { styleList.push('win10') } } return styleList } module.exports.isDarwin = () => { return os.platform() === 'darwin' || navigator.platform === 'MacIntel' } module.exports.isWindows = () => { return os.platform() === 'win32' || navigator.platform === 'Win32' }
Make linter know when JSX is using React variable
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "installedESLint": true, "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "react/jsx-uses-vars": 1, "react/jsx-uses-react": [1], "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "never" ] } };
module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "installedESLint": true, "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "react/jsx-uses-vars": 1, "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "never" ] } };
Fix for adjust parent method definition
<?php /* * This file is part of the Eulogix\Cool package. * * (c) Eulogix <http://www.eulogix.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Eulogix\Cool\Lib\Database\Propel\generator\platform; /** * @author Pietro Baricco <pietro@eulogix.com> */ class PgsqlPlatform extends \PgsqlPlatform { /** * Trivial modifications that avoids spitting an error like * psql:/tmp/SQLlMdpMc:317: ERROR: sequence "XXXX_id_seq" does not exist * * @param \Table $table * @return string */ protected function getDropSequenceDDL( $table) { if ($table->getIdMethod() == \IDMethod::NATIVE && $table->getIdMethodParameters() != null) { $pattern = " DROP SEQUENCE IF EXISTS %s; "; return sprintf($pattern, $this->quoteIdentifier(strtolower($this->getSequenceName($table))) ); } } }
<?php /* * This file is part of the Eulogix\Cool package. * * (c) Eulogix <http://www.eulogix.com/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Eulogix\Cool\Lib\Database\Propel\generator\platform; /** * @author Pietro Baricco <pietro@eulogix.com> */ class PgsqlPlatform extends \PgsqlPlatform { /** * Trivial modifications that avoids spitting an error like * psql:/tmp/SQLlMdpMc:317: ERROR: sequence "XXXX_id_seq" does not exist * * @param \Table $table * @return string */ protected function getDropSequenceDDL(\Table $table) { if ($table->getIdMethod() == \IDMethod::NATIVE && $table->getIdMethodParameters() != null) { $pattern = " DROP SEQUENCE IF EXISTS %s; "; return sprintf($pattern, $this->quoteIdentifier(strtolower($this->getSequenceName($table))) ); } } }
1.0.0: Change URL to point to trac-hacks.org
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2010 Sebastian Krysmanski # Copyright (C) 2012 Greg Lavallee # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # from setuptools import setup PACKAGE = 'TicketGuidelinesPlugin' VERSION = '1.0.0' setup( name=PACKAGE, version=VERSION, author='Sebastian Krysmanski', url='https://trac-hacks.org/wiki/TicketGuidelinesPlugin', description="Adds your ticket guidelines to the ticket view. The " "guidelines are specified in the wiki pages " "'TicketGuidelines/NewShort' and " "'TicketGuidelines/ModifyShort'.", keywords='trac plugin', license='Modified BSD', install_requires=['Trac'], packages=['ticketguidelines'], package_data={'ticketguidelines': ['htdocs/*']}, entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE}, )
# -*- coding: utf-8 -*- # # Copyright (C) 2009-2010 Sebastian Krysmanski # Copyright (C) 2012 Greg Lavallee # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. # from setuptools import setup PACKAGE = 'TicketGuidelinesPlugin' VERSION = '1.0.0' setup( name=PACKAGE, version=VERSION, author='Sebastian Krysmanski', url='https://github.com/trac-hacks/TicketGuidelinesPlugin', description="Adds your ticket guidelines to the ticket view. The " "guidelines are specified in the wiki pages " "'TicketGuidelines/NewShort' and " "'TicketGuidelines/ModifyShort'.", keywords='trac plugin', license='Modified BSD', install_requires=['Trac'], packages=['ticketguidelines'], package_data={'ticketguidelines': ['htdocs/*']}, entry_points={'trac.plugins': '%s = ticketguidelines.web_ui' % PACKAGE}, )
Include assertFileExists and assertFileNotExists as public.
<?php namespace Codeception\Module; use Codeception\Module as CodeceptionModule; use \Codeception\Util\Shared\Asserts as SharedAsserts; /** * Special module for using asserts in your tests. * */ class Asserts extends CodeceptionModule { use SharedAsserts { assertEquals as public; assertNotEquals as public; assertSame as public; assertNotSame as public; assertGreaterThan as public; assertGreaterThen as public; assertGreaterThanOrEqual as public; assertGreaterThenOrEqual as public; assertLessThan as public; assertLessThanOrEqual as public; assertContains as public; assertNotContains as public; assertRegExp as public; assertNotRegExp as public; assertEmpty as public; assertNotEmpty as public; assertNull as public; assertNotNull as public; assertTrue as public; assertFalse as public; assertFileExists as public; assertFileNotExists as public; fail as public; } }
<?php namespace Codeception\Module; use Codeception\Module as CodeceptionModule; use \Codeception\Util\Shared\Asserts as SharedAsserts; /** * Special module for using asserts in your tests. * */ class Asserts extends CodeceptionModule { use SharedAsserts { assertEquals as public; assertNotEquals as public; assertSame as public; assertNotSame as public; assertGreaterThan as public; assertGreaterThen as public; assertGreaterThanOrEqual as public; assertGreaterThenOrEqual as public; assertLessThan as public; assertLessThanOrEqual as public; assertContains as public; assertNotContains as public; assertRegExp as public; assertNotRegExp as public; assertEmpty as public; assertNotEmpty as public; assertNull as public; assertNotNull as public; assertTrue as public; assertFalse as public; fail as public; } }
Fix broken path on CSV converter form
<?php include 'header_meta_inc_view.php';?> <?php include 'header_inc_view.php';?> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-lg-12"> <h2>CSV Converter</h2> <form action="<?php echo site_url(); ?>/datagov/csv_to_json" method="post" role="form" enctype="multipart/form-data"> <div class="form-group"> <label for="datajson">Upload a CSV File</label> <input type="file" name="csv_upload"> </div> <div class="form-group"> <input type="submit" value="Convert" class="btn btn-primary"> </div> </form> </div> </div> <?php include 'footer.php'; ?>
<?php include 'header_meta_inc_view.php';?> <?php include 'header_inc_view.php';?> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-lg-12"> <h2>CSV Converter</h2> <form action="<?php echo site_url(); ?>/csv_to_json" method="post" role="form" enctype="multipart/form-data"> <div class="form-group"> <label for="datajson">Upload a CSV File</label> <input type="file" name="csv_upload"> </div> <div class="form-group"> <input type="submit" value="Convert" class="btn btn-primary"> </div> </form> </div> </div> <?php include 'footer.php'; ?>